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

together.test.ts

607 lines19.8 KB

1import nativeDocs from '../fixtures/native-reasoning-docs.json'
2import { describe, expect, it } from 'vitest'
3​
4import { price } from '@modelschemas/rate-card'
5​
6import { classifyAndBundle } from '#/server/ingest/sync.ts'
7import { providerRegistry } from '#/server/providers/index.ts'
8​
9import { provider, togetherRateCard } from './together.ts'
10​
11const SPEC_YAML = `openapi: 3.1.0
12info:
13 title: Together APIs
14paths:
15 /chat/completions:
16 post:
17 summary: Create chat completion
18 requestBody:
19 content:
20 application/json:
21 schema:
22 type: object
23 required: [model, messages]
24 properties:
25 model: { type: string }
26 messages: { type: array }
27 responses:
28 "200":
29 content:
30 application/json:
31 schema:
32 type: object
33 properties:
34 id: { type: string }
35 /embeddings:
36 post:
37 summary: Create embedding
38 requestBody:
39 content:
40 application/json:
41 schema:
42 type: object
43 required: [model, input]
44 properties:
45 model: { type: string }
46 input: { type: string }
47 responses:
48 "200":
49 content:
50 application/json:
51 schema:
52 type: object
53 /images/generations:
54 post:
55 summary: Create image
56 requestBody:
57 content:
58 application/json:
59 schema:
60 type: object
61 required: [model, prompt]
62 properties:
63 model: { type: string }
64 prompt: { type: string }
65 responses:
66 "200":
67 content:
68 application/json:
69 schema:
70 type: object
71 /videos:
72 post:
73 summary: Create video
74 requestBody:
75 content:
76 application/json:
77 schema:
78 type: object
79 required: [model]
80 properties:
81 model: { type: string }
82 responses:
83 "200":
84 content:
85 application/json:
86 schema:
87 type: object
88 /audio/speech:
89 post:
90 summary: Create audio
91 requestBody:
92 content:
93 application/json:
94 schema:
95 type: object
96 required: [model, input]
97 properties:
98 model: { type: string }
99 input: { type: string }
100 responses:
101 "200":
102 content:
103 application/json:
104 schema:
105 type: object
106 /files:
107 post:
108 summary: Upload file
109 requestBody:
110 content:
111 application/json:
112 schema:
113 type: object
114 responses:
115 "200":
116 content:
117 application/json:
118 schema:
119 type: object
121​
122describe('together classify', () => {
123 it('maps generation paths to activities', () => {
124 expect(provider.classify('/chat/completions', {})).toBe('chat')
125 expect(provider.classify('/completions', {})).toBe('chat')
126 expect(provider.classify('/v1/chat/completions', {})).toBe('chat')
127 expect(provider.classify('/embeddings', {})).toBe('embeddings')
128 expect(provider.classify('/images/generations', {})).toBe('image')
129 expect(provider.classify('/videos', {})).toBe('video')
130 expect(provider.classify('/audio/speech', {})).toBe('audio')
131 expect(provider.classify('/audio/transcriptions', {})).toBe('audio')
132 expect(provider.classify('/audio/translations', {})).toBe('audio')
133 })
134​
135 it('drops files, fine-tune, rerank, batches, and endpoint admin', () => {
136 expect(provider.classify('/files', {})).toBeNull()
137 expect(provider.classify('/fine-tunes', {})).toBeNull()
138 expect(provider.classify('/rerank', {})).toBeNull()
139 expect(provider.classify('/batches', {})).toBeNull()
140 expect(provider.classify('/endpoints', {})).toBeNull()
141 expect(provider.classify('/projects/{projectId}/endpoints', {})).toBeNull()
142 expect(provider.classify('/models', {})).toBeNull()
143 expect(provider.classify('/videos/{id}', {})).toBeNull()
144 })
145})
146​
147describe('together listModels', () => {
148 it('skips when TOGETHER_API_KEY is absent', async () => {
149 const result = await provider.listModels({})
150 expect(result.models).toEqual([])
151 expect(result.skipped).toBe('together: TOGETHER_API_KEY not set — skipped')
152 })
153​
154 it('parses Together’s bare-array catalog', async () => {
155 const restore = installTogetherFetch()
156 try {
157 const result = await provider.listModels({ TOGETHER_API_KEY: 'test-key' })
158 expect(result.skipped).toBeUndefined()
159 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
160 const byId = Object.fromEntries(
161 result.models.map((model) => [model.rawId, model]),
162 )
163 const qwen = byId['Qwen/Qwen3.5-9B']
164 expect(qwen).toMatchObject({
165 displayName: 'Qwen 3.5 9B',
166 activity: 'chat',
167 contextWindow: 32768,
168 maxOutput: 8192,
169 releasedAt: 1692896905,
170 modalities: { input: ['text'], output: ['text'] },
171 capabilities: ['tools', 'reasoning'],
172 reasoning: { mode: 'toggle', mandatory: false },
173 })
174 expect(qwen?.factSources?.contextWindow).toEqual({
175 derivation: 'listing',
176 sourceUrl: 'https://api.together.xyz/v1/models',
177 path: 'context_length',
178 })
179 expect(qwen?.factSources?.maxOutput?.path).toBe(
180 'config.max_output_length',
181 )
182 expect(qwen?.factSources?.pricing?.sourceUrl).toBe(
183 'https://api.together.xyz/v1/models',
184 )
185 expect(qwen?.factSources?.modalities?.sourceUrl).toBe(
186 'https://api.together.ai/v2/supported-models',
187 )
188 expect(qwen?.factSources?.reasoning?.sourceUrl).toBe(
189 'https://docs.together.ai/docs/inference/chat/reasoning.md',
190 )
191 const kimi = byId['moonshotai/Kimi-K3']
192 expect(kimi?.reasoning).toEqual({
193 mode: 'effort',
194 mandatory: false,
195 efforts: ['low', 'medium', 'high', 'max'],
196 })
197 expect(kimi?.factSources?.reasoning?.sourceUrl).toBe(
198 'https://docs.together.ai/docs/kimi-k3-quickstart.md',
199 )
200 expect(kimi?.contextWindow).toBe(1048576)
201 if (!kimi?.pricing || typeof kimi.pricing !== 'object') {
202 throw new Error('kimi card missing')
203 }
204 expect(
205 price(
206 kimi.pricing as never,
207 {},
208 { input_tokens: 1e6, output_tokens: 0 },
209 ),
210 ).toBeCloseTo(2.7, 9)
211 // Audio is priced from the catalog, never the listing's token object.
212 expect(byId['hexgrad/Kokoro-82M']?.pricing).toBeTruthy()
213 expect(byId['hexgrad/Kokoro-82M']?.absent).toBeUndefined()
214 const rime = byId['rime-labs/rime-arcana-v2']
215 expect(rime?.pricing).toBeUndefined()
216 expect(rime?.absent).toEqual({ pricing: 'cleared' })
217 expect(qwen?.absent).toBeUndefined()
218 const gpt = byId['openai/gpt-oss-120b']
219 expect(gpt?.reasoning).toEqual({
220 mode: 'effort',
221 mandatory: true,
222 efforts: ['low', 'medium', 'high'],
223 })
224 expect(gpt?.factSources?.reasoning?.sourceUrl).toBe(
225 'https://docs.together.ai/docs/gpt-oss.md',
226 )
227 expect(byId['zai-org/GLM-5.3']?.reasoning).toEqual({
228 mode: 'effort',
229 mandatory: true,
230 efforts: ['low', 'medium', 'high', 'max'],
231 })
232 expect(byId['zai-org/GLM-5.3']?.contextWindow).toBe(1048575)
233 expect(byId['zai-org/GLM-5.3-Flash']?.reasoning).toBeUndefined()
234 expect(byId['org/vision-only']?.contextWindow).toBeNull()
235 expect(byId['org/vision-only']?.modalities).toEqual({
236 input: ['text', 'image'],
237 output: ['text'],
238 })
239 expect(byId['org/vision-only']?.factSources?.modalities?.path).toBe(
240 'Vision models',
241 )
242 const flagged = byId['org/reason-flag']
243 expect(flagged?.reasoning).toBeUndefined()
244 expect(flagged?.capabilities).toEqual(['reasoning'])
245 expect(flagged?.factSources?.reasoning?.path).toBe('silent')
246 expect(byId['BAAI/bge-large-en-v1.5']?.activity).toBe('embeddings')
247 expect(byId['org/reranker']?.activity).toBeNull()
248 } finally {
249 restore()
250 }
251 })
252​
253 it('reads a JSON docs-cache hit back into reasoning and chat facts', async () => {
254 const docsFetches = { count: 0 }
255 const restore = installTogetherFetch(docsFetches)
256 const kv = jsonKv()
257 try {
258 await provider.listModels({ TOGETHER_API_KEY: 'test-key' }, kv)
259 const warmed = docsFetches.count
260 expect(warmed).toBeGreaterThan(0)
261 const result = await provider.listModels(
262 { TOGETHER_API_KEY: 'test-key' },
263 kv,
264 )
265 expect(docsFetches.count).toBe(warmed)
266 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
267 const byId = Object.fromEntries(
268 result.models.map((model) => [model.rawId, model]),
269 )
270 expect(byId['Qwen/Qwen3.5-9B']?.reasoning).toEqual({
271 mode: 'toggle',
272 mandatory: false,
273 })
274 expect(byId['moonshotai/Kimi-K3']?.reasoning).toEqual({
275 mode: 'effort',
276 mandatory: false,
277 efforts: ['low', 'medium', 'high', 'max'],
278 })
279 expect(byId['openai/gpt-oss-120b']?.reasoning).toEqual({
280 mode: 'effort',
281 mandatory: true,
282 efforts: ['low', 'medium', 'high'],
283 })
284 expect(byId['zai-org/GLM-5.3']?.contextWindow).toBe(1048575)
285 expect(byId['org/vision-only']?.modalities).toEqual({
286 input: ['text', 'image'],
287 output: ['text'],
288 })
289 } finally {
290 restore()
291 }
292 })
293})
294​
295/** KV that stores the same JSON `cachedDocs` writes. A Map comes back as `{}`. */
296function jsonKv(): KVNamespace {
297 const store = new Map<string, string>()
298 return {
299 get: (key: string) => Promise.resolve(store.get(key) ?? null),
300 put: (key: string, value: string) => {
301 store.set(key, value)
302 return Promise.resolve()
303 },
304 } as KVNamespace
306​
307function installTogetherFetch(docsFetches?: { count: number }): () => void {
308 const original = globalThis.fetch
309 globalThis.fetch = ((url: string, init?: RequestInit) => {
310 const target = String(url)
311 const headers = new Headers(init?.headers)
312 if (
313 target.startsWith('https://api.together.xyz/') ||
314 target.startsWith('https://api.together.ai/')
315 ) {
316 expect(headers.get('Authorization')).toBe('Bearer test-key')
317 }
318 if (target.includes('/v2/supported-models')) {
319 return Promise.resolve(
320 new Response(
321 JSON.stringify({
322 data: [
323 {
324 name: 'Qwen/Qwen3.5-9B',
325 inputModalities: ['MODALITY_TEXT'],
326 outputModalities: ['MODALITY_TEXT'],
327 features: ['FEATURE_TOOL_CALLING', 'FEATURE_REASONING'],
328 },
329 {
330 name: 'org/reason-flag',
331 inputModalities: ['MODALITY_TEXT'],
332 outputModalities: ['MODALITY_TEXT'],
333 features: ['FEATURE_REASONING'],
334 },
335 ],
336 }),
337 { status: 200, headers: { 'content-type': 'application/json' } },
338 ),
339 )
340 }
341 if (target.includes('.md') && docsFetches) docsFetches.count += 1
342 if (target.includes('/deepseek-v4-quickstart.md'))
343 return textResponse(
344 nativeDocs['https://docs.together.ai/docs/deepseek-v4-quickstart.md'],
345 )
346 if (target.includes('/serverless/models.md')) {
347 return textResponse(LIST_DOCS)
348 }
349 if (target.includes('/inference/chat/reasoning.md')) {
350 return textResponse(
351 LIST_REASONING +
352 '\n' +
353 nativeDocs[
354 'https://docs.together.ai/docs/inference/chat/reasoning.md'
355 ],
356 )
357 }
358 if (target.includes('/kimi-k3-quickstart.md'))
359 return textResponse(LIST_KIMI)
360 if (target.includes('/glm-5.3-quickstart.md'))
361 return textResponse(
362 nativeDocs['https://docs.together.ai/docs/glm-5.3-quickstart.md'],
363 )
364 if (target.endsWith('/gpt-oss.md')) return textResponse(LIST_GPT)
365 expect(target).toBe('https://api.together.xyz/v1/models')
366 return Promise.resolve(
367 new Response(
368 JSON.stringify([
369 {
370 id: 'Qwen/Qwen3.5-9B',
371 display_name: 'Qwen 3.5 9B',
372 created: 1692896905,
373 type: 'chat',
374 context_length: 32768,
375 config: { max_output_length: 8192 },
376 pricing: { input: 0.17, output: 0.25, cached_input: 0 },
377 },
378 {
379 id: 'moonshotai/Kimi-K3',
380 type: 'chat',
381 context_length: 1048576,
382 pricing: { input: 2.7, output: 13.5, cached_input: 0.27 },
383 },
384 { id: 'openai/gpt-oss-120b', type: 'chat', context_length: 131072 },
385 { id: 'zai-org/GLM-5.3', type: 'chat' },
386 {
387 id: 'zai-org/GLM-5.3-Flash',
388 type: 'chat',
389 context_length: 1048575,
390 },
391 { id: 'org/vision-only', type: 'chat', context_length: 0 },
392 { id: 'org/reason-flag', type: 'chat', context_length: 4096 },
393 { id: 'BAAI/bge-large-en-v1.5', type: 'embedding' },
394 { id: 'org/reranker', type: 'rerank' },
395 { id: 'hexgrad/Kokoro-82M', type: 'audio', pricing: { input: 4 } },
396 {
397 id: 'rime-labs/rime-arcana-v2',
398 type: 'audio',
399 pricing: { input: 0.27, output: 0 },
400 },
401 ]),
402 { status: 200, headers: { 'content-type': 'application/json' } },
403 ),
404 )
405 }) as typeof fetch
406 return () => {
407 globalThis.fetch = original
408 }
410​
411function textResponse(body: string): Promise<Response> {
412 return Promise.resolve(
413 new Response(body, {
414 status: 200,
415 headers: { 'content-type': 'text/markdown' },
416 }),
417 )
419​
420const LIST_DOCS = `
421## Chat models
422​
423| Organization | Model name | API model string | Context length | Input pricing (per 1M tokens) | Cached input pricing (per 1M tokens) | Output pricing (per 1M tokens) | Quantization | Function calling | Structured outputs |
424| :- | :- | :- | :- | :- | :- | :- | :- | :- | :- |
425| Qwen | Qwen3.5 9B | Qwen/Qwen3.5-9B | 262144 | \\$0.17 | - | \\$0.25 | FP8 | Yes | Yes |
426| Z.ai | GLM-5.3 | zai-org/GLM-5.3 | 1048575 | \\$1.40 | \\$0.26 | \\$4.40 | FP4 | Yes | Yes |
427​
428## Vision models
429​
430| Organization | Model name | API model string | Context length | Input pricing (per 1M tokens) | Output pricing (per 1M tokens) |
431| :- | :- | :- | :- | :- | :- |
432| Org | Vision only | org/vision-only | 8192 | \\$1.00 | \\$1.00 |
433​
434## Audio models
435​
436| Organization | Modality | Model name | Model string for API | Pricing |
437| :- | :- | :- | :- | :- |
438| Kokoro | Text-to-Speech | Kokoro | hexgrad/Kokoro-82M | \\$4.00 per 1M chars |
440​
441const LIST_REASONING = `
442* **Hybrid:** Supports both reasoning and non-reasoning modes via \`reasoning={"enabled": True/False}\`.
443* **Adjustable effort:** Supports the \`reasoning_effort\` parameter to control reasoning depth (\`"low"\`, \`"medium"\`, or \`"high"\`).
444​
445## Supported models
446​
447| Model | API string | Type | Context length |
448| :- | :- | :- | :- |
449| Qwen3.5 9B | \`Qwen/Qwen3.5-9B\` | Hybrid (on by default) | 262K |
450| Kimi K3 | \`moonshotai/Kimi-K3\` | Hybrid (on by default) | 1M |
451| GPT-OSS 120B | \`openai/gpt-oss-120b\` | Adjustable effort | 128K |
453​
454const LIST_KIMI = `
455The model ID is \`moonshotai/Kimi-K3\`.
456​
457| Parameter | Behavior on Together |
458| - | - |
459| \`reasoning_effort\` | \`"low"\`, \`"medium"\`, \`"high"\`, or \`"max"\` (default). |
460| \`reasoning\` | \`{"enabled": False}\` disables thinking entirely. |
462​
463const LIST_GPT = `
464The model ID is \`openai/gpt-oss-120b\`.
465​
466\`reasoning_effort\` accepts \`"low"\`, \`"medium"\`, and \`"high"\`.
467​
468Reasoning cannot be disabled entirely.
470​
471describe('togetherRateCard', () => {
472 it('compiles per-million listing rates into a token card', async () => {
473 const card = await togetherRateCard({
474 hourly: 0,
475 input: 0.88,
476 output: 0.88,
477 cached_input: 0.2,
478 base: 0,
479 finetune: 0,
480 })
481 if (!card) throw new Error('did not compile')
482 expect(
483 price(card, {}, { input_tokens: 1e6, output_tokens: 0 }),
484 ).toBeCloseTo(0.88, 9)
485 expect(
486 price(
487 card,
488 {},
489 { cache_read_tokens: 1e6, input_tokens: 0, output_tokens: 0 },
490 ),
491 ).toBeCloseTo(0.2, 9)
492 expect(card.source.url).toBe('https://api.together.xyz/v1/models')
493 })
494​
495 it('serves no card for an all-zero or absent listing', async () => {
496 // Issue #111 examples Together does not quote per token.
497 expect(
498 await togetherRateCard({
499 hourly: 0,
500 input: 0,
501 output: 0,
502 cached_input: 0,
503 base: 0,
504 }),
505 ).toBeNull()
506 expect(await togetherRateCard(undefined)).toBeNull()
507 })
508})
509​
510describe('together provider', () => {
511 it('keeps reasoning flags off the shared chat schema', () => {
512 expect(provider.perModelSchemaFlags).toEqual([
513 'reasoning',
514 'reasoning_effort',
515 ])
516 })
517​
518 // Ids from the live /v1/models listing (2026-11-21).
519 it('names the maker in a two-segment id, through its namespace', () => {
520 const stated = (rawId: string) => {
521 const identity = provider.upstreamModelIdentity?.(rawId)
522 if (!identity) return null
523 const target = providerRegistry.find(
524 (p) =>
525 p.id === identity.providerNamespace ||
526 p.modelNamespaces?.includes(identity.providerNamespace),
527 )
528 return [target?.id ?? null, identity.rawId]
529 }
530 expect(stated('alibaba/happyhorse-1.0-t2v')).toEqual([
531 'dashscope',
532 'happyhorse-1.0-t2v',
533 ])
534 expect(stated('MiniMaxAI/MiniMax-M3.1-Flash')).toEqual([
535 'minimax',
536 'MiniMax-M3.1-Flash',
537 ])
538 expect(stated('google/gemini-3-pro-image')).toEqual([
539 'gemini',
540 'gemini-3-pro-image',
541 ])
542 expect(stated('openai/gpt-image-2')).toEqual(['openai', 'gpt-image-2'])
543 // A maker with no API row here is still stated; it just resolves nowhere.
544 expect(stated('deepcogito/cogito-v1-preview-llama-70B')).toEqual([
545 null,
546 'cogito-v1-preview-llama-70B',
547 ])
548 expect(stated('nim/meta/llama-3.3-70b-instruct')).toBeNull()
549 expect(
550 provider.upstreamModelIdentity?.('openai/gpt-image-2')?.source,
551 ).toEqual({
552 derivation: 'listing',
553 sourceUrl: 'https://api.together.xyz/v1/models',
554 path: 'id',
555 })
556 })
557})
558​
559describe('together fetchSpec', () => {
560 it('loads the published yaml and classifies generation POSTs', async () => {
561 const original = globalThis.fetch
562 globalThis.fetch = ((url: string) => {
563 expect(String(url)).toBe('https://docs.together.ai/openapi.yaml')
564 return Promise.resolve(new Response(SPEC_YAML, { status: 200 }))
565 }) as typeof fetch
566 try {
567 const fetched = await provider.fetchSpec({})
568 expect(fetched.outputStrategy).toBe('post-200')
569 expect(fetched.sources[0]?.url).toBe(
570 'https://docs.together.ai/openapi.yaml',
571 )
572 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
573​
574 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
575 expect(warnings).toEqual([])
576 expect(
577 endpoints
578 .map((endpoint): [string, string] => [
579 endpoint.dbId,
580 endpoint.activity,
581 ])
582 .sort(([aId, aAct], [bId, bAct]) =>
583 aId < bId
584 ? -1
585 : aId > bId
586 ? 1
587 : aAct < bAct
588 ? -1
589 : aAct > bAct
590 ? 1
591 : 0,
592 ),
593 ).toEqual([
594 ['together/audio/speech', 'audio'],
595 ['together/chat/completions', 'chat'],
596 ['together/embeddings', 'embeddings'],
597 ['together/images/generations', 'image'],
598 ['together/videos', 'video'],
599 ])
600 expect(
601 endpoints.every((endpoint) => endpoint.derivation === 'upstream-spec'),
602 ).toBe(true)
603 } finally {
604 globalThis.fetch = original
605 }
606 })
607})