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