Open History to see the last commit
1/**
2 * Together chat facts the v1 listing leaves empty: reasoning mode from the
3 * reasoning guide and model quickstarts, and serverless chat rates / context
4 * / vision inputs from the models catalog. Listing values win when both
5 * publish a number. A zero listing rate stays unpublished.
6 */
7import { compileTokenCard } from '@modelschemas/rate-card'
8import { isCapabilityMap } from '#/lib/capabilities.ts'
9
10import type { ThinkingRequest } from './request-map.ts'
11import { tagDocsFacts } from './fact-sources.ts'
12import type { cachedDocs } from './model-facts.ts'
13import {
14 assertParsed,
15 markdownSection,
16 markdownTableRows,
17} from './model-facts.ts'
18import { TOGETHER_MODELS_DOCS_URL } from './together-pricing.ts'
19import { fetchText, sha256Text } from './types.ts'
20import type {
21 FactSource,
22 ModelFactSources,
23 ModelInfo,
24 ModelReasoning,
25} from './types.ts'
26
27export const TOGETHER_REASONING_URL =
28 'https://docs.together.ai/docs/inference/chat/reasoning.md'
29export const TOGETHER_KIMI_K3_URL =
30 'https://docs.together.ai/docs/kimi-k3-quickstart.md'
31export const TOGETHER_GLM_53_URL =
32 'https://docs.together.ai/docs/glm-5.3-quickstart.md'
33export const TOGETHER_GPT_OSS_URL = 'https://docs.together.ai/docs/gpt-oss.md'
34
35/** Quickstarts that name one model's effort levels. The guide's table does not. */
36export const TOGETHER_REASONING_QUICKSTARTS = [
37 TOGETHER_KIMI_K3_URL,
38 TOGETHER_GLM_53_URL,
39 TOGETHER_GPT_OSS_URL,
40] as const
41
42const DOC_HEADERS = { 'User-Agent': 'modelschemas' }
43
44export interface TogetherChatRow {
45 contextWindow: number | null
46 /** USD per million tokens. Absent when the cell is `-`, `Free`, or not a single rate. */
47 inputPerMillion: number | null
48 cachedPerMillion: number | null
49 outputPerMillion: number | null
50}
51
52export interface TogetherDocsBundle {
53 chat: Record<string, TogetherChatRow>
54 /** Vision-table ids the supported-models API did not already describe. */
55 vision: Record<string, { input: Array<string>; output: Array<string> }>
56 hash: string
57 extractedAt: string
58}
59
60export interface TogetherReasoningHit {
61 reasoning: ModelReasoning
62 sourceUrl: string
63 sourceHash: string
64 thinking?: ThinkingRequest | null
65}
66
67function section(markdown: string, heading: string): string {
68 const text = markdown.startsWith('## ') ? `\n${markdown}` : markdown
69 return markdownSection(text, heading)
70}
71
72function stripFences(markdown: string): string {
73 return markdown.replace(/```[\s\S]*?```/g, '')
74}
75
76function clean(cell: string): string {
77 return cell.replace(/\\/g, '').replace(/`/g, '').replace(/\s+/g, ' ').trim()
78}
79
80function modelId(cell: string): string | null {
81 const id = clean(cell)
82 return /^[A-Za-z0-9][\w.+-]*\/[\w.+-]+$/.test(id) ? id : null
83}
84
85/** Quoted effort names in source order. `"low"`, `"medium"`, or `"high"`. */
86function quotedLevels(text: string): Array<string> {
87 const levels: Array<string> = []
88 for (const match of text.matchAll(/"([a-z][a-z0-9]*)"/g)) {
89 const level = match[1]
90 if (level && !levels.includes(level)) levels.push(level)
91 }
92 return levels
93}
94
95function positiveCount(cell: string): number | null {
96 const text = clean(cell)
97 if (text === '' || text === '-' || /^free$/i.test(text)) return null
98 if (!/^[\d,]+$/.test(text)) return null
99 const value = Number(text.replace(/,/g, ''))
100 return Number.isFinite(value) && value > 0 ? value : null
101}
102
103/** One `$X` cell. `Free`, `-`, and varying copy are not a rate. */
104function perMillion(cell: string): number | null {
105 const text = clean(cell)
106 if (text === '' || text === '-' || /^free$/i.test(text)) return null
107 const amounts = [...text.matchAll(/\$(\d+(?:\.\d+)?)/g)]
108 if (amounts.length !== 1 || !amounts[0]?.[1]) return null
109 const amount = Number(amounts[0][1])
110 return Number.isFinite(amount) && amount > 0 ? amount : null
111}
112
113/**
114 * Serverless chat table. Context `-` and price `Free` stay null.
115 * Ids the table omits are absent from the map.
116 */
117export function parseTogetherChatCatalog(
118 markdown: string,
119): Map<string, TogetherChatRow> {
120 const out = new Map<string, TogetherChatRow>()
121 for (const cells of markdownTableRows(section(markdown, 'Chat models'))) {
122 const id = modelId(cells[2] ?? '')
123 if (!id || out.has(id)) continue
124 out.set(id, {
125 contextWindow: positiveCount(cells[3] ?? ''),
126 inputPerMillion: perMillion(cells[4] ?? ''),
127 cachedPerMillion: perMillion(cells[5] ?? ''),
128 outputPerMillion: perMillion(cells[6] ?? ''),
129 })
130 }
131 return out
132}
133
134/**
135 * Vision catalog rows. Input is text plus image; output is text.
136 * This table is a subset of the supported-models API.
137 */
138export function parseTogetherVisionModalities(
139 markdown: string,
140): Map<string, { input: Array<string>; output: Array<string> }> {
141 const out = new Map<string, { input: Array<string>; output: Array<string> }>()
142 for (const cells of markdownTableRows(section(markdown, 'Vision models'))) {
143 const id = modelId(cells[2] ?? '')
144 if (!id || out.has(id)) continue
145 out.set(id, { input: ['text', 'image'], output: ['text'] })
146 }
147 return out
148}
149
150/**
151 * Reasoning guide table plus the effort sentences on that same page.
152 * Hybrid with no listed levels is a toggle that can be turned off.
153 * Hybrid plus `accepts only` levels is effort. Adjustable effort uses the
154 * levels in the type definition. Reasoning-only rows name no request field.
155 */
156export function parseTogetherReasoning(
157 markdown: string,
158): Map<string, ModelReasoning> {
159 const prose = stripFences(markdown)
160 const defined = prose.match(/Adjustable effort:[\s\S]*?\(([^)]*)\)/)
161 const defaultEfforts = defined ? quotedLevels(defined[1] ?? '') : []
162 const namedEfforts = new Map<string, Array<string>>()
163 for (const match of prose.matchAll(
164 /([A-Za-z0-9][A-Za-z0-9. +-]{2,80}?) accepts only ((?:`?"[a-z0-9]+"`?(?:, | and )?)+) for `reasoning_effort`/g,
165 )) {
166 const name = match[1]?.trim()
167 const levels = quotedLevels(match[2] ?? '')
168 if (name && levels.length > 0) namedEfforts.set(name, levels)
169 }
170 const out = new Map<string, ModelReasoning>()
171 for (const cells of markdownTableRows(
172 section(markdown, 'Supported models'),
173 )) {
174 const name = clean(cells[0] ?? '')
175 const id = modelId(cells[1] ?? '')
176 const type = clean(cells[2] ?? '')
177 if (!id || !name || name === 'Model') continue
178 const levels = namedEfforts.get(name)
179 if (/^hybrid\b/i.test(type) && levels && levels.length > 0) {
180 out.set(id, { mode: 'effort', mandatory: false, efforts: levels })
181 } else if (/^hybrid\b/i.test(type)) {
182 out.set(id, { mode: 'toggle', mandatory: false })
183 } else if (/adjustable effort/i.test(type) && defaultEfforts.length > 0) {
184 out.set(id, {
185 mode: 'effort',
186 mandatory: null,
187 efforts: levels ?? defaultEfforts,
188 })
189 }
190 }
191 return out
192}
193
194/** An explicit own-host family contract binds only native catalog family names. */
195export function parseTogetherGptOssFamily(
196 markdown: string,
197): ModelReasoning | null {
198 const prose = stripFences(markdown)
199 if (
200 !/^GPT-OSS models support a `reasoning_effort` parameter that controls how much computation the model spends on reasoning\./m.test(
201 prose,
202 )
203 )
204 return null
205 const definition = prose.match(
206 /^\* \*\*Adjustable effort:\*\* Supports the `reasoning_effort` parameter to control reasoning depth \(([^)]*)\)\./m,
207 )
208 const efforts = definition ? quotedLevels(definition[1] ?? '') : []
209 if (!efforts.length)
210 throw new Error('together: native GPT-OSS effort values missing')
211 return { mode: 'effort', mandatory: null, efforts }
212}
213
214export function togetherGptOssFamilyMatches(
215 displayName: string | null,
216): boolean {
217 return (
218 typeof displayName === 'string' &&
219 /^(?:OpenAI )?GPT-OSS \d+B$/i.test(displayName)
220 )
221}
222
223/** Additional dedicated controls require a named native operational disable contract. */
224export function parseTogetherNamedHybrid(
225 markdown: string,
226): { nativeBasename: string; reasoning: ModelReasoning } | null {
227 const prose = stripFences(markdown)
228 const supported = prose.match(
229 /^Additional reasoning models,[^\n]* and (DeepSeek V[\d.]+) \(hybrid\), are available for \[dedicated model inference\]/m,
230 )?.[1]
231 if (!supported) return null
232 const operational = prose.match(
233 /^\s*For (DeepSeek V[\d.]+), function calling only works in non-reasoning mode \(`reasoning=\{"enabled": False\}`\)\./m,
234 )?.[1]
235 if (
236 operational !== supported ||
237 !/^\* \*\*Hybrid:\*\* Supports both reasoning and non-reasoning modes via `reasoning=\{"enabled": True\/False\}`\./m.test(
238 prose,
239 )
240 )
241 throw new Error('together: named hybrid enable/disable contract missing')
242 return {
243 nativeBasename: supported.replace(' ', '-'),
244 reasoning: { mode: 'toggle', mandatory: false },
245 }
246}
247export function togetherNamedHybridMatches(
248 rawId: string,
249 nativeBasename: string,
250): boolean {
251 return rawId === 'deepseek-ai/' + nativeBasename
252}
253
254export function parseTogetherFamilyThinking(markdown: string): {
255 effort: ThinkingRequest | null
256 hybrid: ThinkingRequest | null
257} {
258 const prose = stripFences(markdown)
259 const gpt = parseTogetherGptOssFamily(markdown)
260 const effortField = prose.match(
261 /^GPT-OSS models support a `([a-z_]+)` parameter/m,
262 )?.[1]
263 const high = gpt?.efforts?.find((value) => value === 'high')
264 const hybrid = parseTogetherNamedHybrid(markdown)
265 const hybridWire = prose.match(
266 /^\* \*\*Hybrid:\*\* Supports both reasoning and non-reasoning modes via `([a-z_]+)=\{"([a-z_]+)": (True)\/(False)\}`\./m,
267 )
268 return {
269 effort:
270 gpt && effortField && high
271 ? { on: { [effortField]: high }, off: null, levels: null }
272 : null,
273 hybrid:
274 hybrid && hybridWire?.[1] && hybridWire[2]
275 ? {
276 on: {
277 [hybridWire[1]]: { [hybridWire[2]]: hybridWire[3] === 'True' },
278 },
279 off: {
280 [hybridWire[1]]: { [hybridWire[2]]: hybridWire[4] === 'True' },
281 },
282 levels: null,
283 }
284 : null,
285 }
286}
287
288/**
289 * One quickstart page. A single `The model ID is` wins. Otherwise only
290 * model ids in that page's effort section are used, so a sibling variant
291 * named in the intro does not inherit the flagship's levels.
292 */
293export function parseTogetherQuickstartReasoning(
294 markdown: string,
295): Map<string, ModelReasoning> {
296 const prose = stripFences(markdown)
297 let efforts: Array<string> | null = null
298 for (const cells of markdownTableRows(prose)) {
299 if (clean(cells[0] ?? '') !== 'reasoning_effort') continue
300 const levels = quotedLevels(cells.slice(1).join(' '))
301 if (levels.length > 0) efforts = levels
302 }
303 if (!efforts) {
304 const accepts = prose.match(/`reasoning_effort` accepts ([^.\n]+)/)
305 const levels = quotedLevels(accepts?.[1] ?? '')
306 if (levels.length > 0) efforts = levels
307 }
308 const named = prose.match(/The model ID is `([^`]+)`/)
309 const ids = named?.[1]?.includes('/')
310 ? [named[1]]
311 : quickstartSectionIds(markdown)
312 const out = new Map<string, ModelReasoning>()
313 if (!efforts || efforts.length === 0 || ids.length === 0) return out
314 const mandatory = /cannot be disabled/i.test(prose)
315 ? true
316 : /disables thinking/i.test(prose)
317 ? false
318 : null
319 for (const id of ids) {
320 out.set(id, { mode: 'effort', mandatory, efforts })
321 }
322 return out
323}
324
325function quickstartSectionIds(markdown: string): Array<string> {
326 const block =
327 section(markdown, 'Set the reasoning effort') ||
328 section(markdown, 'Set the thinking effort') ||
329 section(markdown, 'Reasoning effort')
330 const ids = new Set<string>()
331 for (const match of block.matchAll(/model[=:]\s*["']([^"']+)["']/g)) {
332 const id = match[1]
333 if (id?.includes('/')) ids.add(id)
334 }
335 return [...ids]
336}
337
338async function readDoc(
339 url: string,
340): Promise<{ markdown: string; hash: string }> {
341 const markdown = await fetchText(url, { headers: DOC_HEADERS })
342 return { markdown, hash: await sha256Text(markdown) }
343}
344
345export async function loadTogetherServerlessChat(
346 kv: KVNamespace | undefined,
347 cached: typeof cachedDocs,
348): Promise<TogetherDocsBundle> {
349 // `#serverless-chat` keeps this shape off the media parser's cache entry.
350 return cached(kv, `${TOGETHER_MODELS_DOCS_URL}#serverless-chat`, async () => {
351 const { markdown, hash } = await readDoc(TOGETHER_MODELS_DOCS_URL)
352 const chat = parseTogetherChatCatalog(markdown)
353 assertParsed(chat, 'together serverless chat catalog')
354 // Records, not Maps: cachedDocs stores JSON, and a Map serialises to {}.
355 return {
356 chat: Object.fromEntries(chat),
357 vision: Object.fromEntries(parseTogetherVisionModalities(markdown)),
358 hash,
359 extractedAt: new Date().toISOString(),
360 }
361 })
362}
363
364export async function loadTogetherReasoningPage(
365 kv: KVNamespace | undefined,
366 cached: typeof cachedDocs,
367): Promise<{
368 byId: Record<string, ModelReasoning>
369 gptOssFamily: ModelReasoning | null
370 namedHybrid: ReturnType<typeof parseTogetherNamedHybrid>
371 familyThinking: ReturnType<typeof parseTogetherFamilyThinking>
372 hash: string
373}> {
374 return cached(kv, `${TOGETHER_REASONING_URL}#named-families-v1`, async () => {
375 const { markdown, hash } = await readDoc(TOGETHER_REASONING_URL)
376 const parsed = parseTogetherReasoning(markdown)
377 assertParsed(parsed, 'together reasoning guide')
378 // Records, not Maps: cachedDocs stores JSON, and a Map serialises to {}.
379 return {
380 byId: Object.fromEntries(parsed),
381 gptOssFamily: parseTogetherGptOssFamily(markdown),
382 namedHybrid: parseTogetherNamedHybrid(markdown),
383 familyThinking: parseTogetherFamilyThinking(markdown),
384 hash,
385 }
386 })
387}
388
389export async function loadTogetherQuickstart(
390 kv: KVNamespace | undefined,
391 cached: typeof cachedDocs,
392 url: string,
393): Promise<{ byId: Record<string, ModelReasoning>; hash: string }> {
394 return cached(kv, url, async () => {
395 const { markdown, hash } = await readDoc(url)
396 const parsed = parseTogetherQuickstartReasoning(markdown)
397 assertParsed(parsed, url)
398 return { byId: Object.fromEntries(parsed), hash }
399 })
400}
401
402function docsSource(url: string, hash: string, path: string): FactSource {
403 return { derivation: 'docs-derived', sourceUrl: url, sourceHash: hash, path }
404}
405
406function unionFlag(
407 capabilities: Array<string> | null,
408 flag: string,
409): Array<string> {
410 if (capabilities?.includes(flag)) return capabilities
411 return [...(capabilities ?? []), flag]
412}
413
414function positiveRates(row: TogetherChatRow): Record<string, number> {
415 const rates: Record<string, number> = {}
416 if (row.inputPerMillion != null)
417 rates.input_tokens = row.inputPerMillion / 1e6
418 if (row.outputPerMillion != null) {
419 rates.output_tokens = row.outputPerMillion / 1e6
420 }
421 if (row.cachedPerMillion != null) {
422 rates.cache_read_tokens = row.cachedPerMillion / 1e6
423 }
424 return rates
425}
426
427/**
428 * Fill only facts the listing left empty. A docs outage marks those facts
429 * unavailable so a stored docs value is kept. Listing numbers are not touched.
430 */
431export function applyTogetherDocs(
432 model: ModelInfo,
433 chat: TogetherDocsBundle | null,
434 reasoning: Map<string, TogetherReasoningHit> | null,
435 reasoningPage: { loaded: boolean; hash: string } | null,
436): ModelInfo {
437 const next: ModelInfo = {
438 ...model,
439 factSources: { ...(model.factSources ?? {}) },
440 }
441 const sources: ModelFactSources = next.factSources ?? {}
442 const absent = { ...(model.absent ?? {}) }
443 const chatRow = chat?.chat[model.rawId]
444 if (model.contextWindow == null) {
445 if (chatRow?.contextWindow != null && chat) {
446 next.contextWindow = chatRow.contextWindow
447 sources.contextWindow = docsSource(
448 TOGETHER_MODELS_DOCS_URL,
449 chat.hash,
450 'Chat models',
451 )
452 } else if (!chat && model.activity === 'chat') {
453 absent.contextWindow = 'unavailable'
454 }
455 }
456 if (next.pricing == null && model.activity === 'chat') {
457 if (
458 chat &&
459 chatRow != null &&
460 chatRow.inputPerMillion != null &&
461 chatRow.outputPerMillion != null
462 ) {
463 const card = compileTokenCard(positiveRates(chatRow), [], {
464 url: TOGETHER_MODELS_DOCS_URL,
465 hash: chat.hash,
466 extractedAt: chat.extractedAt,
467 })
468 if (card) {
469 next.pricing = card
470 sources.pricing = docsSource(
471 TOGETHER_MODELS_DOCS_URL,
472 chat.hash,
473 'Chat models',
474 )
475 }
476 } else if (!chat) {
477 absent.pricing = 'unavailable'
478 }
479 }
480 if (next.modalities == null) {
481 if (chat && model.rawId in chat.vision) {
482 next.modalities = chat.vision[model.rawId]
483 sources.modalities = docsSource(
484 TOGETHER_MODELS_DOCS_URL,
485 chat.hash,
486 'Vision models',
487 )
488 } else if (!chat && model.activity === 'chat') {
489 absent.modalities = 'unavailable'
490 }
491 }
492 const hit = reasoning?.get(model.rawId)
493 if (hit) {
494 if (
495 next.unsupportedCapabilities?.includes('reasoning') ||
496 (isCapabilityMap(next.capabilities) &&
497 next.capabilities.reasoning === false)
498 )
499 throw new Error(
500 'together: native controls contradict existing explicit reasoning rejection',
501 )
502 next.reasoning = hit.reasoning
503 sources.reasoning = docsSource(hit.sourceUrl, hit.sourceHash, 'reasoning')
504 if ('thinking' in hit) {
505 next.requestMap = {
506 ...(next.requestMap ?? {
507 thinking: null,
508 maxTokensField: null,
509 developerRole: null,
510 replayReasoningContent: null,
511 store: null,
512 strictTools: null,
513 sessionAffinity: null,
514 cacheControl: null,
515 toolStream: null,
516 reasoningEffort: null,
517 }),
518 thinking: hit.thinking ?? null,
519 }
520 sources.requestMapFields = {
521 ...sources.requestMapFields,
522 thinking: docsSource(
523 hit.sourceUrl,
524 hit.sourceHash,
525 'native named-family caller control declaration',
526 ),
527 }
528 }
529 const flags = Array.isArray(next.capabilities)
530 ? next.capabilities.filter(
531 (flag): flag is string => typeof flag === 'string',
532 )
533 : null
534 next.capabilities = isCapabilityMap(next.capabilities)
535 ? { ...next.capabilities, reasoning: true }
536 : unionFlag(flags, 'reasoning')
537 sources.capabilities = {
538 ...(sources.capabilities ?? {}),
539 reasoning: docsSource(hit.sourceUrl, hit.sourceHash, 'reasoning'),
540 }
541 } else if (!reasoningPage?.loaded && model.activity === 'chat') {
542 absent.reasoning = 'unavailable'
543 } else if (
544 reasoningPage?.loaded &&
545 Array.isArray(next.capabilities) &&
546 next.capabilities.includes('reasoning')
547 ) {
548 sources.reasoning = docsSource(
549 TOGETHER_REASONING_URL,
550 reasoningPage.hash,
551 'silent',
552 )
553 }
554 if (Object.keys(absent).length > 0) next.absent = absent
555 else delete next.absent
556 if (Object.keys(sources).length === 0) delete next.factSources
557 else next.factSources = sources
558 return next
559}
560
561export function reasoningHit(
562 reasoning: ModelReasoning,
563 sourceUrl: string,
564 sourceHash: string,
565 thinking?: ThinkingRequest | null,
566): TogetherReasoningHit {
567 return {
568 reasoning,
569 sourceUrl,
570 sourceHash,
571 ...(thinking !== undefined ? { thinking } : {}),
572 }
573}
574
575const TOGETHER_SUPPORTED_URL = 'https://api.together.ai/v2/supported-models'
576
577/** Supported-models is a listing. `tagDocsFacts` stamps docs-derived; restamp it. */
578export function supportedFactSources(
579 facts: Pick<ModelInfo, 'modalities' | 'capabilities'>,
580): ModelFactSources {
581 const tagged = tagDocsFacts(facts, TOGETHER_SUPPORTED_URL)
582 const asListing = (source: FactSource): FactSource => ({
583 ...source,
584 derivation: 'listing',
585 })
586 const capabilities = tagged.capabilities
587 ? Object.fromEntries(
588 Object.entries(tagged.capabilities).map(([flag, source]) => [
589 flag,
590 asListing(source),
591 ]),
592 )
593 : undefined
594 return {
595 ...(tagged.modalities ? { modalities: asListing(tagged.modalities) } : {}),
596 ...(capabilities ? { capabilities } : {}),
597 }
598}