Open History to see the last commit
1import { useState } from 'react'
2import { Provenance } from '#/components/provenance.tsx'
3import { createFileRoute, useNavigate } from '@tanstack/react-router'
4import { createServerFn } from '@tanstack/react-start'
5
6import {
7 JsonPane,
8 MetaStrip,
9 ReqLine,
10 SiteFooter,
11 SiteNav,
12 ViewToggle,
13} from '#/components/site.tsx'
14import type { ResourceView } from '#/components/site.tsx'
15import { activities } from '#/db/schema.ts'
16import type { Activity } from '#/db/schema.ts'
17import type { ModelRow } from '#/lib/completeness.ts'
18import type { SerializableModel } from '#/lib/json.ts'
19import { timeAgo, shortDate } from '#/lib/time.ts'
20
21/** Rows shown / serialized per page-load; refine with filters beyond this. */
22const MAX_ROWS = 200
23
24interface CatalogSearch {
25 provider?: string
26 activity?: Activity
27 q?: string
28}
29
30/** Chat facts filled of those scored for one row; null for non-chat rows. */
31interface RowCompleteness {
32 filled: number
33 needed: number
34 missing: Array<string>
35}
36
37interface CatalogData {
38 count: number
39 /** By model id, for the rows shown. */
40 completeness: Record<string, RowCompleteness>
41 models: Array<SerializableModel>
42 providers: Array<string>
43 truncated: boolean
44}
45
46const getCatalog = createServerFn({ method: 'GET' })
47 .inputValidator((filters: CatalogSearch) => filters)
48 .handler(async ({ data }): Promise<CatalogData> => {
49 const { env } = await import('cloudflare:workers')
50 const { getDb } = await import('#/db/index.ts')
51 const { listModelsCatalog, knownProviderIds } =
52 await import('#/server/catalog.ts')
53 const { FACT_KEYS, buildReport } = await import('#/lib/completeness.ts')
54 const { sourceSilentLedger } = await import('#/server/source-silent.ts')
55 const db = getDb(env)
56 // The second read carries full rate cards: the score reads them, and the
57 // page shows the compact rows the API serves.
58 const [result, scored, providers] = await Promise.all([
59 listModelsCatalog(db, data),
60 listModelsCatalog(db, { ...data, pricing: true }),
61 knownProviderIds(db),
62 ])
63 const completeness: Record<string, RowCompleteness> = {}
64 for (const row of scored.models.slice(0, MAX_ROWS)) {
65 if (row.activity !== 'chat') continue
66 // Same scorer as the front page and `bun run gap:report`, one row at a time.
67 const [report] = buildReport(
68 [row as unknown as ModelRow],
69 sourceSilentLedger,
70 ).providers
71 if (!report) continue
72 const counted = FACT_KEYS.filter(
73 (key) =>
74 !report.silent.includes(key) &&
75 report.facts[key].need - (report.modelSilent?.[key] ?? 0) > 0,
76 )
77 const missing = counted.filter((key) => report.facts[key].have === 0)
78 completeness[row.id] = {
79 filled: counted.length - missing.length,
80 needed: counted.length,
81 missing,
82 }
83 }
84 return {
85 count: result.count,
86 completeness,
87 // drizzle json columns are typed unknown; the values are plain JSON
88 models: result.models.slice(
89 0,
90 MAX_ROWS,
91 ) as unknown as Array<SerializableModel>,
92 providers,
93 truncated: result.count > MAX_ROWS,
94 }
95 })
96
97export const Route = createFileRoute('/models/')({
98 validateSearch: (search: Record<string, unknown>): CatalogSearch => ({
99 provider:
100 typeof search.provider === 'string' && search.provider !== ''
101 ? search.provider
102 : undefined,
103 activity: (activities as ReadonlyArray<string>).includes(
104 String(search.activity),
105 )
106 ? (search.activity as Activity)
107 : undefined,
108 q: typeof search.q === 'string' && search.q !== '' ? search.q : undefined,
109 }),
110 loaderDeps: ({ search }) => search,
111 loader: ({ deps }) => getCatalog({ data: deps }),
112 component: ModelsCatalog,
113})
114
115function queryString(search: CatalogSearch): string {
116 const params = new URLSearchParams()
117 if (search.provider) params.set('provider', search.provider)
118 if (search.activity) params.set('activity', search.activity)
119 if (search.q) params.set('q', search.q)
120 const qs = params.toString()
121 return qs === '' ? '' : `?${qs}`
122}
123
124function completenessCell(row: RowCompleteness | undefined): string {
125 return row ? `${String(row.filled)}/${String(row.needed)}` : '—'
126}
127
128function completenessTitle(row: RowCompleteness | undefined): string {
129 if (!row) return 'Scored for chat models only'
130 return row.missing.length === 0
131 ? 'Every scored fact is filled'
132 : `Missing: ${row.missing.join(', ')}`
133}
134
135/** Model rawIds can contain slashes (FAL); those detail URLs use the slug id. */
136export function modelHref(model: SerializableModel): string {
137 const id = model.rawId.includes('/') ? model.id : model.rawId
138 return `/models/${model.provider}/${id}`
139}
140
141function ModelsCatalog() {
142 const data = Route.useLoaderData()
143 const search = Route.useSearch()
144 const navigate = useNavigate({ from: Route.fullPath })
145 const [view, setView] = useState<ResourceView>('readable')
146 const [q, setQ] = useState(search.q ?? '')
147
148 const qs = queryString(search)
149 const apiPath = `/v1/models${qs}`
150 const jsonBody = JSON.stringify(
151 { count: data.count, models: data.models },
152 null,
153 2,
154 )
155
156 const setSearch = (patch: Partial<CatalogSearch>) => {
157 void navigate({
158 search: (prev: CatalogSearch): CatalogSearch => {
159 const next = { ...prev, ...patch }
160 return {
161 provider: next.provider || undefined,
162 activity: next.activity || undefined,
163 q: next.q || undefined,
164 }
165 },
166 })
167 }
168
169 const selectClasses =
170 'hairline rounded-[3px] border bg-paper-raised px-2.5 py-1.5 font-mono text-xs text-ink outline-none transition-colors focus:border-rule-strong'
171
172 return (
173 <div className="min-h-screen text-ink">
174 <SiteNav active="models" />
175 <main className="mx-auto max-w-[1080px] px-6 pb-16">
176 <ReqLine
177 path={
178 <>
179 /v1/models
180 {qs === '' ? null : <span className="text-ink-faint">{qs}</span>}
181 </>
182 }
183 copyUrl={`https://modelschemas.com${apiPath}`}
184 right={<ViewToggle view={view} onChange={setView} />}
185 />
186 <MetaStrip
187 items={[
188 ['count', String(data.count)],
189 ['cache', 'swr'],
190 ['shown', data.truncated ? `first ${String(MAX_ROWS)}` : 'all'],
191 ]}
192 />
193
194 {view === 'json' ? (
195 <JsonPane
196 title={`application/json · 200 OK${data.truncated ? ` · trimmed to ${String(MAX_ROWS)} models` : ''}`}
197 json={jsonBody}
198 note={
199 <>
200 identical body to{' '}
201 <code>curl https://modelschemas.com{apiPath}</code>
202 {data.truncated ? ' — the API returns the full list' : null}
203 </>
204 }
205 />
206 ) : (
207 <>
208 <div className="mb-3.5 flex flex-wrap items-center gap-2 font-mono text-xs">
209 <select
210 aria-label="Filter by provider"
211 className={selectClasses}
212 value={search.provider ?? ''}
213 onChange={(event) => {
214 setSearch({ provider: event.target.value || undefined })
215 }}
216 >
217 <option value="">provider=any</option>
218 {data.providers.map((p) => (
219 <option key={p} value={p}>
220 provider={p}
221 </option>
222 ))}
223 </select>
224 <select
225 aria-label="Filter by activity"
226 className={selectClasses}
227 value={search.activity ?? ''}
228 onChange={(event) => {
229 setSearch({
230 activity: (event.target.value || undefined) as
231 | Activity
232 | undefined,
233 })
234 }}
235 >
236 <option value="">activity=any</option>
237 {activities.map((a) => (
238 <option key={a} value={a}>
239 activity={a}
240 </option>
241 ))}
242 </select>
243 <form
244 className="contents"
245 onSubmit={(event) => {
246 event.preventDefault()
247 setSearch({ q: q || undefined })
248 }}
249 >
250 <input
251 aria-label="Filter models by text"
252 className={`${selectClasses} w-52`}
253 placeholder="q=filter models…"
254 value={q}
255 onChange={(event) => setQ(event.target.value)}
256 onBlur={() => setSearch({ q: q || undefined })}
257 />
258 </form>
259 </div>
260
261 <div className="figure overflow-x-auto">
262 <table className="dtable">
263 <thead>
264 <tr>
265 <th>model id</th>
266 <th>display name</th>
267 <th className="max-sm:hidden">activity</th>
268 <th title="Has a price card">priced</th>
269 <th
270 className="num max-sm:hidden"
271 title="Chat completeness: chat facts filled of those scored for this model. Facts the provider does not publish are left out."
272 >
273 chat
274 </th>
275 <th className="num">first seen</th>
276 <th className="num">last seen</th>
277 <th aria-label="links" />
278 </tr>
279 </thead>
280 <tbody>
281 {data.models.length === 0 ? (
282 <tr>
283 <td colSpan={8} className="text-ink-faint">
284 No models match these filters — clear a filter or
285 broaden <code>q</code>.
286 </td>
287 </tr>
288 ) : (
289 data.models.map((m) => (
290 <tr key={m.id}>
291 <td className="font-mono text-[12.5px]">
292 <a
293 className="font-medium text-ink hover:text-tok-blue"
294 href={modelHref(m)}
295 >
296 {m.rawId}
297 </a>
298 </td>
299 <td>{m.displayName ?? '—'}</td>
300 <td className="font-mono text-xs text-ink-soft max-sm:hidden">
301 {m.activity ?? '—'}
302 </td>
303 <td
304 className={
305 m.pricing === null
306 ? 'text-ink-faint'
307 : 'text-tok-green'
308 }
309 aria-label={
310 m.pricing === null ? 'not priced' : 'priced'
311 }
312 >
313 {m.pricing === null ? '✗' : '✓'}
314 </td>
315 <td
316 className="num text-ink-soft max-sm:hidden"
317 title={completenessTitle(data.completeness[m.id])}
318 >
319 {completenessCell(data.completeness[m.id])}
320 </td>
321 <td className="num text-ink-faint">
322 {shortDate(m.firstSeenAt)}
323 </td>
324 <td className="num text-ink-faint">
325 {timeAgo(m.lastSeenAt)}
326 </td>
327 <td className="font-mono text-xs">
328 <a className="press-link" href={modelHref(m)}>
329 detail →
330 </a>
331 <div className="mt-1">
332 <Provenance facts={m.factSources} compact />
333 </div>
334 </td>
335 </tr>
336 ))
337 )}
338 </tbody>
339 </table>
340 </div>
341 {data.truncated ? (
342 <p className="mt-2.5 font-mono text-xs text-ink-faint">
343 showing {MAX_ROWS} of {data.count} — narrow with the filters
344 above, or fetch the full list from{' '}
345 <a className="press-link" href={apiPath}>
346 {apiPath}
347 </a>
348 </p>
349 ) : null}
350 </>
351 )}
352 </main>
353 <SiteFooter />
354 </div>
355 )
356}