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