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

bedrock-thinking-guides.ts

508 lines16.8 KB

1/** Controls from AWS-hosted guides, scoped by their own model tables. */
2import { nativeReasoningCapability } from './native-host-reasoning.ts'
3import { tagDocsFacts } from './fact-sources.ts'
4import {
5 markdownSection,
6 markdownTableRows,
7 tryDocs,
8 unavailable,
9} from './model-facts.ts'
10import type { DocsRun } from './model-facts.ts'
11import { fetchText, sha256Text } from './types.ts'
12import type { ModelInfo, ModelReasoning } from './types.ts'
13​
14const DOCS = 'https://docs.aws.amazon.com/bedrock/latest/userguide/'
15export const BEDROCK_EXTENDED_THINKING_URL = `${DOCS}claude-messages-extended-thinking.md`
16export const BEDROCK_NOVA_THINKING_URL =
17 'https://docs.aws.amazon.com/nova/latest/nova2-userguide/using-converse-api.md'
18export const BEDROCK_ADAPTIVE_THINKING_URL = `${DOCS}claude-messages-adaptive-thinking.md`
19export interface BedrockThinkingGuide {
20 controls: Record<string, ModelReasoning>
21 namedControls?: Record<string, ModelReasoning>
22 runtimeNamedControls?: Record<string, ModelReasoning>
23 url: string
24 hash: string
26export interface BedrockCardOwnedGroup {
27 /** Only base IDs and profile IDs explicitly declared by this one card. */
28 modelName: string | null
29 runtimeRowIds?: Array<string>
30 baseIds: Array<string>
31 rowIds: Array<string>
33​
34const prose = (text: string) => text.replace(/```[\s\S]*?```/g, '')
35const rows = (text: string) => markdownTableRows(text.replace(/[ \t]+$/gm, ''))
36const clean = (text: string) => text.replace(/[*`]/g, '').trim()
37const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
38​
39function models(text: string): Map<string, string> {
40 const beforeExamples = text.split(/^## /m)[0] ?? ''
41 const table = rows(beforeExamples)
42 const header = table[0]
43 if (header?.[0] !== 'Model' || header[1] !== 'Model ID') {
44 throw new Error(
45 'amazon-bedrock thinking guide: missing supported model table',
46 )
47 }
48 const result = new Map<string, string>()
49 for (const row of table.slice(1)) {
50 // The hosted table links each name to its model card. The label is the
51 // name the effort rows use; anything else stays fail-closed.
52 const name = row[0]
53 ?.trim()
54 .replace(/^\[([^\]]+)\]\([^)\s]+\)$/, (_, label: string) => label.trim())
55 const id = row[1]?.match(/^`(anthropic\.[a-z0-9.:-]+)`$/)?.[1]
56 if (!name || !id || row.length !== 2 || result.has(name)) {
57 throw new Error(
58 'amazon-bedrock thinking guide: unreadable supported model row',
59 )
60 }
61 result.set(name, id)
62 }
63 if (!result.size)
64 throw new Error(
65 'amazon-bedrock thinking guide: empty supported model table',
66 )
67 return result
69​
70/** Whole names only: Opus 5 is never an abbreviation for Opus 5.5. */
71function namedIds(text: string, names: Map<string, string>): Array<string> {
72 const result: Array<string> = []
73 for (const [name, id] of names) {
74 if (
75 new RegExp(`(?<![\\w.])${escape(name)}(?![\\w]|\\.\\d|\\s+\\d)`).test(
76 clean(text),
77 )
78 )
79 result.push(id)
80 }
81 return result
83​
84/** Ids a cell names; a Claude name outside the guide's model table throws. */
85function scopeIds(
86 text: string,
87 names: Map<string, string>,
88 scope: string,
89): Array<string> {
90 let unmatched = clean(text)
91 for (const name of names.keys())
92 unmatched = unmatched.replace(
93 new RegExp(`(?<![\\w.])${escape(name)}(?![\\w]|\\.\\d|\\s+\\d)`, 'g'),
94 '',
95 )
96 if (/\bClaude\s+[A-Z0-9]/.test(unmatched))
97 throw new Error(
98 `amazon-bedrock adaptive thinking: unsupported named scope for ${scope}`,
99 )
100 return namedIds(text, names)
102​
103export function parseBedrockExtendedThinking(
104 text: string,
105): Record<string, ModelReasoning> {
106 const native = prose(text)
107 const supported = models(native)
108 const use = markdownSection(native, 'How to use extended thinking')
109 if (
110 !/^To turn on extended thinking, add a `thinking` object/m.test(use) ||
111 !/^The `budget_tokens` parameter determines the maximum number of tokens/m.test(
112 use,
113 )
114 ) {
115 throw new Error(
116 'amazon-bedrock extended thinking: missing native budget declaration',
117 )
118 }
119 return Object.fromEntries(
120 [...supported.values()].map((id) => [
121 id,
122 { mode: 'budget', mandatory: null },
123 ]),
124 )
126​
127export function parseBedrockAdaptiveThinking(
128 text: string,
129): Record<string, ModelReasoning> {
130 const native = prose(text)
131 const supported = models(native)
132 const effortSection = markdownSection(
133 native,
134 'Adaptive thinking with the effort parameter',
135 )
136 const table = rows(effortSection)
137 if (
138 table[0]?.[0] !== 'Effort level' ||
139 table[0][1] !== 'Thinking behavior' ||
140 table.length < 2 ||
141 !/^Set `thinking.type` to `"adaptive"` in your API request:$/m.test(native)
142 ) {
143 throw new Error(
144 'amazon-bedrock adaptive thinking: missing native mode or effort table',
145 )
146 }
147 const result: Record<string, ModelReasoning> = Object.fromEntries(
148 [...supported.values()].map((id) => [
149 id,
150 { mode: 'adaptive', mandatory: null, efforts: [] },
151 ]),
152 )
153 const seen = new Set<string>()
154 for (const row of table.slice(1)) {
155 const level = row[0]?.match(
156 /^([a-z][a-z0-9_-]*)(?: \(default(?: [^)]+)?\))?$/,
157 )?.[1]
158 const description = row[1]
159 if (!level || !description || row.length !== 2 || seen.has(level))
160 throw new Error('amazon-bedrock adaptive thinking: unreadable effort row')
161 seen.add(level)
162 const named = scopeIds(description, supported, level)
163 const scoped =
164 /\bonly\b|\bsupports?\b|\bsupported\b|unsupported models/i.test(
165 description,
166 )
167 if (scoped && !named.length)
168 throw new Error(
169 `amazon-bedrock adaptive thinking: unreadable model scope for ${level}`,
170 )
171 if (named.length && !scoped)
172 throw new Error(
173 `amazon-bedrock adaptive thinking: ambiguous model scope for ${level}`,
174 )
175 for (const id of scoped ? named : supported.values())
176 result[id]?.efforts?.push(level)
177 }
178 for (const control of Object.values(result)) {
179 if (!control.efforts?.length)
180 throw new Error(
181 'amazon-bedrock adaptive thinking: model has no published effort levels',
182 )
183 }
184 // mandatory comes only from the guide's per-model thinking.type table, never
185 // from defaults or effort descriptions.
186 const config = rows(
187 markdownSection(native, 'Thinking configuration by model'),
188 )
189 const head = config[0]?.map(clean) ?? []
190 const disabled = head.indexOf('"disabled"')
191 const betweenTools = head.indexOf('"between_tools"')
192 if (
193 head[0] !== 'Model' ||
194 disabled < 0 ||
195 betweenTools < 0 ||
196 config.length < 2
197 )
198 throw new Error(
199 'amazon-bedrock adaptive thinking: missing thinking configuration table',
200 )
201 const configured = new Set<string>()
202 for (const row of config.slice(1)) {
203 const ids = scopeIds(row[0] ?? '', supported, 'thinking configuration')
204 const off = clean(row[disabled] ?? '')
205 const tools = clean(row[betweenTools] ?? '')
206 // "Thinking off" states it can be turned off; a 400 on both off switches
207 // states it cannot. Sonnet 5.5's between_tools drops only up-front
208 // thinking, which states neither. Any other wording throws.
209 const mandatory = /^Thinking off\b/.test(off)
210 ? false
211 : off === '400 error' && tools === '400 error'
212 ? true
213 : off === '400 error' && /^Up-front thinking off\b/.test(tools)
214 ? null
215 : undefined
216 if (!ids.length || row.length !== head.length || mandatory === undefined)
217 throw new Error(
218 `amazon-bedrock adaptive thinking: unreadable thinking configuration row for ${clean(row[0] ?? '')}`,
219 )
220 for (const id of ids) {
221 const control = result[id]
222 if (!control || configured.has(id))
223 throw new Error(
224 `amazon-bedrock adaptive thinking: duplicate thinking configuration for ${id}`,
225 )
226 configured.add(id)
227 control.mandatory = mandatory
228 }
229 }
230 return result
232​
233/** The hosted guide names one model explicitly; examples cannot add scope. */
234export function parseBedrockNovaThinking(text: string): {
235 modelName: string
236 reasoning: ModelReasoning
237} {
238 const native = markdownSection(prose(text), 'Using reasoning')
239 const modelName = native.match(
240 /^([^\n]+) supports extended thinking for complex problem-solving\. Enable reasoning with `reasoningConfig`\.$/m,
241 )?.[1]
242 const type = native.match(/^\+ `type`: (.+)$/m)?.[1]
243 const declaration = native.match(
244 /^\+ `maxReasoningEffort`: (.+?)\. This is required when reasoning is enabled\./m,
245 )?.[1]
246 if (
247 !modelName ||
248 !type ||
249 !/^`enabled` or `disabled` \(default: `disabled`\)$/.test(type) ||
250 !declaration
251 ) {
252 throw new Error(
253 'amazon-bedrock Nova thinking: missing native model, type or effort declaration',
254 )
255 }
256 const efforts = [...declaration.matchAll(/`([a-z][a-z0-9_-]*)`/g)].map(
257 (match) => match[1] ?? '',
258 )
259 if (
260 !efforts.length ||
261 new Set(efforts).size !== efforts.length ||
262 declaration
263 .replace(/`[a-z][a-z0-9_-]*`/g, '')
264 .replace(/[,\s]|\bor\b/g, '') !== ''
265 ) {
266 throw new Error(
267 'amazon-bedrock Nova thinking: unreadable native effort list',
268 )
269 }
270 return { modelName, reasoning: { mode: 'effort', mandatory: false, efforts } }
272​
273/** A profile is enriched only through IDs explicitly declared on its card. */
274export function applyBedrockThinkingGuides(
275 catalog: Array<ModelInfo>,
276 groups: Array<BedrockCardOwnedGroup>,
277 guides: Array<BedrockThinkingGuide>,
278): Array<ModelInfo> {
279 const byRow = new Map<
280 string,
281 ModelReasoning & { url: string; hash: string }
282 >()
283 // Adaptive is AWS's recommended successor where its table overlaps extended.
284 for (const guide of guides) {
285 for (const group of groups) {
286 const named = group.modelName
287 ? (guide.namedControls ?? guide.runtimeNamedControls)?.[group.modelName]
288 : undefined
289 const byId = group.baseIds
290 .map((id) => guide.controls[id])
291 .filter((value): value is ModelReasoning => value != null)
292 const useName = !!guide.namedControls || (!byId.length && named != null)
293 const declarations = useName ? (named ? [named] : []) : byId
294 if (
295 useName &&
296 named &&
297 (!Array.isArray(group.runtimeRowIds) ||
298 !group.runtimeRowIds.every((id) => typeof id === 'string'))
299 )
300 throw new Error(
301 'amazon-bedrock thinking: unreadable native runtime card binding',
302 )
303 const targetIds = useName
304 ? (group.runtimeRowIds ?? []).filter((id) => group.rowIds.includes(id))
305 : group.rowIds
306 if (
307 useName &&
308 named &&
309 groups.filter((candidate) => candidate.modelName === group.modelName)
310 .length !== 1
311 )
312 throw new Error(
313 'amazon-bedrock thinking: ambiguous native card title binding',
314 )
315 if (!declarations.length) continue
316 if (
317 declarations.some(
318 (value) => JSON.stringify(value) !== JSON.stringify(declarations[0]),
319 )
320 )
321 throw new Error(
322 'amazon-bedrock thinking: contradictory controls for card-owned base IDs',
323 )
324 for (const id of targetIds)
325 byRow.set(id, { ...declarations[0]!, url: guide.url, hash: guide.hash })
326 }
327 }
328 return catalog.map((model) => {
329 const declaration = byRow.get(model.rawId)
330 if (!declaration) return model
331 const capSource = tagDocsFacts(
332 { capabilities: ['reasoning'] },
333 declaration.url,
334 declaration.hash,
335 ).capabilities!.reasoning!
336 const capable = nativeReasoningCapability(model, capSource)
337 const existing = model.reasoning
338 if (
339 existing?.mandatory != null &&
340 declaration.mandatory != null &&
341 existing.mandatory !== declaration.mandatory
342 )
343 throw new Error(
344 `amazon-bedrock thinking: native guide contradicts card mandatory for ${model.rawId}`,
345 )
346 // Do not add adaptive efforts to a budget/effort object from a card.
347 if (existing && existing.mode !== declaration.mode) return model
348 if (existing?.efforts?.length && existing.mandatory != null) return model
349 // Only cite the guide for a complete object when every retained value is
350 // independently supported by that guide. Otherwise leave the card intact.
351 if (
352 existing?.mandatory != null &&
353 existing.mandatory !== declaration.mandatory
354 )
355 return model
356 if (
357 existing?.efforts?.length &&
358 JSON.stringify([...existing.efforts].sort()) !==
359 JSON.stringify([...(declaration.efforts ?? [])].sort())
360 )
361 return model
362 const reasoning: ModelReasoning = {
363 mode: existing?.mode ?? declaration.mode,
364 mandatory: existing?.mandatory ?? declaration.mandatory,
365 ...(existing?.efforts?.length
366 ? { efforts: existing.efforts }
367 : declaration.efforts?.length
368 ? { efforts: declaration.efforts }
369 : {}),
370 }
371 if (JSON.stringify(reasoning) === JSON.stringify(existing)) return model
372 const reasonSource = tagDocsFacts(
373 { reasoning },
374 declaration.url,
375 declaration.hash,
376 )
377 return {
378 ...capable,
379 reasoning,
380 factSources: {
381 ...model.factSources,
382 ...reasonSource,
383 capabilities: {
384 ...capable.factSources?.capabilities,
385 reasoning: model.factSources?.capabilities?.reasoning ?? capSource,
386 },
387 },
388 }
389 })
391​
392export async function loadBedrockThinkingGuides(
393 catalog: Array<ModelInfo>,
394 groups: Array<BedrockCardOwnedGroup>,
395 run: DocsRun,
396 kv?: KVNamespace,
397): Promise<Array<ModelInfo>> {
398 const sources = [
399 {
400 url: BEDROCK_EXTENDED_THINKING_URL,
401 parse: (text: string) => {
402 const controls = parseBedrockExtendedThinking(text)
403 return {
404 controls,
405 runtimeNamedControls: Object.fromEntries(
406 [...models(prose(text))].map(([name, id]) => [name, controls[id]!]),
407 ),
408 }
409 },
410 },
411 {
412 url: BEDROCK_ADAPTIVE_THINKING_URL,
413 parse: (text: string) => {
414 const controls = parseBedrockAdaptiveThinking(text)
415 return {
416 controls,
417 runtimeNamedControls: Object.fromEntries(
418 [...models(prose(text))].map(([name, id]) => [name, controls[id]!]),
419 ),
420 }
421 },
422 },
423 {
424 url: BEDROCK_NOVA_THINKING_URL,
425 parse: (text: string) => {
426 const declaration = parseBedrockNovaThinking(text)
427 return {
428 controls: {},
429 namedControls: { [declaration.modelName]: declaration.reasoning },
430 }
431 },
432 },
433 ]
434 const guides = await Promise.all(
435 sources.map((source) =>
436 tryDocs(run, source.url, (cached) =>
437 cached(kv, source.url, async () => {
438 const text = await fetchText(source.url, {
439 signal: AbortSignal.timeout(20_000),
440 headers: {
441 'User-Agent':
442 'modelschemas (+https://modelschemas.openstory.workers.dev)',
443 },
444 })
445 return {
446 ...source.parse(text),
447 url: source.url,
448 hash: await sha256Text(text),
449 }
450 }),
451 ),
452 ),
453 )
454 let enriched = catalog
455 const failedSources = new Set(
456 sources
457 .filter((_, index) => guides[index] == null)
458 .map((source) => source.url),
459 )
460 // Apply adaptive first: it is the recommendation for overlapping IDs.
461 for (const index of [1, 0, 2]) {
462 const guide = guides[index]
463 if (!guide) continue
464 const result = await tryDocs(run, guide.url, async () =>
465 applyBedrockThinkingGuides(enriched, groups, [guide]),
466 )
467 if (result) enriched = result
468 else failedSources.add(guide.url)
469 }
470 if (!failedSources.size) return enriched
471 // A failed guide cannot clear missing controls that it may have supplied.
472 // Existing populated card facts remain intact; failures are public.
473 const claude = new Set(
474 groups
475 .filter((group) =>
476 group.baseIds.some((id) => id.startsWith('anthropic.')),
477 )
478 .flatMap((group) => group.rowIds),
479 )
480 const nova = new Set(
481 groups
482 .filter((group) =>
483 group.baseIds.some((id) => id.startsWith('amazon.nova-')),
484 )
485 .flatMap((group) => group.rowIds),
486 )
487 return enriched.map((model) => {
488 const missingMode = model.reasoning == null
489 const missingAdaptiveEfforts =
490 model.reasoning?.mode === 'adaptive' && !model.reasoning.efforts?.length
491 const missingNovaEfforts =
492 model.reasoning?.mode === 'effort' && !model.reasoning.efforts?.length
493 const affected =
494 (claude.has(model.rawId) &&
495 ((failedSources.has(BEDROCK_EXTENDED_THINKING_URL) && missingMode) ||
496 (failedSources.has(BEDROCK_ADAPTIVE_THINKING_URL) &&
497 (missingMode || missingAdaptiveEfforts)))) ||
498 (nova.has(model.rawId) &&
499 failedSources.has(BEDROCK_NOVA_THINKING_URL) &&
500 (missingMode || missingNovaEfforts))
501 return affected
502 ? {
503 ...model,
504 absent: { ...model.absent, ...unavailable('reasoning').absent },
505 }
506 : model
507 })