Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

index.tsx

391 lines14.4 KB

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