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

provider-replay.ts

196 lines6.2 KB

1/** Replay facts parsed from each host's own published documentation. */
2import { cachedDocs } from './model-facts.ts'
3import type { ChatRequestMap } from './request-map.ts'
4import { fetchText, sha256Text } from './types.ts'
5import type { FactSource, ModelInfo, ModelReasoning } from './types.ts'
6​
7export const DEEPSEEK_THINKING_URL =
8 'https://api-docs.deepseek.com/guides/thinking_mode/'
9export const ZAI_THINKING_MODE_URL =
10 'https://docs.z.ai/guides/capabilities/thinking-mode.md'
11export const ZHIPU_THINKING_MODE_URL =
12 'https://docs.bigmodel.cn/cn/guide/capabilities/thinking-mode.md'
13export const KIMI_THINKING_URL =
14 'https://platform.kimi.ai/docs/guide/use-thinking-models.md'
15export const KIMI_CN_THINKING_URL =
16 'https://platform.kimi.com/docs/guide/use-thinking-models.md'
17​
18function record(value: unknown): value is Record<string, unknown> {
19 return value !== null && typeof value === 'object' && !Array.isArray(value)
21​
22/** A native model-specific effort list is a control, not evidence it is mandatory. */
23export function deepseekEffortFacts(
24 effort: unknown,
25): { reasoning: ModelReasoning; source: FactSource } | null {
26 if (effort == null) return null
27 if (!record(effort)) throw new Error('deepseek: unreadable effort metadata')
28 const levels = effort.supported_levels
29 if (levels === undefined) return null
30 if (
31 !Array.isArray(levels) ||
32 levels.length === 0 ||
33 !levels.every((level) => typeof level === 'string' && level.length > 0)
34 )
35 throw new Error('deepseek: unreadable supported_levels')
36 const efforts = levels as Array<string>
37 return {
38 reasoning: {
39 mode: 'effort',
40 mandatory: null,
41 efforts,
42 },
43 source: {
44 derivation: 'listing',
45 sourceUrl: 'https://api.deepseek.com/models',
46 path: 'data[].effort.supported_levels',
47 },
48 }
50​
51export function replayRequestMap(
52 existing?: ChatRequestMap | null,
53): ChatRequestMap {
54 const base: ChatRequestMap = {
55 thinking: null,
56 maxTokensField: null,
57 developerRole: null,
58 replayReasoningContent: true,
59 store: null,
60 strictTools: null,
61 sessionAffinity: null,
62 cacheControl: null,
63 toolStream: null,
64 reasoningEffort: null,
65 }
66 return { ...base, ...existing, replayReasoningContent: true }
68​
69function plain(text: string): string {
70 return text
71 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
72 .replace(/<[^>]+>/g, ' ')
73 .replace(/\\_/g, '_')
74 .replace(/[*`]/g, '')
75 .replace(/\s+/g, ' ')
77​
78/** The native guide requires replay with tools; without tools it says it is ignored. */
79export function parseDeepseekReplay(text: string): true {
80 const prose = plain(text)
81 if (
82 !/request carries the tools parameter.{0,240}reasoning_content.{0,160}passed back/i.test(
83 prose,
84 ) ||
85 !/does not carry the tools parameter.{0,200}reasoning_content.{0,240}ignored/i.test(
86 prose,
87 )
88 )
89 throw new Error(
90 'deepseek: thinking guide has no verified tool replay contract',
91 )
92 return true
94​
95/** Only explicitly named models are bound; no inferred model-family membership. */
96export function parseGlmReplay(text: string): Array<string> {
97 const prose = plain(text)
98 const instruction =
99 /thinking blocks.{0,150}preserv.{0,150}return.{0,150}tool results/i.test(
100 prose,
101 ) || /必须显式保留.{0,80}Reasoning content.{0,80}返回工具结果/i.test(prose)
102 if (!instruction || !prose.includes('reasoning_content'))
103 throw new Error(
104 'glm: thinking-mode guide has no verified replay instruction',
105 )
106 const section = text
107 .split(/^## /m)
108 .find((part) =>
109 /^(?:\*\*)?Default Thinking Behaviour|^默认思考行为/.test(part),
110 )
111 const ids = [
112 ...new Set(
113 (section?.match(/\bGLM-\d+(?:\.\d+)?(?:-FLASH)?\b/g) ?? []).map((id) =>
114 id.toLowerCase(),
115 ),
116 ),
117 ]
118 const interleaved = text
119 .split(/^## /m)
120 .find((part) => /^\*\*Interleaved thinking/.test(part))
121 // The native guide names the first supported model explicitly. It does
122 // not enumerate variants; only that exact id gets this tool-turn rule.
123 const since = interleaved?.match(
124 /supported since (GLM-\d+(?:\.\d+)?(?:-[A-Za-z0-9]+)*)(?![\w-]|\.\d)/,
125 )?.[1]
126 if (
127 since &&
128 /thinking blocks should be explicitly preserved/i.test(plain(interleaved))
129 )
130 ids.push(since.toLowerCase())
131 if (ids.length === 0)
132 throw new Error('glm: thinking-mode guide names no supported model ids')
133 return [...new Set(ids)]
135​
136export function parseKimiReplay(text: string): Array<string> {
137 const prose = plain(text)
138 if (
139 !prose.includes('reasoning_content') ||
140 !(
141 /complete assistant message.{0,180}(?:back|including)/i.test(prose) ||
142 /完整 assistant message.{0,80}(?:回传|reasoning_content)/i.test(prose)
143 )
144 )
145 throw new Error('kimi: thinking guide has no verified replay instruction')
146 const preamble = text.split(/^## (?:Basic calls|基本调用)/m)[0] ?? ''
147 const ids = [...new Set(preamble.match(/\bkimi-[a-z0-9][a-z0-9.-]*/g) ?? [])]
148 if (ids.length === 0)
149 throw new Error('kimi: thinking guide names no supported model ids')
150 return ids
152​
153export function explicitCardReplay(text: string): boolean {
154 return /must pass back the complete assistant message.{0,180}reasoning_content/i.test(
155 plain(text),
156 )
158​
159export async function loadReplayDoc(
160 url: string,
161 kv?: KVNamespace,
162): Promise<{ text: string; source: FactSource }> {
163 const doc = await cachedDocs(kv, url, async () => {
164 const text = await fetchText(url, { signal: AbortSignal.timeout(30_000) })
165 if (
166 /^\s*<(?:!doctype|html)/i.test(text) &&
167 !url.includes('api-docs.deepseek.com')
168 )
169 throw new Error(`replay docs: ${url} returned HTML`)
170 return { text, hash: await sha256Text(text) }
171 })
172 return {
173 text: doc.text,
174 source: {
175 derivation: 'docs-derived',
176 sourceUrl: url,
177 sourceHash: doc.hash,
178 path: 'reasoning_content',
179 },
180 }
182​
183export function applyReplay(model: ModelInfo, source: FactSource): ModelInfo {
184 return {
185 ...model,
186 requestMap: replayRequestMap(model.requestMap),
187 factSources: {
188 ...model.factSources,
189 requestMap: model.factSources?.requestMap ?? source,
190 requestMapFields: {
191 ...model.factSources?.requestMapFields,
192 replayReasoningContent: source,
193 },
194 },
195 }