Open History to see the last commit
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
21}
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 ),
34]
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 sentence
94 .trim()
95 .startsWith(
96 'Return the complete assistant message on every turn, `reasoning_content` included',
97 ),
98 ) &&
99 modelsInSamples(history).includes(named)
100 )
101 replay.add(named)
102 return { ids: [...ids], replay: [...replay] }
103}
104export async function togetherNativeThinking(
105 kv?: KVNamespace,
106): Promise<Array<Evidence>> {
107 return Promise.all(
108 [
109 TOGETHER_DEEPSEEK_URL,
110 TOGETHER_GLM_URL,
111 TOGETHER_NATIVE_REASONING_URL,
112 TOGETHER_KIMI_REPLAY_URL,
113 ].map((url) =>
114 cachedDocs(kv, `${url}#native-thinking`, async () => {
115 const markdown = await fetchText(url, {
116 signal: AbortSignal.timeout(20_000),
117 })
118 const facts = parseTogetherNativeThinking(markdown)
119 if (!facts.ids.length && !facts.replay.length)
120 throw new Error(
121 `together native thinking: parsed no evidence from ${url}`,
122 )
123 return { ...facts, url, hash: await sha256Text(markdown) }
124 }),
125 ),
126 )
127}
128export function applyTogetherNativeThinking(
129 model: ModelInfo,
130 docs: Array<Evidence>,
131): ModelInfo {
132 if (model.activity !== 'chat') return model
133 const reason = docs.find((doc) => doc.ids.includes(model.rawId))
134 const replay = docs.find((doc) => doc.replay.includes(model.rawId))
135 if (!reason && !replay) return model
136 if (replay && model.requestMap?.replayReasoningContent === false)
137 throw new Error(
138 'together: native replay contradicts existing explicit rejection',
139 )
140 const nativeReasoning = !!reason
141 if (
142 nativeReasoning &&
143 (model.unsupportedCapabilities?.includes('reasoning') ||
144 (isCapabilityMap(model.capabilities) &&
145 model.capabilities.reasoning === false))
146 ) {
147 throw new Error(
148 'together: native reasoning contradicts existing explicit rejection',
149 )
150 }
151 const capabilities = isCapabilityMap(model.capabilities)
152 ? { ...model.capabilities, reasoning: true }
153 : [
154 ...new Set([
155 ...(Array.isArray(model.capabilities)
156 ? (model.capabilities as Array<string>)
157 : []),
158 'reasoning',
159 ]),
160 ]
161 const source = (doc: Evidence, path: string) => ({
162 derivation: 'docs-derived' as const,
163 sourceUrl: doc.url,
164 sourceHash: doc.hash,
165 path,
166 })
167 const map: ChatRequestMap | null =
168 model.requestMap ??
169 (replay
170 ? {
171 thinking: null,
172 maxTokensField: null,
173 developerRole: null,
174 replayReasoningContent: null,
175 store: null,
176 strictTools: null,
177 sessionAffinity: null,
178 cacheControl: null,
179 toolStream: null,
180 reasoningEffort: null,
181 }
182 : null)
183 return {
184 ...model,
185 ...(reason
186 ? {
187 capabilities,
188 }
189 : {}),
190 requestMap: map && replay ? { ...map, replayReasoningContent: true } : map,
191 factSources: {
192 ...model.factSources,
193 ...(reason
194 ? {
195 capabilities: {
196 ...model.factSources?.capabilities,
197 reasoning: source(reason, 'Native model reasoning'),
198 },
199 }
200 : {}),
201 ...(replay
202 ? {
203 requestMapFields: {
204 ...model.factSources?.requestMapFields,
205 replayReasoningContent: source(
206 replay,
207 'Preserved thinking / multi-turn function calling',
208 ),
209 },
210 }
211 : {}),
212 },
213 }
214}