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

huggingface.test.ts

706 lines21.5 KB

1import hostDocs from '../fixtures/host-native-reasoning.json'
2import { readFileSync } from 'node:fs'
3​
4import { afterEach, describe, expect, it } from 'vitest'
5​
6import { classifyAndBundle } from '#/server/ingest/sync.ts'
7​
8import {
9 buildHuggingFaceSpec,
10 HUGGINGFACE_MODELS_URL,
11 HUGGINGFACE_SPEC_RAW_URL,
12 parseHuggingFaceModels,
13 provider,
14} from './huggingface.ts'
15​
16const fixture = (name: string) =>
17 readFileSync(
18 new URL(
19 `../fixtures/huggingface-chat-completion-${name}.json`,
20 import.meta.url,
21 ),
22 'utf8',
23 )
24/** huggingface.js `chat-completion/spec/{input,output}.json` (2026-10-06). */
25const INPUT = fixture('input')
26const OUTPUT = fixture('output')
27​
28const host = (name: string, rest: Record<string, unknown>) => ({
29 provider: name,
30 status: 'live',
31 is_free: false,
32 is_model_author: false,
33 ...rest,
34})
35/** featherless-ai is live but publishes no figures, so it is not `:fastest`. */
36const SILENT = host('featherless-ai', {})
37​
38const model = (id: string, providers: unknown, output = ['text']) => ({
39 id,
40 created: 1785918179,
41 architecture: { input_modalities: ['text'], output_modalities: output },
42 providers,
43})
44​
45/** Rows shaped like https://router.huggingface.co/v1/models (2026-10-06). */
46const FIXTURE = {
47 object: 'list',
48 data: [
49 model('agree/all', [
50 host('nscale', {
51 context_length: 40960,
52 pricing: { input: 0.07, output: 0.2 },
53 supports_tools: true,
54 supports_structured_output: false,
55 throughput: 79.9,
56 }),
57 host('deepinfra', {
58 context_length: 40960,
59 pricing: { input: 0.07, output: 0.2 },
60 supports_tools: true,
61 supports_structured_output: false,
62 throughput: 15.2,
63 }),
64 ]),
65 // An unprobed host is not the default route and does not veto it.
66 model('agree/but-one-silent', [
67 host('nscale', {
68 context_length: 40960,
69 pricing: { input: 0.07, output: 0.2 },
70 supports_tools: false,
71 supports_structured_output: false,
72 throughput: 79.9,
73 }),
74 SILENT,
75 ]),
76 // inclusionAI/Ling-3.0-flash and tencent/Hy4-preview: the same price
77 // with float noise on one side.
78 model('agree/float-noise', [
79 host('novita', {
80 context_length: 131072,
81 pricing: { input: 0.06, output: 2.501 },
82 supports_tools: true,
83 supports_structured_output: true,
84 throughput: 60,
85 }),
86 host('deepinfra', {
87 context_length: 131072,
88 pricing: { input: 0.060000000000000005, output: 2.5010000000000003 },
89 supports_tools: true,
90 supports_structured_output: true,
91 }),
92 ]),
93 // ibm-granite/granite-4.2-3b: one provider, noisy figures.
94 model('single/float-noise', [
95 host('deepinfra', {
96 context_length: 131072,
97 pricing: { input: 0.030000000000000002, output: 0.12000000000000001 },
98 supports_tools: true,
99 supports_structured_output: true,
100 throughput: 60,
101 }),
102 ]),
103 // deepseek-ai/DeepSeek-V4.1-Flash: same context, different prices, one
104 // provider with no price, structured output split.
105 model('split/price', [
106 host('novita', {
107 context_length: 1048576,
108 pricing: { input: 0.3, output: 1.2 },
109 supports_tools: true,
110 supports_structured_output: false,
111 throughput: 102.2,
112 }),
113 host('fireworks-ai', {
114 context_length: 1048576,
115 supports_tools: true,
116 supports_structured_output: true,
117 throughput: 126.4,
118 }),
119 host('deepinfra', {
120 context_length: 1048576,
121 pricing: { input: 0.2, output: 0.6 },
122 supports_tools: true,
123 supports_structured_output: true,
124 throughput: 106,
125 }),
126 ]),
127 model('split/context', [
128 host('novita', {
129 context_length: 1000000,
130 pricing: { input: 0.42, output: 3 },
131 supports_tools: true,
132 supports_structured_output: true,
133 throughput: 39,
134 }),
135 host('cerebras', {
136 context_length: 65536,
137 pricing: { input: 0.42, output: 3 },
138 supports_tools: true,
139 supports_structured_output: true,
140 throughput: 172,
141 }),
142 ]),
143 model('unranked/only', [SILENT]),
144 model('promo/free', [
145 host('novita', {
146 context_length: 8192,
147 pricing: { input: 0.1, output: 0.2 },
148 is_free: true,
149 supports_tools: false,
150 supports_structured_output: false,
151 throughput: 50,
152 }),
153 ]),
154 // Same throughput: context is shared, the prices are not.
155 model('route/tie', [
156 host('novita', {
157 context_length: 4096,
158 pricing: { input: 0.2, output: 0.4 },
159 supports_tools: true,
160 supports_structured_output: false,
161 throughput: 40,
162 }),
163 host('deepinfra', {
164 context_length: 4096,
165 pricing: { input: 0.5, output: 0.9 },
166 supports_tools: true,
167 supports_structured_output: false,
168 throughput: 40,
169 }),
170 ]),
171 model('route/tie-price', [
172 host('novita', {
173 context_length: 8192,
174 pricing: { input: 0.2, output: 0.4 },
175 supports_tools: true,
176 supports_structured_output: true,
177 throughput: 40,
178 }),
179 host('together', {
180 context_length: 8192,
181 pricing: { input: 0.2, output: 0.4 },
182 supports_tools: true,
183 supports_structured_output: true,
184 throughput: 40,
185 }),
186 ]),
187 // `:fastest` is highest throughput, not the lowest output price.
188 model('route/fast-not-cheap', [
189 host('cerebras', {
190 context_length: 65536,
191 pricing: { input: 0.9, output: 2 },
192 supports_tools: true,
193 supports_structured_output: false,
194 throughput: 200,
195 }),
196 host('novita', {
197 context_length: 1000000,
198 pricing: { input: 0.1, output: 0.2 },
199 supports_tools: false,
200 supports_structured_output: true,
201 throughput: 20,
202 }),
203 ]),
204 // The fastest host publishes no context. The slower one does not fill it.
205 model('route/fast-no-context', [
206 host('cerebras', {
207 pricing: { input: 0.1, output: 0.1 },
208 supports_tools: false,
209 supports_structured_output: false,
210 throughput: 1000,
211 }),
212 host('novita', {
213 context_length: 16384,
214 pricing: { input: 0.02, output: 0.05 },
215 supports_tools: false,
216 supports_structured_output: false,
217 throughput: 80,
218 }),
219 ]),
220 // An error host is not the route, even with a higher throughput.
221 model('route/error-faster', [
222 host('fireworks-ai', {
223 status: 'error',
224 context_length: 1000,
225 pricing: { input: 9, output: 9 },
226 supports_tools: false,
227 supports_structured_output: false,
228 throughput: 500,
229 }),
230 host('novita', {
231 context_length: 8192,
232 pricing: { input: 0.1, output: 0.2 },
233 supports_tools: true,
234 supports_structured_output: false,
235 throughput: 10,
236 }),
237 ]),
238 model('image/model', [], ['image']),
239 ],
241​
242const listing = { derivation: 'listing', sourceUrl: HUGGINGFACE_MODELS_URL }
243​
244const originalFetch = globalThis.fetch
245​
246afterEach(() => {
247 globalThis.fetch = originalFetch
248})
249​
250describe('huggingface listing', () => {
251 it('stores a fact only when every provider states it and agrees', async () => {
252 const { models, docsFailures } = await parseHuggingFaceModels(FIXTURE)
253 expect(docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
254 const byId = Object.fromEntries(models.map((m) => [m.rawId, m]))
255​
256 expect(byId['agree/all']).toMatchObject({
257 activity: 'chat',
258 contextWindow: 40960,
259 capabilities: ['tools'],
260 pricing: {
261 tables: {
262 rate: {
263 base: { input_tokens: 0.07 / 1e6, output_tokens: 0.2 / 1e6 },
264 },
265 },
266 source: { url: HUGGINGFACE_MODELS_URL },
267 },
268 factSources: {
269 contextWindow: {
270 ...listing,
271 path: 'providers[provider=nscale].context_length',
272 },
273 pricing: { ...listing, path: 'providers[provider=nscale].pricing' },
274 capabilities: {
275 tools: {
276 ...listing,
277 path: 'providers[provider=nscale].supports_tools',
278 },
279 },
280 },
281 })
282​
283 // `agree/all`: every host says no structured output. That is a stated
284 // no, and it says nothing about plain `response_format`.
285 expect(byId['agree/all']?.unsupportedCapabilities).toEqual([
286 'structured_outputs',
287 ])
288 expect(byId['agree/all']?.factSources?.capabilities).toMatchObject({
289 structured_outputs: {
290 ...listing,
291 path: 'providers[provider=nscale].supports_structured_output',
292 },
293 })
294 expect(byId['promo/free']?.unsupportedCapabilities).toEqual([
295 'tools',
296 'structured_outputs',
297 ])
298​
299 expect(byId['agree/but-one-silent']).toMatchObject({
300 contextWindow: 40960,
301 capabilities: [],
302 unsupportedCapabilities: ['tools', 'structured_outputs'],
303 pricing: {
304 tables: {
305 rate: {
306 base: { input_tokens: 0.07 / 1e6, output_tokens: 0.2 / 1e6 },
307 },
308 },
309 },
310 factSources: {
311 contextWindow: {
312 ...listing,
313 path: 'providers[provider=nscale].context_length',
314 },
315 pricing: { ...listing, path: 'providers[provider=nscale].pricing' },
316 capabilities: {
317 tools: {
318 ...listing,
319 path: 'providers[provider=nscale].supports_tools',
320 },
321 structured_outputs: {
322 ...listing,
323 path: 'providers[provider=nscale].supports_structured_output',
324 },
325 },
326 },
327 })
328 expect(byId['agree/float-noise']?.pricing).toMatchObject({
329 tables: {
330 rate: {
331 base: { input_tokens: 0.06 / 1e6, output_tokens: 2.501 / 1e6 },
332 },
333 },
334 })
335 expect(byId['single/float-noise']?.pricing).toMatchObject({
336 tables: {
337 rate: {
338 base: { input_tokens: 0.03 / 1e6, output_tokens: 0.12 / 1e6 },
339 },
340 },
341 })
342​
343 expect(byId['split/price']).toMatchObject({
344 contextWindow: 1048576,
345 pricing: null,
346 capabilities: ['tools', 'structured_outputs', 'response_format'],
347 })
348 expect(byId['split/price']?.factSources).toEqual({
349 contextWindow: {
350 ...listing,
351 path: 'providers[provider=fireworks-ai].context_length',
352 },
353 capabilities: {
354 tools: {
355 ...listing,
356 path: 'providers[provider=fireworks-ai].supports_tools',
357 },
358 structured_outputs: {
359 ...listing,
360 path: 'providers[provider=fireworks-ai].supports_structured_output',
361 },
362 response_format: {
363 ...listing,
364 path: 'providers[provider=fireworks-ai].supports_structured_output',
365 },
366 },
367 })
368​
369 expect(byId['split/context']).toMatchObject({
370 contextWindow: 65536,
371 capabilities: ['tools', 'structured_outputs', 'response_format'],
372 factSources: {
373 contextWindow: {
374 ...listing,
375 path: 'providers[provider=cerebras].context_length',
376 },
377 pricing: { ...listing, path: 'providers[provider=cerebras].pricing' },
378 },
379 })
380 expect(byId['split/context']?.pricing).not.toBeNull()
381​
382 expect(byId['route/tie']).toMatchObject({
383 contextWindow: 4096,
384 pricing: null,
385 capabilities: ['tools'],
386 factSources: {
387 contextWindow: {
388 ...listing,
389 path: 'providers[provider=deepinfra,novita].context_length',
390 },
391 capabilities: {
392 tools: {
393 ...listing,
394 path: 'providers[provider=deepinfra,novita].supports_tools',
395 },
396 },
397 },
398 })
399 expect(byId['route/tie-price']).toMatchObject({
400 contextWindow: 8192,
401 factSources: {
402 pricing: {
403 ...listing,
404 path: 'providers[provider=novita,together].pricing',
405 },
406 },
407 })
408 expect(byId['route/tie-price']?.pricing).toMatchObject({
409 tables: {
410 rate: {
411 base: { input_tokens: 0.2 / 1e6, output_tokens: 0.4 / 1e6 },
412 },
413 },
414 })
415 expect(byId['route/fast-not-cheap']).toMatchObject({
416 contextWindow: 65536,
417 capabilities: ['tools'],
418 factSources: {
419 pricing: { ...listing, path: 'providers[provider=cerebras].pricing' },
420 },
421 })
422 expect(byId['route/fast-not-cheap']?.pricing).toMatchObject({
423 tables: {
424 rate: { base: { input_tokens: 0.9 / 1e6, output_tokens: 2 / 1e6 } },
425 },
426 })
427 expect(byId['route/fast-no-context']).toMatchObject({
428 contextWindow: null,
429 capabilities: [],
430 factSources: {
431 pricing: { ...listing, path: 'providers[provider=cerebras].pricing' },
432 },
433 })
434 expect(byId['route/error-faster']).toMatchObject({
435 contextWindow: 8192,
436 capabilities: ['tools'],
437 factSources: {
438 contextWindow: {
439 ...listing,
440 path: 'providers[provider=novita].context_length',
441 },
442 pricing: { ...listing, path: 'providers[provider=novita].pricing' },
443 },
444 })
445​
446 expect(byId['unranked/only']).toMatchObject({
447 contextWindow: null,
448 pricing: null,
449 capabilities: null,
450 factSources: {},
451 })
452 // A promo is not the standard price; settled "no" flags are an empty list.
453 expect(byId['promo/free']).toMatchObject({
454 contextWindow: 8192,
455 pricing: null,
456 capabilities: [],
457 })
458 expect(byId['image/model']).toMatchObject({
459 activity: 'image',
460 pricing: null,
461 })
462​
463 // No price is said, not left out: the poller then drops a stored card
464 // instead of keeping it as a parser miss.
465 for (const row of models) {
466 expect(row.absent).toEqual(
467 row.pricing === null ? { pricing: 'cleared' } : undefined,
468 )
469 }
470 // A zero quote and a null `pricing` both state no price.
471 const none = await parseHuggingFaceModels({
472 data: [
473 model('zero/quote', [
474 host('novita', { pricing: { input: 0, output: 0 } }),
475 ]),
476 model('null/quote', [host('novita', { pricing: null })]),
477 ...FIXTURE.data,
478 ],
479 })
480 expect(none.docsFailures.failed).toBe(0)
481 for (const row of none.models.slice(0, 2)) {
482 expect(row).toMatchObject({
483 pricing: null,
484 absent: { pricing: 'cleared' },
485 })
486 }
487 })
488​
489 // `cleared` drops a stored card, so nothing the parser cannot read may
490 // come out as "no price".
491 it('throws on a listing-wide reshape instead of clearing', async () => {
492 const replay = (edit: (json: string) => string) =>
493 parseHuggingFaceModels(JSON.parse(edit(JSON.stringify(FIXTURE))))
494 // The listing with its price keys renamed, then with numbers as strings.
495 await expect(
496 replay((json) =>
497 json
498 .replaceAll('"input":', '"prompt":')
499 .replaceAll('"output":', '"completion":'),
500 ),
501 ).rejects.toThrow(
502 /^huggingface: (\d+) of \1 provider prices are in an unread shape$/,
503 )
504 await expect(
505 replay((json) => json.replace(/"(input|output)":([\d.]+)/g, '"$1":"$2"')),
506 ).rejects.toThrow(
507 /^huggingface: (\d+) of \1 provider prices are in an unread shape$/,
508 )
509 // Prices moved out of the entries altogether.
510 await expect(
511 replay((json) => json.replaceAll('"pricing":', '"rates":')),
512 ).rejects.toThrow('no provider entry states a price')
513​
514 const ranked = host('nscale', {
515 context_length: 40960,
516 pricing: { input: 0.07, output: 0.2 },
517 })
518 for (const providers of [
519 { nscale: ranked },
520 [ranked, 'featherless-ai'],
521 undefined,
522 ]) {
523 await expect(
524 parseHuggingFaceModels({
525 data: [...FIXTURE.data, model('x/y', providers)],
526 }),
527 ).rejects.toThrow('a providers list is in an unread shape')
528 }
529 // More than a tenth of the stated prices unreadable is a reshape too.
530 const odd = (id: string) =>
531 model(id, [{ ...ranked, pricing: { input: 0.07 } }])
532 await expect(
533 parseHuggingFaceModels({
534 data: [...FIXTURE.data, odd('a/1'), odd('a/2'), odd('a/3'), odd('a/4')],
535 }),
536 ).rejects.toThrow(
537 /^huggingface: 4 of \d+ provider prices are in an unread shape$/,
538 )
539 })
540​
541 it('withholds only that row’s price when one entry’s price is unreadable', async () => {
542 const ranked = host('nscale', {
543 context_length: 40960,
544 pricing: { input: 0.07, output: 0.2 },
545 })
546 const clean = await parseHuggingFaceModels(FIXTURE)
547 for (const pricing of [
548 0.07,
549 '0.07',
550 { input: 0.07 },
551 { input: -1, output: 1 },
552 ]) {
553 const { models, docsFailures } = await parseHuggingFaceModels({
554 data: [
555 // A second, readable entry: the row still cannot be settled.
556 model('x/y', [ranked, { ...ranked, provider: 'novita', pricing }]),
557 ...FIXTURE.data,
558 ],
559 })
560 expect(docsFailures).toEqual({
561 failed: 1,
562 skipped: 0,
563 first: [
564 {
565 source: `${HUGGINGFACE_MODELS_URL}#x/y`,
566 error:
567 'huggingface: the price of provider entry "novita" is in an unread shape',
568 elapsedMs: expect.any(Number) as number,
569 },
570 ],
571 })
572 // Kept as stored, not cleared; its other facts are read as usual.
573 expect(models[0]).toMatchObject({
574 rawId: 'x/y',
575 contextWindow: 40960,
576 pricing: null,
577 absent: { pricing: 'unavailable' },
578 })
579 const facts = ({ pricing: card, ...rest }: (typeof models)[number]) => ({
580 ...rest,
581 priced: card !== null,
582 })
583 expect(models.slice(1).map(facts)).toEqual(clean.models.map(facts))
584 }
585 })
586​
587 it('leaves context and flags null when their fields change type', async () => {
588 const {
589 models: [row],
590 } = await parseHuggingFaceModels({
591 data: [
592 model('x/y', [
593 host('nscale', {
594 context_length: '40960',
595 pricing: { input: 0.07, output: 0.2 },
596 supports_tools: 'yes',
597 }),
598 ]),
599 ],
600 })
601 expect(row).toMatchObject({ contextWindow: null, capabilities: null })
602 })
603​
604 it('throws when a provider status is not live or error', async () => {
605 await expect(
606 parseHuggingFaceModels({
607 data: [
608 model('x/y', [
609 host('novita', {
610 status: 'staging',
611 context_length: 8192,
612 pricing: { input: 0.1, output: 0.2 },
613 throughput: 10,
614 }),
615 ]),
616 ],
617 }),
618 ).rejects.toThrow('status is in an unread shape')
619 })
620​
621 it('throws on a payload that lists nothing', async () => {
622 await expect(parseHuggingFaceModels({ data: [] })).rejects.toThrow(
623 'listed no ids',
624 )
625 await expect(parseHuggingFaceModels('<html>')).rejects.toThrow(
626 'no data array',
627 )
628 })
629})
630​
631describe('huggingface spec', () => {
632 it('wraps the published schemas into one chat path', () => {
633 const spec = buildHuggingFaceSpec(INPUT, OUTPUT)
634 expect(Object.keys(spec.paths ?? {})).toEqual(['/v1/chat/completions'])
635 expect(JSON.stringify(spec)).not.toContain('#/$defs/')
636​
637 const { endpoints, warnings } = classifyAndBundle(provider, {
638 specs: [spec],
639 sources: [{ url: 'x', hash: 'y' }],
640 outputStrategy: 'post-200',
641 })
642 expect(endpoints).toHaveLength(1)
643 const [endpoint] = endpoints
644 expect(endpoint).toMatchObject({
645 activity: 'chat',
646 derivation: 'generated',
647 })
648 expect(warnings).toEqual([])
649 expect(Object.keys(endpoint?.input?.$defs ?? {})).toHaveLength(16)
650 expect(endpoint?.output).toBeDefined()
651 expect(
652 provider.generationEndpointId?.({ rawId: 'a/b', activity: 'chat' }),
653 ).toBe('v1/chat/completions')
654 expect(
655 provider.generationEndpointId?.({ rawId: 'a/b', activity: 'image' }),
656 ).toBeNull()
657 })
658​
659 it('throws on a file that is not the published schema', () => {
660 const renamed = INPUT.replace('"ChatCompletionInput"', '"ChatInput"')
661 const noMessages = INPUT.replace('"messages": {', '"msgs": {')
662 for (const [input, output] of [
663 ['<!doctype html><title>Not found</title>', OUTPUT],
664 [INPUT, '{}'],
665 [renamed, OUTPUT],
666 [noMessages, OUTPUT],
667 [INPUT, INPUT],
668 ]) {
669 expect(() => buildHuggingFaceSpec(input ?? '', output ?? '')).toThrow(
670 /^huggingface: /,
671 )
672 }
673 })
674​
675 it('throws on an HTML body served for either schema file', () => {
676 const html = '<!doctype html><html><body>Not found</body></html>'
677 expect(() => buildHuggingFaceSpec(html, OUTPUT)).toThrow('is not JSON')
678 expect(() => buildHuggingFaceSpec(INPUT, html)).toThrow('is not JSON')
679 })
680​
681 it('fetches the listing and both schema files', async () => {
682 const urls: Array<string> = []
683 globalThis.fetch = ((url: string) => {
684 urls.push(String(url))
685 const body: Record<string, string> = {
686 [HUGGINGFACE_MODELS_URL]: JSON.stringify(FIXTURE),
687 ['https://huggingface.co/docs/inference-providers/tasks/chat-completion']:
688 hostDocs.hf,
689 [`${HUGGINGFACE_SPEC_RAW_URL}/input.json`]: INPUT,
690 [`${HUGGINGFACE_SPEC_RAW_URL}/output.json`]: OUTPUT,
691 }
692 const text = body[String(url)]
693 return text === undefined
694 ? Promise.reject(new Error(`unexpected fetch: ${String(url)}`))
695 : Promise.resolve(new Response(text))
696 }) as typeof fetch
697​
698 const listed = await provider.listModels({})
699 const spec = await provider.fetchSpec({})
700​
701 expect(listed.models).toHaveLength(FIXTURE.data.length)
702 expect(spec.specs).toHaveLength(1)
703 expect(spec.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
704 expect(urls).toHaveLength(4)
705 })
706})