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

huggingface.ts

496 lines16.7 KB

1/**
2 * Hugging Face Inference Providers — the public router model list.
3 *
4 * A router row is served by several hosts. The bare model id routes to
5 * `:fastest`: the live provider with the highest `throughput` (tokens per
6 * second). That entry's context, price, and flags are the row — the bill
7 * and the window a caller gets with no suffix. `:cheapest`, `:preferred`,
8 * and a named provider are other routes, not this row. A tie stores a fact
9 * only when the tied entries agree. An entry with no throughput was not
10 * probed, so it is not a candidate and does not veto the probed route.
11 * When no live entry was probed, a fact is stored only when every live
12 * entry states it and they agree. Nothing is averaged. Policy:
13 * https://huggingface.co/docs/inference-providers/index
14 * Field meanings and units:
15 * https://huggingface.co/docs/inference-providers/hub-api
16 *
17 * A price the chosen route does not state (missing, zero, or an `is_free`
18 * promo) is `absent: cleared`, not just null: the listing was read and
19 * says so, so the poller drops a stored card instead of keeping it as a
20 * parser miss. A price that could not be read is never `cleared`: one odd
21 * entry makes its row's price `unavailable` (the stored card stays) and is
22 * reported as a docs failure, and a listing-wide change throws
23 * (`UNREAD_PRICE_SHARE`).
24 *
25 * The request schema is Hugging Face's own chat-completion JSON Schema
26 * (huggingface.js `tasks`), wrapped into one OpenAPI path at sync time.
27 * It is `generated`, so its fields are not walked onto rows: a shared
28 * router schema does not show that every routed model accepts every field.
29 */
30import {
31 HF_CHAT_GUIDE,
32 nativeReasoningCapability,
33 parseHfHostedReasoning,
34} from '../native-host-reasoning.ts'
35import { docsReport, docsRun, tryDocs, unavailable } from '../model-facts.ts'
36import type { Activity } from '#/db/schema.ts'
37​
38import { hyperbolicListingCard } from '../catalog-prices.ts'
39import { bearerConnect } from '../connect.ts'
40import { namespacedUpstreamIdentity } from '../upstream-model.ts'
41import type { DocsRun } from '../model-facts.ts'
42import { fetchJson, fetchText, sha256Text } from '../types.ts'
43import type {
44 FactSource,
45 ListModelsResult,
46 ModelFactSources,
47 ModelInfo,
48 OpenApiDocument,
49 ProviderConfig,
50 ProviderSecrets,
51 SpecFetchResult,
52} from '../types.ts'
53​
54export const HUGGINGFACE_MODELS_URL = 'https://router.huggingface.co/v1/models'
55const SPEC_DIR = 'packages/tasks/src/tasks/chat-completion/spec'
56/** The two files `fetchSpec` reads: `input.json` and `output.json`. */
57export const HUGGINGFACE_SPEC_RAW_URL = `https://raw.githubusercontent.com/huggingface/huggingface.js/main/${SPEC_DIR}`
58export const HUGGINGFACE_SPEC_URL = `https://github.com/huggingface/huggingface.js/tree/main/${SPEC_DIR}`
59​
60const SERVER_URL = 'https://router.huggingface.co'
61const CHAT_PATH = '/v1/chat/completions'
62const FETCH_TIMEOUT_MS = 30_000
63​
64type Row = Record<string, unknown>
65​
66function isRecord(value: unknown): value is Row {
67 return typeof value === 'object' && value !== null && !Array.isArray(value)
69​
70function stringList(value: unknown): Array<string> | null {
71 if (!Array.isArray(value) || value.length === 0) return null
72 const out: Array<string> = []
73 for (const item of value) {
74 if (typeof item !== 'string') return null
75 out.push(item)
76 }
77 return out
79​
80function activityFor(output: Array<string> | null): Activity | null {
81 if (!output) return null
82 if (output.includes('image') && !output.includes('text')) return 'image'
83 if (output.includes('text')) return 'chat'
84 if (output.includes('embedding') || output.includes('embeddings')) {
85 return 'embeddings'
86 }
87 if (output.includes('audio')) return 'audio'
88 return null
90​
91/**
92 * Every provider entry. A list in another shape throws: read as "no
93 * providers" it would say the price is gone and clear a stored card.
94 */
95function routes(providers: unknown): Array<Row> {
96 if (Array.isArray(providers) && providers.every(isRecord)) return providers
97 throw new Error('huggingface: a providers list is in an unread shape')
99​
100/** The one value every entry states, or null. */
101function agreed<T>(route: Array<Row>, read: (p: Row) => T | null): T | null {
102 const [first, ...rest] = route.map(read)
103 if (first === undefined || first === null) return null
104 const key = JSON.stringify(first)
105 return rest.every((value) => JSON.stringify(value) === key) ? first : null
107​
108function providerId(p: Row): string {
109 const id = p.provider
110 if (typeof id !== 'string' || id.length === 0 || /[[\],\s]/.test(id)) {
111 throw new Error('huggingface: a provider entry has no provider id')
112 }
113 return id
115​
116/** Probe throughput in tokens per second, or null when this entry has none. */
117function throughput(p: Row): number | null {
118 const n = p.throughput
119 return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : null
121​
122/**
123 * The bare model id's route, and the `providers…` prefix for its fact path.
124 * Live entries at the highest throughput, or every live entry when none
125 * was probed. An `error` host is not a route.
126 */
127function defaultRoute(route: Array<Row>): {
128 entries: Array<Row>
129 path: string
130} {
131 for (const entry of route) {
132 providerId(entry)
133 if (entry.status !== 'live' && entry.status !== 'error') {
134 throw new Error(
135 `huggingface: provider ${JSON.stringify(entry.provider)} status is in an unread shape`,
136 )
137 }
138 }
139 const live = route.filter((entry) => entry.status === 'live')
140 let best: number | null = null
141 for (const entry of live) {
142 const n = throughput(entry)
143 if (n !== null && (best === null || n > best)) best = n
144 }
145 if (best === null) return { entries: live, path: 'providers[]' }
146 const winners = live.filter((entry) => throughput(entry) === best)
147 const names = [...new Set(winners.map(providerId))].sort()
148 return { entries: winners, path: `providers[provider=${names.join(',')}]` }
150​
151function contextLength(p: Row): number | null {
152 const n = p.context_length
153 return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null
155​
156/** The listing carries float noise (`0.030000000000000002`). */
157const exact = (n: number) => Number(n.toPrecision(12))
158​
159/**
160 * USD per million tokens, or null when the entry states no price: its
161 * `pricing` is missing or null, quotes zero, or is an `is_free` promo (not
162 * the standard price). A `pricing` in any other shape throws. Null means
163 * "unsettled" and clears a stored card, so it must never mean "could not
164 * read".
165 */
166function price(p: Row): { input: number; output: number } | null {
167 if (p.pricing == null) return null
168 const { input, output } = isRecord(p.pricing) ? p.pricing : {}
169 if (
170 typeof input !== 'number' ||
171 typeof output !== 'number' ||
172 !(input >= 0 && output >= 0)
173 ) {
174 throw new Error(
175 `huggingface: the price of provider entry ${JSON.stringify(p.provider)} is in an unread shape`,
176 )
177 }
178 return p.is_free !== true && input > 0 && output > 0
179 ? { input: exact(input), output: exact(output) }
180 : null
182​
183const flag = (key: string) => (p: Row) => {
184 const value = p[key]
185 return typeof value === 'boolean' ? value : null
187​
188function listed(path: string): FactSource {
189 return { derivation: 'listing', sourceUrl: HUGGINGFACE_MODELS_URL, path }
191​
192async function routeFacts(
193 rawId: string,
194 route: Array<Row>,
195 run: DocsRun,
196): Promise<
197 Pick<
198 ModelInfo,
199 | 'contextWindow'
200 | 'pricing'
201 | 'capabilities'
202 | 'unsupportedCapabilities'
203 | 'factSources'
204 | 'absent'
205 >
206> {
207 const selected = defaultRoute(route)
208 const contextWindow = agreed(selected.entries, contextLength)
209 // One entry whose price cannot be read withholds this row's price only,
210 // including a host that is not the default route.
211 const read = await tryDocs(run, `${HUGGINGFACE_MODELS_URL}#${rawId}`, () =>
212 Promise.resolve().then(() => {
213 for (const entry of route) price(entry)
214 return { quote: agreed(selected.entries, price) }
215 }),
216 )
217 const quote = read?.quote ?? null
218 const pricing = quote
219 ? await hyperbolicListingCard(
220 quote.input,
221 quote.output,
222 HUGGINGFACE_MODELS_URL,
223 )
224 : null
225 // The flag list reads "absent = unsupported", so it is stored only when
226 // both flags are settled on the chosen route.
227 const tools = agreed(selected.entries, flag('supports_tools'))
228 const structured = agreed(
229 selected.entries,
230 flag('supports_structured_output'),
231 )
232 const capabilities =
233 tools === null || structured === null
234 ? null
235 : [
236 ...(tools ? ['tools'] : []),
237 ...(structured ? ['structured_outputs', 'response_format'] : []),
238 ]
239​
240 // A no needs no second flag settled: every host on the chosen route
241 // states it. An unset structured-output flag says nothing about plain
242 // `response_format`.
243 const unsupported = [
244 ...(tools === false ? ['tools'] : []),
245 ...(structured === false ? ['structured_outputs'] : []),
246 ]
247​
248 const at = (name: string) => listed(`${selected.path}.${name}`)
249 const factSources: ModelFactSources = {}
250 if (contextWindow !== null) factSources.contextWindow = at('context_length')
251 if (pricing !== null) factSources.pricing = at('pricing')
252 const sourced = [...(capabilities ?? []), ...unsupported]
253 if (sourced.length > 0) {
254 factSources.capabilities = Object.fromEntries(
255 sourced.map((name) => [
256 name,
257 at(name === 'tools' ? 'supports_tools' : 'supports_structured_output'),
258 ]),
259 )
260 }
261 return {
262 contextWindow,
263 pricing,
264 capabilities,
265 unsupportedCapabilities: unsupported.length > 0 ? unsupported : null,
266 factSources,
267 ...(pricing === null
268 ? { absent: { pricing: read ? 'cleared' : 'unavailable' } }
269 : {}),
270 }
272​
273/**
274 * When more than this share of the entries that carry a `pricing` value
275 * cannot be read, the listing has changed shape: throw, so the poll fails
276 * and no price moves. At or under it the odd entries are theirs alone.
277 */
278const UNREAD_PRICE_SHARE = 0.1
279​
280export async function parseHuggingFaceModels(
281 payload: unknown,
282): Promise<Required<Pick<ListModelsResult, 'models' | 'docsFailures'>>> {
283 if (!isRecord(payload) || !Array.isArray(payload.data)) {
284 throw new Error('huggingface: models payload has no data array')
285 }
286 const models: Array<ModelInfo> = []
287 const run = docsRun()
288 let stated = 0
289 let unread = 0
290 let quotes = 0
291 for (const row of payload.data) {
292 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
293 continue
294 }
295 const route = routes(row.providers)
296 for (const p of route) {
297 if (p.pricing == null) continue
298 stated++
299 try {
300 if (price(p) !== null) quotes++
301 } catch {
302 unread++
303 }
304 }
305 const architecture = isRecord(row.architecture) ? row.architecture : null
306 const input = architecture
307 ? stringList(architecture.input_modalities)
308 : null
309 const output = architecture
310 ? stringList(architecture.output_modalities)
311 : null
312 models.push({
313 rawId: row.id,
314 activity: activityFor(output),
315 modalities: input && output ? { input, output } : null,
316 ...(await routeFacts(row.id, route, run)),
317 releasedAt:
318 typeof row.created === 'number' && row.created > 0 ? row.created : null,
319 })
320 }
321 if (models.length === 0) {
322 throw new Error('huggingface: models payload listed no ids')
323 }
324 // Most entries quote a price. None at all is a listing that moved its
325 // prices, not a router where every host stopped charging.
326 if (unread > stated * UNREAD_PRICE_SHARE) {
327 throw new Error(
328 `huggingface: ${String(unread)} of ${String(stated)} provider prices are in an unread shape`,
329 )
330 }
331 if (quotes === 0) {
332 throw new Error('huggingface: no provider entry states a price')
333 }
334 return { models, docsFailures: docsReport(run) }
336​
337async function listModels(
338 _env: ProviderSecrets,
339 kv?: KVNamespace,
340): Promise<ListModelsResult> {
341 const payload = await fetchJson(HUGGINGFACE_MODELS_URL, {
342 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
343 })
344 const catalog = await parseHuggingFaceModels(payload)
345 // The listing above is never wrapped. This guide is the only native
346 // statement of which hosted models reason. A missing section throws
347 // inside the parser; `tryDocs` keeps that throw off the poll, reports
348 // it, and the rows keep the stored reasoning object.
349 const guide = docsRun()
350 const doc = await tryDocs(guide, HF_CHAT_GUIDE, (cached) =>
351 cached(kv, HF_CHAT_GUIDE, async () => {
352 const html = await fetchText(HF_CHAT_GUIDE, {
353 signal: AbortSignal.timeout(30_000),
354 })
355 return { ids: parseHfHostedReasoning(html), hash: await sha256Text(html) }
356 }),
357 )
358 const reported = docsReport(guide)
359 const docsFailures = {
360 failed: catalog.docsFailures.failed + reported.failed,
361 skipped: catalog.docsFailures.skipped + reported.skipped,
362 first: [...catalog.docsFailures.first, ...reported.first].slice(0, 5),
363 }
364 if (!doc) {
365 return {
366 ...catalog,
367 docsFailures,
368 models: catalog.models.map((model) => ({
369 ...model,
370 absent: { ...model.absent, ...unavailable('reasoning').absent },
371 })),
372 }
373 }
374 const ids = new Set(doc.ids)
375 return {
376 ...catalog,
377 docsFailures,
378 models: catalog.models.map((model) =>
379 ids.has(model.rawId)
380 ? nativeReasoningCapability(model, {
381 derivation: 'docs-derived',
382 sourceUrl: HF_CHAT_GUIDE,
383 sourceHash: doc.hash,
384 path: 'Recommended models; explicit reasoning description',
385 })
386 : model,
387 ),
388 }
390​
391/**
392 * One published schema file as OpenAPI components: the root under `title`,
393 * its `$defs` beside it. Throws on anything that is not that file.
394 */
395function components(
396 text: string,
397 title: string,
398 property: string,
399): Record<string, unknown> {
400 let schema: unknown
401 try {
402 schema = JSON.parse(text.replaceAll('"#/$defs/', '"#/components/schemas/'))
403 } catch {
404 throw new Error(`huggingface: ${title} schema is not JSON`)
405 }
406 if (
407 !isRecord(schema) ||
408 schema.title !== title ||
409 !isRecord(schema.properties) ||
410 !isRecord(schema.properties[property]) ||
411 !isRecord(schema.$defs) ||
412 title in schema.$defs
413 ) {
414 throw new Error(`huggingface: ${title} schema has an unexpected shape`)
415 }
416 const { $id: _id, $schema: _draft, $defs: defs, ...root } = schema
417 return { ...defs, [title]: root }
419​
420export function buildHuggingFaceSpec(
421 inputText: string,
422 outputText: string,
423): OpenApiDocument {
424 const input = components(inputText, 'ChatCompletionInput', 'messages')
425 const output = components(outputText, 'ChatCompletionOutput', 'choices')
426 const clash = Object.keys(input).filter((name) => name in output)
427 if (clash.length > 0) {
428 throw new Error(`huggingface: schema name clash: ${clash.join(', ')}`)
429 }
430 const json = (name: string) => ({
431 'application/json': { schema: { $ref: `#/components/schemas/${name}` } },
432 })
433 return {
434 openapi: '3.1.0',
435 info: { title: 'Hugging Face Inference Providers', version: '1' },
436 servers: [{ url: SERVER_URL }],
437 paths: {
438 [CHAT_PATH]: {
439 post: {
440 operationId: 'chatCompletion',
441 summary: 'Chat Completion',
442 requestBody: { required: true, content: json('ChatCompletionInput') },
443 responses: {
444 '200': {
445 description: 'Chat Completion Output',
446 content: json('ChatCompletionOutput'),
447 },
448 },
449 },
450 },
451 },
452 components: { schemas: { ...input, ...output } },
453 }
455​
456async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
457 const file = (name: string) =>
458 fetchText(`${HUGGINGFACE_SPEC_RAW_URL}/${name}`, {
459 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
460 })
461 const [input, output] = await Promise.all([
462 file('input.json'),
463 file('output.json'),
464 ])
465 // One document from two files: the hash is of their concatenation.
466 const hash = await sha256Text(`${input}${output}`)
467 return {
468 specs: [buildHuggingFaceSpec(input, output)],
469 sources: [{ url: HUGGINGFACE_SPEC_URL, hash }],
470 outputStrategy: 'post-200',
471 specRevision: hash,
472 }
474​
475export const provider: ProviderConfig = {
476 id: 'huggingface',
477 displayName: 'Hugging Face',
478 specSourceUrl: HUGGINGFACE_SPEC_URL,
479 modelsEndpoint: HUGGINGFACE_MODELS_URL,
480 defaultDerivation: 'generated',
481 // A router id is the Hub repo, `owner/name`, and `owned_by` repeats the
482 // owner on every row. The owner is the repo's publisher: a quantised
483 // re-upload names its uploader, which no provider claims.
484 upstreamModelIdentity: (rawId) =>
485 namespacedUpstreamIdentity(rawId, {
486 derivation: 'listing',
487 sourceUrl: HUGGINGFACE_MODELS_URL,
488 path: 'data[].id',
489 }),
490 connect: bearerConnect(SERVER_URL),
491 fetchSpec,
492 listModels,
493 classify: (path) => (path === CHAT_PATH ? 'chat' : null),
494 generationEndpointId: ({ activity }) =>
495 activity === 'chat' ? CHAT_PATH.slice(1) : null,