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