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

together-facts.ts

600 lines19.8 KB

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
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
59​
60export interface TogetherReasoningHit {
61 reasoning: ModelReasoning
62 sourceUrl: string
63 sourceHash: string
64 thinking?: ThinkingRequest | null
66​
67function section(markdown: string, heading: string): string {
68 const text = markdown.startsWith('## ') ? `\n${markdown}` : markdown
69 return markdownSection(text, heading)
71​
72function stripFences(markdown: string): string {
73 return markdown.replace(/```[\s\S]*?```/g, '')
75​
76function clean(cell: string): string {
77 return cell.replace(/\\/g, '').replace(/`/g, '').replace(/\s+/g, ' ').trim()
79​
80function modelId(cell: string): string | null {
81 const id = clean(cell)
82 return /^[A-Za-z0-9][\w.+-]*\/[\w.+-]+$/.test(id) ? id : null
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
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
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
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
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
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
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 }
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 )
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 // The note was a line inside <Info> tags; the .md export now renders it
233 // as a `> [!NOTE]` blockquote. Both forms match.
234 const operational = prose.match(
235 /^\s*(?:>\s*)?For (DeepSeek V[\d.]+), function calling only works in non-reasoning mode \(`reasoning=\{"enabled": False\}`\)\./m,
236 )?.[1]
237 if (
238 operational !== supported ||
239 !/^\* \*\*Hybrid:\*\* Supports both reasoning and non-reasoning modes via `reasoning=\{"enabled": True\/False\}`\./m.test(
240 prose,
241 )
242 )
243 throw new Error('together: named hybrid enable/disable contract missing')
244 return {
245 nativeBasename: supported.replace(' ', '-'),
246 reasoning: { mode: 'toggle', mandatory: false },
247 }
249export function togetherNamedHybridMatches(
250 rawId: string,
251 nativeBasename: string,
252): boolean {
253 return rawId === 'deepseek-ai/' + nativeBasename
255​
256export function parseTogetherFamilyThinking(markdown: string): {
257 effort: ThinkingRequest | null
258 hybrid: ThinkingRequest | null
259} {
260 const prose = stripFences(markdown)
261 const gpt = parseTogetherGptOssFamily(markdown)
262 const effortField = prose.match(
263 /^GPT-OSS models support a `([a-z_]+)` parameter/m,
264 )?.[1]
265 const high = gpt?.efforts?.find((value) => value === 'high')
266 const hybrid = parseTogetherNamedHybrid(markdown)
267 const hybridWire = prose.match(
268 /^\* \*\*Hybrid:\*\* Supports both reasoning and non-reasoning modes via `([a-z_]+)=\{"([a-z_]+)": (True)\/(False)\}`\./m,
269 )
270 return {
271 effort:
272 gpt && effortField && high
273 ? { on: { [effortField]: high }, off: null, levels: null }
274 : null,
275 hybrid:
276 hybrid && hybridWire?.[1] && hybridWire[2]
277 ? {
278 on: {
279 [hybridWire[1]]: { [hybridWire[2]]: hybridWire[3] === 'True' },
280 },
281 off: {
282 [hybridWire[1]]: { [hybridWire[2]]: hybridWire[4] === 'True' },
283 },
284 levels: null,
285 }
286 : null,
287 }
289​
290/**
291 * One quickstart page. A single `The model ID is` wins. Otherwise only
292 * model ids in that page's effort section are used, so a sibling variant
293 * named in the intro does not inherit the flagship's levels.
294 */
295export function parseTogetherQuickstartReasoning(
296 markdown: string,
297): Map<string, ModelReasoning> {
298 const prose = stripFences(markdown)
299 let efforts: Array<string> | null = null
300 for (const cells of markdownTableRows(prose)) {
301 if (clean(cells[0] ?? '') !== 'reasoning_effort') continue
302 const levels = quotedLevels(cells.slice(1).join(' '))
303 if (levels.length > 0) efforts = levels
304 }
305 if (!efforts) {
306 const accepts = prose.match(/`reasoning_effort` accepts ([^.\n]+)/)
307 const levels = quotedLevels(accepts?.[1] ?? '')
308 if (levels.length > 0) efforts = levels
309 }
310 const named = prose.match(/The model ID is `([^`]+)`/)
311 const ids = named?.[1]?.includes('/')
312 ? [named[1]]
313 : quickstartSectionIds(markdown)
314 const out = new Map<string, ModelReasoning>()
315 if (!efforts || efforts.length === 0 || ids.length === 0) return out
316 const mandatory = /cannot be disabled/i.test(prose)
317 ? true
318 : /disables thinking/i.test(prose)
319 ? false
320 : null
321 for (const id of ids) {
322 out.set(id, { mode: 'effort', mandatory, efforts })
323 }
324 return out
326​
327function quickstartSectionIds(markdown: string): Array<string> {
328 const block =
329 section(markdown, 'Set the reasoning effort') ||
330 section(markdown, 'Set the thinking effort') ||
331 section(markdown, 'Reasoning effort')
332 const ids = new Set<string>()
333 for (const match of block.matchAll(/model[=:]\s*["']([^"']+)["']/g)) {
334 const id = match[1]
335 if (id?.includes('/')) ids.add(id)
336 }
337 return [...ids]
339​
340async function readDoc(
341 url: string,
342): Promise<{ markdown: string; hash: string }> {
343 const markdown = await fetchText(url, { headers: DOC_HEADERS })
344 return { markdown, hash: await sha256Text(markdown) }
346​
347export async function loadTogetherServerlessChat(
348 kv: KVNamespace | undefined,
349 cached: typeof cachedDocs,
350): Promise<TogetherDocsBundle> {
351 // `#serverless-chat` keeps this shape off the media parser's cache entry.
352 return cached(kv, `${TOGETHER_MODELS_DOCS_URL}#serverless-chat`, async () => {
353 const { markdown, hash } = await readDoc(TOGETHER_MODELS_DOCS_URL)
354 const chat = parseTogetherChatCatalog(markdown)
355 assertParsed(chat, 'together serverless chat catalog')
356 // Records, not Maps: cachedDocs stores JSON, and a Map serialises to {}.
357 return {
358 chat: Object.fromEntries(chat),
359 vision: Object.fromEntries(parseTogetherVisionModalities(markdown)),
360 hash,
361 extractedAt: new Date().toISOString(),
362 }
363 })
365​
366export async function loadTogetherReasoningPage(
367 kv: KVNamespace | undefined,
368 cached: typeof cachedDocs,
369): Promise<{
370 byId: Record<string, ModelReasoning>
371 gptOssFamily: ModelReasoning | null
372 namedHybrid: ReturnType<typeof parseTogetherNamedHybrid>
373 familyThinking: ReturnType<typeof parseTogetherFamilyThinking>
374 hash: string
375}> {
376 return cached(kv, `${TOGETHER_REASONING_URL}#named-families-v1`, async () => {
377 const { markdown, hash } = await readDoc(TOGETHER_REASONING_URL)
378 const parsed = parseTogetherReasoning(markdown)
379 assertParsed(parsed, 'together reasoning guide')
380 // Records, not Maps: cachedDocs stores JSON, and a Map serialises to {}.
381 return {
382 byId: Object.fromEntries(parsed),
383 gptOssFamily: parseTogetherGptOssFamily(markdown),
384 namedHybrid: parseTogetherNamedHybrid(markdown),
385 familyThinking: parseTogetherFamilyThinking(markdown),
386 hash,
387 }
388 })
390​
391export async function loadTogetherQuickstart(
392 kv: KVNamespace | undefined,
393 cached: typeof cachedDocs,
394 url: string,
395): Promise<{ byId: Record<string, ModelReasoning>; hash: string }> {
396 return cached(kv, url, async () => {
397 const { markdown, hash } = await readDoc(url)
398 const parsed = parseTogetherQuickstartReasoning(markdown)
399 assertParsed(parsed, url)
400 return { byId: Object.fromEntries(parsed), hash }
401 })
403​
404function docsSource(url: string, hash: string, path: string): FactSource {
405 return { derivation: 'docs-derived', sourceUrl: url, sourceHash: hash, path }
407​
408function unionFlag(
409 capabilities: Array<string> | null,
410 flag: string,
411): Array<string> {
412 if (capabilities?.includes(flag)) return capabilities
413 return [...(capabilities ?? []), flag]
415​
416function positiveRates(row: TogetherChatRow): Record<string, number> {
417 const rates: Record<string, number> = {}
418 if (row.inputPerMillion != null)
419 rates.input_tokens = row.inputPerMillion / 1e6
420 if (row.outputPerMillion != null) {
421 rates.output_tokens = row.outputPerMillion / 1e6
422 }
423 if (row.cachedPerMillion != null) {
424 rates.cache_read_tokens = row.cachedPerMillion / 1e6
425 }
426 return rates
428​
429/**
430 * Fill only facts the listing left empty. A docs outage marks those facts
431 * unavailable so a stored docs value is kept. Listing numbers are not touched.
432 */
433export function applyTogetherDocs(
434 model: ModelInfo,
435 chat: TogetherDocsBundle | null,
436 reasoning: Map<string, TogetherReasoningHit> | null,
437 reasoningPage: { loaded: boolean; hash: string } | null,
438): ModelInfo {
439 const next: ModelInfo = {
440 ...model,
441 factSources: { ...(model.factSources ?? {}) },
442 }
443 const sources: ModelFactSources = next.factSources ?? {}
444 const absent = { ...(model.absent ?? {}) }
445 const chatRow = chat?.chat[model.rawId]
446 if (model.contextWindow == null) {
447 if (chatRow?.contextWindow != null && chat) {
448 next.contextWindow = chatRow.contextWindow
449 sources.contextWindow = docsSource(
450 TOGETHER_MODELS_DOCS_URL,
451 chat.hash,
452 'Chat models',
453 )
454 } else if (!chat && model.activity === 'chat') {
455 absent.contextWindow = 'unavailable'
456 }
457 }
458 if (next.pricing == null && model.activity === 'chat') {
459 if (
460 chat &&
461 chatRow != null &&
462 chatRow.inputPerMillion != null &&
463 chatRow.outputPerMillion != null
464 ) {
465 const card = compileTokenCard(positiveRates(chatRow), [], {
466 url: TOGETHER_MODELS_DOCS_URL,
467 hash: chat.hash,
468 extractedAt: chat.extractedAt,
469 })
470 if (card) {
471 next.pricing = card
472 sources.pricing = docsSource(
473 TOGETHER_MODELS_DOCS_URL,
474 chat.hash,
475 'Chat models',
476 )
477 }
478 } else if (!chat) {
479 absent.pricing = 'unavailable'
480 }
481 }
482 if (next.modalities == null) {
483 if (chat && model.rawId in chat.vision) {
484 next.modalities = chat.vision[model.rawId]
485 sources.modalities = docsSource(
486 TOGETHER_MODELS_DOCS_URL,
487 chat.hash,
488 'Vision models',
489 )
490 } else if (!chat && model.activity === 'chat') {
491 absent.modalities = 'unavailable'
492 }
493 }
494 const hit = reasoning?.get(model.rawId)
495 if (hit) {
496 if (
497 next.unsupportedCapabilities?.includes('reasoning') ||
498 (isCapabilityMap(next.capabilities) &&
499 next.capabilities.reasoning === false)
500 )
501 throw new Error(
502 'together: native controls contradict existing explicit reasoning rejection',
503 )
504 next.reasoning = hit.reasoning
505 sources.reasoning = docsSource(hit.sourceUrl, hit.sourceHash, 'reasoning')
506 if ('thinking' in hit) {
507 next.requestMap = {
508 ...(next.requestMap ?? {
509 thinking: null,
510 maxTokensField: null,
511 developerRole: null,
512 replayReasoningContent: null,
513 store: null,
514 strictTools: null,
515 sessionAffinity: null,
516 cacheControl: null,
517 toolStream: null,
518 reasoningEffort: null,
519 }),
520 thinking: hit.thinking ?? null,
521 }
522 sources.requestMapFields = {
523 ...sources.requestMapFields,
524 thinking: docsSource(
525 hit.sourceUrl,
526 hit.sourceHash,
527 'native named-family caller control declaration',
528 ),
529 }
530 }
531 const flags = Array.isArray(next.capabilities)
532 ? next.capabilities.filter(
533 (flag): flag is string => typeof flag === 'string',
534 )
535 : null
536 next.capabilities = isCapabilityMap(next.capabilities)
537 ? { ...next.capabilities, reasoning: true }
538 : unionFlag(flags, 'reasoning')
539 sources.capabilities = {
540 ...(sources.capabilities ?? {}),
541 reasoning: docsSource(hit.sourceUrl, hit.sourceHash, 'reasoning'),
542 }
543 } else if (!reasoningPage?.loaded && model.activity === 'chat') {
544 absent.reasoning = 'unavailable'
545 } else if (
546 reasoningPage?.loaded &&
547 Array.isArray(next.capabilities) &&
548 next.capabilities.includes('reasoning')
549 ) {
550 sources.reasoning = docsSource(
551 TOGETHER_REASONING_URL,
552 reasoningPage.hash,
553 'silent',
554 )
555 }
556 if (Object.keys(absent).length > 0) next.absent = absent
557 else delete next.absent
558 if (Object.keys(sources).length === 0) delete next.factSources
559 else next.factSources = sources
560 return next
562​
563export function reasoningHit(
564 reasoning: ModelReasoning,
565 sourceUrl: string,
566 sourceHash: string,
567 thinking?: ThinkingRequest | null,
568): TogetherReasoningHit {
569 return {
570 reasoning,
571 sourceUrl,
572 sourceHash,
573 ...(thinking !== undefined ? { thinking } : {}),
574 }
576​
577const TOGETHER_SUPPORTED_URL = 'https://api.together.ai/v2/supported-models'
578​
579/** Supported-models is a listing. `tagDocsFacts` stamps docs-derived; restamp it. */
580export function supportedFactSources(
581 facts: Pick<ModelInfo, 'modalities' | 'capabilities'>,
582): ModelFactSources {
583 const tagged = tagDocsFacts(facts, TOGETHER_SUPPORTED_URL)
584 const asListing = (source: FactSource): FactSource => ({
585 ...source,
586 derivation: 'listing',
587 })
588 const capabilities = tagged.capabilities
589 ? Object.fromEntries(
590 Object.entries(tagged.capabilities).map(([flag, source]) => [
591 flag,
592 asListing(source),
593 ]),
594 )
595 : undefined
596 return {
597 ...(tagged.modalities ? { modalities: asListing(tagged.modalities) } : {}),
598 ...(capabilities ? { capabilities } : {}),
599 }