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

together-native-thinking.ts

212 lines6.5 KB

1import { isCapabilityMap } from '#/lib/capabilities.ts'
2/** Host-owned reasoning and replay evidence, independently of mode controls. */
3import { cachedDocs, markdownTableRows } from './model-facts.ts'
4import { fetchText, sha256Text } from './types.ts'
5import type { ChatRequestMap } from './request-map.ts'
6import type { ModelInfo } from './types.ts'
7​
8export const TOGETHER_KIMI_REPLAY_URL =
9 'https://docs.together.ai/docs/kimi-k3-quickstart.md'
10export const TOGETHER_DEEPSEEK_URL =
11 'https://docs.together.ai/docs/deepseek-v4-quickstart.md'
12export const TOGETHER_GLM_URL =
13 'https://docs.together.ai/docs/glm-5.3-quickstart.md'
14export const TOGETHER_NATIVE_REASONING_URL =
15 'https://docs.together.ai/docs/inference/chat/reasoning.md'
16interface Evidence {
17 ids: Array<string>
18 replay: Array<string>
19 hash: string
20 url: string
22const normativeSentences = (text: string): string[] =>
23 text
24 .replace(/```[\s\S]*?```/g, '')
25 .replace(/<[^>]+>/g, '')
26 .split(/[.!?]\s+|\n/)
27 .map((sentence) => sentence.trim())
28const modelsInSamples = (text: string): Array<string> => [
29 ...new Set(
30 [...text.matchAll(/model[=:]\s*["']([\w.+-]+\/[\w.+-]+)["']/g)].flatMap(
31 (match) => (match[1] ? [match[1]] : []),
32 ),
33 ),
35export function parseTogetherNativeThinking(
36 markdown: string,
37): Pick<Evidence, 'ids' | 'replay'> {
38 const intro = markdown.split(/^## /m)[0] ?? ''
39 const named = intro.match(/The model ID is `([^`]+)`/)?.[1]
40 const ids = new Set<string>()
41 if (named && /reasoning/i.test(intro)) ids.add(named)
42 if (/Thinking is on by default/i.test(intro)) {
43 for (const row of markdownTableRows(intro)) {
44 if (!row[1]) continue
45 const id = row[1].replace(/`/g, '').trim()
46 if (/^[\w.+-]+\/[\w.+-]+$/.test(id)) ids.add(id)
47 }
48 }
49 const replay = new Set<string>()
50 const preserved =
51 markdown.match(
52 /^### Preserved thinking\s*\n([\s\S]*?)(?=^###? |(?![\s\S]))/m,
53 )?.[1] ??
54 markdown.match(
55 /^## (?:Preserved thinking|Preserve thinking across turns)\s*\n([\s\S]*?)(?=^## |(?![\s\S]))/m,
56 )?.[1]
57 if (
58 preserved &&
59 normativeSentences(preserved).some((sentence) =>
60 /^When using preserved thinking, (?:include the unmodified|return the model's) `reasoning_content`/i.test(
61 sentence,
62 ),
63 )
64 ) {
65 for (const id of modelsInSamples(preserved)) replay.add(id)
66 }
67 // This host explicitly names reasoning_content on the next request even
68 // when its response uses the reasoning alias. Scope to the page's own ID.
69 if (
70 named &&
71 normativeSentences(markdown).some((sentence) =>
72 /^For multi-turn function calling, pass the assistant message's reasoning trace back/i.test(
73 sentence,
74 ),
75 ) &&
76 normativeSentences(markdown).some((sentence) =>
77 /^Include the assistant message's `content`, `reasoning_content`, and `tool_calls`/i.test(
78 sentence,
79 ),
80 )
81 )
82 replay.add(named)
83 const history = markdown.match(
84 /^## Preserve the thinking history\s*\n([\s\S]*?)(?=^## |(?![\s\S]))/m,
85 )?.[1]
86 if (
87 named &&
88 history &&
89 history
90 .replace(/```[\s\S]*?```/g, '')
91 .split(/[.!?]\s+|\n/)
92 .some((sentence) =>
93 /^Return the complete assistant message on every turn, `reasoning_content` included/.test(
94 sentence.trim(),
95 ),
96 ) &&
97 modelsInSamples(history).includes(named)
98 )
99 replay.add(named)
100 return { ids: [...ids], replay: [...replay] }
102export async function togetherNativeThinking(
103 kv?: KVNamespace,
104): Promise<Array<Evidence>> {
105 return Promise.all(
106 [
107 TOGETHER_DEEPSEEK_URL,
108 TOGETHER_GLM_URL,
109 TOGETHER_NATIVE_REASONING_URL,
110 TOGETHER_KIMI_REPLAY_URL,
111 ].map((url) =>
112 cachedDocs(kv, `${url}#native-thinking`, async () => {
113 const markdown = await fetchText(url, {
114 signal: AbortSignal.timeout(20_000),
115 })
116 const facts = parseTogetherNativeThinking(markdown)
117 if (!facts.ids.length && !facts.replay.length)
118 throw new Error(
119 `together native thinking: parsed no evidence from ${url}`,
120 )
121 return { ...facts, url, hash: await sha256Text(markdown) }
122 }),
123 ),
124 )
126export function applyTogetherNativeThinking(
127 model: ModelInfo,
128 docs: Array<Evidence>,
129): ModelInfo {
130 if (model.activity !== 'chat') return model
131 const reason = docs.find((doc) => doc.ids.includes(model.rawId))
132 const replay = docs.find((doc) => doc.replay.includes(model.rawId))
133 if (!reason && !replay) return model
134 if (replay && model.requestMap?.replayReasoningContent === false)
135 throw new Error(
136 'together: native replay contradicts existing explicit rejection',
137 )
138 const nativeReasoning = !!reason
139 if (
140 nativeReasoning &&
141 (model.unsupportedCapabilities?.includes('reasoning') ||
142 (isCapabilityMap(model.capabilities) &&
143 model.capabilities.reasoning === false))
144 ) {
145 throw new Error(
146 'together: native reasoning contradicts existing explicit rejection',
147 )
148 }
149 const capabilities = isCapabilityMap(model.capabilities)
150 ? { ...model.capabilities, reasoning: true }
151 : [
152 ...new Set([
153 ...(Array.isArray(model.capabilities)
154 ? (model.capabilities as Array<string>)
155 : []),
156 'reasoning',
157 ]),
158 ]
159 const source = (doc: Evidence, path: string) => ({
160 derivation: 'docs-derived' as const,
161 sourceUrl: doc.url,
162 sourceHash: doc.hash,
163 path,
164 })
165 const map: ChatRequestMap | null =
166 model.requestMap ??
167 (replay
168 ? {
169 thinking: null,
170 maxTokensField: null,
171 developerRole: null,
172 replayReasoningContent: null,
173 store: null,
174 strictTools: null,
175 sessionAffinity: null,
176 cacheControl: null,
177 toolStream: null,
178 reasoningEffort: null,
179 }
180 : null)
181 return {
182 ...model,
183 ...(reason
184 ? {
185 capabilities,
186 }
187 : {}),
188 requestMap: map && replay ? { ...map, replayReasoningContent: true } : map,
189 factSources: {
190 ...model.factSources,
191 ...(reason
192 ? {
193 capabilities: {
194 ...model.factSources?.capabilities,
195 reasoning: source(reason, 'Native model reasoning'),
196 },
197 }
198 : {}),
199 ...(replay
200 ? {
201 requestMapFields: {
202 ...model.factSources?.requestMapFields,
203 replayReasoningContent: source(
204 replay,
205 'Preserved thinking / multi-turn function calling',
206 ),
207 },
208 }
209 : {}),
210 },
211 }