@namzu/anthropic 1.2.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +336 -0
- package/dist/__tests__/anthropic.test.js +1 -0
- package/dist/__tests__/anthropic.test.js.map +1 -1
- package/dist/__tests__/block-shape-guard.test.d.ts +2 -0
- package/dist/__tests__/block-shape-guard.test.d.ts.map +1 -0
- package/dist/__tests__/block-shape-guard.test.js +218 -0
- package/dist/__tests__/block-shape-guard.test.js.map +1 -0
- package/dist/__tests__/cache-anchors.test.d.ts +2 -0
- package/dist/__tests__/cache-anchors.test.d.ts.map +1 -0
- package/dist/__tests__/cache-anchors.test.js +220 -0
- package/dist/__tests__/cache-anchors.test.js.map +1 -0
- package/dist/__tests__/citations.test.d.ts +2 -0
- package/dist/__tests__/citations.test.d.ts.map +1 -0
- package/dist/__tests__/citations.test.js +189 -0
- package/dist/__tests__/citations.test.js.map +1 -0
- package/dist/__tests__/content-blocks.test.d.ts +2 -0
- package/dist/__tests__/content-blocks.test.d.ts.map +1 -0
- package/dist/__tests__/content-blocks.test.js +131 -0
- package/dist/__tests__/content-blocks.test.js.map +1 -0
- package/dist/__tests__/document-input.test.d.ts +2 -0
- package/dist/__tests__/document-input.test.d.ts.map +1 -0
- package/dist/__tests__/document-input.test.js +98 -0
- package/dist/__tests__/document-input.test.js.map +1 -0
- package/dist/__tests__/reasoning-close.test.d.ts +2 -0
- package/dist/__tests__/reasoning-close.test.d.ts.map +1 -0
- package/dist/__tests__/reasoning-close.test.js +219 -0
- package/dist/__tests__/reasoning-close.test.js.map +1 -0
- package/dist/__tests__/thinking-capability.test.d.ts +2 -0
- package/dist/__tests__/thinking-capability.test.d.ts.map +1 -0
- package/dist/__tests__/thinking-capability.test.js +127 -0
- package/dist/__tests__/thinking-capability.test.js.map +1 -0
- package/dist/__tests__/thinking-request-body.test.d.ts +2 -0
- package/dist/__tests__/thinking-request-body.test.d.ts.map +1 -0
- package/dist/__tests__/thinking-request-body.test.js +90 -0
- package/dist/__tests__/thinking-request-body.test.js.map +1 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +186 -3
- package/dist/client.js.map +1 -1
- package/dist/thinking-capability.d.ts +78 -0
- package/dist/thinking-capability.d.ts.map +1 -0
- package/dist/thinking-capability.js +114 -0
- package/dist/thinking-capability.js.map +1 -0
- package/package.json +4 -4
- package/src/__tests__/anthropic.test.ts +1 -0
- package/src/__tests__/block-shape-guard.test.ts +256 -0
- package/src/__tests__/cache-anchors.test.ts +262 -0
- package/src/__tests__/citations.test.ts +218 -0
- package/src/__tests__/content-blocks.test.ts +153 -0
- package/src/__tests__/document-input.test.ts +131 -0
- package/src/__tests__/reasoning-close.test.ts +262 -0
- package/src/__tests__/thinking-capability.test.ts +150 -0
- package/src/__tests__/thinking-request-body.test.ts +111 -0
- package/src/client.ts +265 -7
- package/src/thinking-capability.ts +177 -0
package/src/client.ts
CHANGED
|
@@ -3,19 +3,28 @@ import Anthropic from '@anthropic-ai/sdk'
|
|
|
3
3
|
import type {
|
|
4
4
|
ChatCompletionParams,
|
|
5
5
|
ChatCompletionResponse,
|
|
6
|
+
Citation,
|
|
6
7
|
LLMProvider,
|
|
7
8
|
ModelInfo,
|
|
8
9
|
ProviderCapabilities,
|
|
10
|
+
ReasoningBlock,
|
|
9
11
|
StreamChunk,
|
|
10
12
|
TokenUsage,
|
|
11
13
|
ToolChoice,
|
|
14
|
+
ToolResultContent,
|
|
12
15
|
} from '@namzu/sdk'
|
|
13
16
|
import {
|
|
14
17
|
ProviderRequestError,
|
|
15
18
|
isCallerAbortError,
|
|
16
19
|
isProviderRequestError,
|
|
17
20
|
providerVendorError,
|
|
21
|
+
toolResultToText,
|
|
18
22
|
} from '@namzu/sdk'
|
|
23
|
+
import {
|
|
24
|
+
resolveEffort,
|
|
25
|
+
resolveThinkingBody,
|
|
26
|
+
resolveThinkingCapability,
|
|
27
|
+
} from './thinking-capability.js'
|
|
19
28
|
import type { AnthropicConfig } from './types.js'
|
|
20
29
|
|
|
21
30
|
// Floor for `max_tokens` when neither the request nor the provider
|
|
@@ -92,7 +101,8 @@ interface AnthropicToolUseBlock {
|
|
|
92
101
|
interface AnthropicToolResultBlock {
|
|
93
102
|
type: 'tool_result'
|
|
94
103
|
tool_use_id: string
|
|
95
|
-
|
|
104
|
+
/** Text, or the blocks this wire accepts inside a tool result. */
|
|
105
|
+
content: string | Array<AnthropicTextBlock | AnthropicImageBlock>
|
|
96
106
|
cache_control?: AnthropicCacheControl
|
|
97
107
|
}
|
|
98
108
|
|
|
@@ -110,10 +120,38 @@ interface AnthropicToolParam {
|
|
|
110
120
|
cache_control?: AnthropicCacheControl
|
|
111
121
|
}
|
|
112
122
|
|
|
113
|
-
/** Shape of an SDK `
|
|
123
|
+
/** Shape of an SDK `MessageAttachment` (read structurally to avoid coupling). */
|
|
114
124
|
interface AttachmentLike {
|
|
125
|
+
readonly type?: 'image' | 'document'
|
|
115
126
|
readonly data: string
|
|
116
127
|
readonly mediaType: string
|
|
128
|
+
readonly name?: string
|
|
129
|
+
readonly citations?: boolean
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A reasoning block, replayed exactly as it arrived.
|
|
134
|
+
*
|
|
135
|
+
* The signature is cryptographic and verified upstream: a block echoed
|
|
136
|
+
* back with its text edited, its signature dropped, or its order changed
|
|
137
|
+
* is rejected, which fails the whole conversation rather than one block.
|
|
138
|
+
* So this is a passthrough, never a re-render.
|
|
139
|
+
*/
|
|
140
|
+
interface AnthropicThinkingBlock {
|
|
141
|
+
type: 'thinking' | 'redacted_thinking'
|
|
142
|
+
thinking?: string
|
|
143
|
+
signature?: string
|
|
144
|
+
data?: string
|
|
145
|
+
cache_control?: AnthropicCacheControl
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
interface AnthropicDocumentBlock {
|
|
149
|
+
type: 'document'
|
|
150
|
+
source: { type: 'base64'; media_type: string; data: string }
|
|
151
|
+
title?: string
|
|
152
|
+
citations?: { enabled: true }
|
|
153
|
+
/** A document is the block most worth a breakpoint, being the largest. */
|
|
154
|
+
cache_control?: AnthropicCacheControl
|
|
117
155
|
}
|
|
118
156
|
|
|
119
157
|
type AnthropicContentBlock =
|
|
@@ -121,6 +159,8 @@ type AnthropicContentBlock =
|
|
|
121
159
|
| AnthropicToolUseBlock
|
|
122
160
|
| AnthropicToolResultBlock
|
|
123
161
|
| AnthropicImageBlock
|
|
162
|
+
| AnthropicDocumentBlock
|
|
163
|
+
| AnthropicThinkingBlock
|
|
124
164
|
|
|
125
165
|
interface AnthropicMessageParam {
|
|
126
166
|
role: 'user' | 'assistant'
|
|
@@ -155,6 +195,64 @@ function extractSystem(
|
|
|
155
195
|
return blocks
|
|
156
196
|
}
|
|
157
197
|
|
|
198
|
+
/**
|
|
199
|
+
* The reasoning blocks an assistant message carries, in wire form.
|
|
200
|
+
*
|
|
201
|
+
* Verbatim by contract, and first in the message: the API requires
|
|
202
|
+
* thinking blocks to lead, and the signature is verified, so re-rendering
|
|
203
|
+
* or reordering them invalidates the turn they belong to.
|
|
204
|
+
*/
|
|
205
|
+
function replayReasoning(msg: { reasoning?: readonly ReasoningBlock[] }): AnthropicThinkingBlock[] {
|
|
206
|
+
if (!msg.reasoning || msg.reasoning.length === 0) return []
|
|
207
|
+
return msg.reasoning.map((block) =>
|
|
208
|
+
block.type === 'redacted_thinking'
|
|
209
|
+
? {
|
|
210
|
+
type: 'redacted_thinking' as const,
|
|
211
|
+
...(block.encrypted ? { data: block.encrypted } : {}),
|
|
212
|
+
}
|
|
213
|
+
: {
|
|
214
|
+
type: 'thinking' as const,
|
|
215
|
+
thinking: block.text ?? '',
|
|
216
|
+
...(block.signature ? { signature: block.signature } : {}),
|
|
217
|
+
},
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* A tool result, in the richest form this wire accepts.
|
|
223
|
+
*
|
|
224
|
+
* The blocks used to be `JSON.stringify`d, so a screenshot reached the
|
|
225
|
+
* model as a wall of quoted base64 — the one thing the SDK's own degrade
|
|
226
|
+
* helper exists to avoid, and pure cost besides: the model paid for every
|
|
227
|
+
* character and could read none of them. This wire carries image blocks in
|
|
228
|
+
* a tool result natively, so they are sent as images.
|
|
229
|
+
*
|
|
230
|
+
* A document block still degrades to the named placeholder: tool results
|
|
231
|
+
* on this wire take text and images, not documents, and inventing an image
|
|
232
|
+
* block around a PDF would fail the request instead of the block.
|
|
233
|
+
*/
|
|
234
|
+
function toolResultContent(
|
|
235
|
+
content: ToolResultContent | undefined,
|
|
236
|
+
): string | Array<AnthropicTextBlock | AnthropicImageBlock> {
|
|
237
|
+
if (content === undefined) return ''
|
|
238
|
+
if (typeof content === 'string') return content
|
|
239
|
+
|
|
240
|
+
const blocks: Array<AnthropicTextBlock | AnthropicImageBlock> = []
|
|
241
|
+
for (const block of content) {
|
|
242
|
+
if (block.type === 'image') {
|
|
243
|
+
blocks.push({
|
|
244
|
+
type: 'image',
|
|
245
|
+
source: { type: 'base64', media_type: block.mediaType, data: block.data },
|
|
246
|
+
})
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
const text = toolResultToText([block])
|
|
250
|
+
if (text.length > 0) blocks.push({ type: 'text', text })
|
|
251
|
+
}
|
|
252
|
+
// An empty array is rejected upstream; an empty string is not.
|
|
253
|
+
return blocks.length > 0 ? blocks : ''
|
|
254
|
+
}
|
|
255
|
+
|
|
158
256
|
function toAnthropicMessages(messages: ChatCompletionParams['messages']): AnthropicMessageParam[] {
|
|
159
257
|
const out: AnthropicMessageParam[] = []
|
|
160
258
|
let pendingToolResults: AnthropicToolResultBlock[] = []
|
|
@@ -170,12 +268,11 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
170
268
|
if (msg.role === 'system') continue
|
|
171
269
|
|
|
172
270
|
if (msg.role === 'tool') {
|
|
173
|
-
const toolMsg = msg as { toolCallId?: string; content?:
|
|
271
|
+
const toolMsg = msg as { toolCallId?: string; content?: ToolResultContent }
|
|
174
272
|
pendingToolResults.push({
|
|
175
273
|
type: 'tool_result',
|
|
176
274
|
tool_use_id: toolMsg.toolCallId ?? 'unknown',
|
|
177
|
-
content:
|
|
178
|
-
typeof toolMsg.content === 'string' ? toolMsg.content : JSON.stringify(toolMsg.content),
|
|
275
|
+
content: toolResultContent(toolMsg.content),
|
|
179
276
|
})
|
|
180
277
|
continue
|
|
181
278
|
}
|
|
@@ -183,7 +280,7 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
183
280
|
flushToolResults()
|
|
184
281
|
|
|
185
282
|
if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
|
|
186
|
-
const blocks: AnthropicContentBlock[] = []
|
|
283
|
+
const blocks: AnthropicContentBlock[] = [...replayReasoning(msg)]
|
|
187
284
|
if (msg.content && typeof msg.content === 'string') {
|
|
188
285
|
blocks.push({ type: 'text', text: msg.content })
|
|
189
286
|
}
|
|
@@ -205,7 +302,16 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
205
302
|
continue
|
|
206
303
|
}
|
|
207
304
|
|
|
305
|
+
// An assistant turn that reasoned replays those blocks even when it
|
|
306
|
+
// called no tool: dropping them invalidates the turn upstream.
|
|
307
|
+
const replayed = msg.role === 'assistant' ? replayReasoning(msg) : []
|
|
208
308
|
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
|
|
309
|
+
if (replayed.length > 0) {
|
|
310
|
+
const trailing: AnthropicContentBlock[] =
|
|
311
|
+
content.length > 0 ? [{ type: 'text', text: content }] : []
|
|
312
|
+
out.push({ role: 'assistant', content: [...replayed, ...trailing] })
|
|
313
|
+
continue
|
|
314
|
+
}
|
|
209
315
|
// User message with image attachments → multimodal content blocks
|
|
210
316
|
// (text first, then each image as a base64 image block).
|
|
211
317
|
const attachments = (msg as { attachments?: readonly AttachmentLike[] }).attachments
|
|
@@ -213,6 +319,23 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
213
319
|
const blocks: AnthropicContentBlock[] = []
|
|
214
320
|
if (content.length > 0) blocks.push({ type: 'text', text: content })
|
|
215
321
|
for (const att of attachments) {
|
|
322
|
+
// A document is not an image with a different media type. It
|
|
323
|
+
// used to be mapped as one, so a PDF went up as an image block
|
|
324
|
+
// the API rejects — while the capability set claimed documents
|
|
325
|
+
// were supported. The native block buys page structure, OCR,
|
|
326
|
+
// and the citations the SDK contract already has a slot for.
|
|
327
|
+
if (att.type === 'document') {
|
|
328
|
+
blocks.push({
|
|
329
|
+
type: 'document',
|
|
330
|
+
source: { type: 'base64', media_type: att.mediaType, data: att.data },
|
|
331
|
+
...(att.name ? { title: att.name } : {}),
|
|
332
|
+
// Opt-in: citations cost tokens, so they are requested
|
|
333
|
+
// only when the caller asked to be able to check the
|
|
334
|
+
// answer.
|
|
335
|
+
...(att.citations ? { citations: { enabled: true as const } } : {}),
|
|
336
|
+
})
|
|
337
|
+
continue
|
|
338
|
+
}
|
|
216
339
|
blocks.push({
|
|
217
340
|
type: 'image',
|
|
218
341
|
source: { type: 'base64', media_type: att.mediaType, data: att.data },
|
|
@@ -333,6 +456,15 @@ interface RawAnthropicUsage {
|
|
|
333
456
|
output_tokens?: number
|
|
334
457
|
cache_read_input_tokens?: number | null
|
|
335
458
|
cache_creation_input_tokens?: number | null
|
|
459
|
+
/**
|
|
460
|
+
* Reasoning share of the output, when the vendor reports it.
|
|
461
|
+
*
|
|
462
|
+
* Counted INSIDE `output_tokens`, so it is carried as a breakdown rather
|
|
463
|
+
* than added to the total. When streaming, this arrives only on the final
|
|
464
|
+
* `message_delta` — earlier events carry no breakdown at all, which is why
|
|
465
|
+
* an absent value has to mean "not reported" and not "zero".
|
|
466
|
+
*/
|
|
467
|
+
output_tokens_details?: { thinking_tokens?: number } | null
|
|
336
468
|
}
|
|
337
469
|
|
|
338
470
|
function emptyUsage(): TokenUsage {
|
|
@@ -349,12 +481,17 @@ function parseUsage(raw?: RawAnthropicUsage): TokenUsage {
|
|
|
349
481
|
if (!raw) return emptyUsage()
|
|
350
482
|
const input = raw.input_tokens ?? 0
|
|
351
483
|
const output = raw.output_tokens ?? 0
|
|
484
|
+
const thinking = raw.output_tokens_details?.thinking_tokens
|
|
352
485
|
return {
|
|
353
486
|
promptTokens: input,
|
|
354
487
|
completionTokens: output,
|
|
355
488
|
totalTokens: input + output,
|
|
356
489
|
cachedTokens: raw.cache_read_input_tokens ?? 0,
|
|
357
490
|
cacheWriteTokens: raw.cache_creation_input_tokens ?? 0,
|
|
491
|
+
// Only when reported. Defaulting to 0 would say "this turn did no
|
|
492
|
+
// thinking" about every turn on every driver that stays silent, and
|
|
493
|
+
// about every streamed event before the last one.
|
|
494
|
+
...(thinking !== undefined ? { reasoningTokens: thinking } : {}),
|
|
358
495
|
}
|
|
359
496
|
}
|
|
360
497
|
|
|
@@ -382,16 +519,77 @@ function mapStopReason(reason?: string | null): NamzuFinishReason {
|
|
|
382
519
|
// Stream event types
|
|
383
520
|
// --------------------------------------------------------------------------------------
|
|
384
521
|
|
|
522
|
+
/**
|
|
523
|
+
* A cited passage as it arrives on the wire.
|
|
524
|
+
*
|
|
525
|
+
* The location is reported three different ways depending on how the
|
|
526
|
+
* provider segmented the source, which is why the SDK's `Citation` keeps
|
|
527
|
+
* a discriminated union rather than flattening everything to a page
|
|
528
|
+
* number: two of the three shapes have no page to report.
|
|
529
|
+
*/
|
|
530
|
+
interface RawAnthropicCitation {
|
|
531
|
+
type?: string
|
|
532
|
+
cited_text?: string
|
|
533
|
+
document_index?: number
|
|
534
|
+
document_title?: string | null
|
|
535
|
+
start_page_number?: number
|
|
536
|
+
end_page_number?: number
|
|
537
|
+
start_char_index?: number
|
|
538
|
+
end_char_index?: number
|
|
539
|
+
start_block_index?: number
|
|
540
|
+
end_block_index?: number
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Map a wire citation onto the SDK's shape.
|
|
545
|
+
*
|
|
546
|
+
* Returns undefined rather than inventing a location: a citation whose
|
|
547
|
+
* source segment cannot be named is worse than none, because it looks
|
|
548
|
+
* checkable and is not.
|
|
549
|
+
*/
|
|
550
|
+
function toCitation(raw: RawAnthropicCitation, index: number): Citation | undefined {
|
|
551
|
+
const citedText = raw.cited_text
|
|
552
|
+
if (!citedText) return undefined
|
|
553
|
+
|
|
554
|
+
const location = (():
|
|
555
|
+
| { kind: 'page'; start: number; end: number }
|
|
556
|
+
| { kind: 'char'; start: number; end: number }
|
|
557
|
+
| { kind: 'block'; start: number; end: number }
|
|
558
|
+
| undefined => {
|
|
559
|
+
if (raw.start_page_number !== undefined && raw.end_page_number !== undefined) {
|
|
560
|
+
return { kind: 'page', start: raw.start_page_number, end: raw.end_page_number }
|
|
561
|
+
}
|
|
562
|
+
if (raw.start_char_index !== undefined && raw.end_char_index !== undefined) {
|
|
563
|
+
return { kind: 'char', start: raw.start_char_index, end: raw.end_char_index }
|
|
564
|
+
}
|
|
565
|
+
if (raw.start_block_index !== undefined && raw.end_block_index !== undefined) {
|
|
566
|
+
return { kind: 'block', start: raw.start_block_index, end: raw.end_block_index }
|
|
567
|
+
}
|
|
568
|
+
return undefined
|
|
569
|
+
})()
|
|
570
|
+
if (!location) return undefined
|
|
571
|
+
|
|
572
|
+
return {
|
|
573
|
+
citedText,
|
|
574
|
+
documentIndex: raw.document_index ?? index,
|
|
575
|
+
...(raw.document_title ? { documentTitle: raw.document_title } : {}),
|
|
576
|
+
location,
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
385
580
|
interface StreamEvent {
|
|
386
581
|
type: string
|
|
387
582
|
message?: { id?: string; usage?: RawAnthropicUsage }
|
|
388
583
|
index?: number
|
|
389
|
-
content_block?: { type?: string; id?: string; name?: string }
|
|
584
|
+
content_block?: { type?: string; id?: string; name?: string; data?: string }
|
|
390
585
|
delta?: {
|
|
391
586
|
type?: string
|
|
392
587
|
text?: string
|
|
393
588
|
partial_json?: string
|
|
394
589
|
stop_reason?: string | null
|
|
590
|
+
citation?: RawAnthropicCitation
|
|
591
|
+
thinking?: string
|
|
592
|
+
signature?: string
|
|
395
593
|
}
|
|
396
594
|
usage?: RawAnthropicUsage
|
|
397
595
|
}
|
|
@@ -410,6 +608,7 @@ export const ANTHROPIC_CAPABILITIES: ProviderCapabilities = {
|
|
|
410
608
|
supportsStreaming: true,
|
|
411
609
|
supportsFunctionCalling: true,
|
|
412
610
|
supportsVision: true,
|
|
611
|
+
supportsDocuments: true,
|
|
413
612
|
}
|
|
414
613
|
|
|
415
614
|
export class AnthropicProvider implements LLMProvider {
|
|
@@ -506,6 +705,25 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
506
705
|
// otherwise) — this also drops a parallelToolCalls-derived choice on
|
|
507
706
|
// tool-less requests.
|
|
508
707
|
if (tools && toolChoice) body.tool_choice = toolChoice
|
|
708
|
+
// Resolved against the model rather than sent verbatim. This used to
|
|
709
|
+
// map `enabled` straight through and everything else to `disabled`,
|
|
710
|
+
// which fails outright on current models: `thinking.type.enabled` is
|
|
711
|
+
// rejected with a 400 from 4.7 onward, `adaptive` is rejected on 4.5
|
|
712
|
+
// and earlier, and the always-on models reject `disabled`. One body
|
|
713
|
+
// for every model is not a compromise here, it is a failed request.
|
|
714
|
+
//
|
|
715
|
+
// `display` is carried through now too. It defaults to `omitted` on
|
|
716
|
+
// newer models, so a caller who wanted to show reasoning and never
|
|
717
|
+
// serialized the field received thinking blocks with empty text and
|
|
718
|
+
// nothing to explain why.
|
|
719
|
+
const capability = resolveThinkingCapability(params.model)
|
|
720
|
+
const thinkingBody = resolveThinkingBody(params.thinking, capability)
|
|
721
|
+
if (thinkingBody) body.thinking = thinkingBody
|
|
722
|
+
|
|
723
|
+
// A sibling of `thinking`, not a field inside it — and gated on the
|
|
724
|
+
// model, since only some accept it at all.
|
|
725
|
+
const effort = resolveEffort(params.effort, thinkingBody, capability)
|
|
726
|
+
if (effort) body.output_config = { effort }
|
|
509
727
|
if (params.temperature !== undefined) body.temperature = params.temperature
|
|
510
728
|
if (params.topP !== undefined) body.top_p = params.topP
|
|
511
729
|
if (params.topK !== undefined) body.top_k = params.topK
|
|
@@ -558,6 +776,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
558
776
|
// Track active tool-use blocks by content_block index so input_json_delta
|
|
559
777
|
// fragments can reference the right tool call.
|
|
560
778
|
const activeTools = new Map<number, { id: string; name: string }>()
|
|
779
|
+
const activeReasoning = new Set<number>()
|
|
561
780
|
|
|
562
781
|
// Anthropic Messages API streams over SSE. Do not impose a
|
|
563
782
|
// provider-local 90s idle cutoff by default: long reasoning or
|
|
@@ -618,6 +837,20 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
618
837
|
case 'content_block_start': {
|
|
619
838
|
const idx = event.index ?? 0
|
|
620
839
|
const block = event.content_block
|
|
840
|
+
if (block?.type === 'thinking' || block?.type === 'redacted_thinking') {
|
|
841
|
+
activeReasoning.add(idx)
|
|
842
|
+
yield {
|
|
843
|
+
id: messageId,
|
|
844
|
+
delta: {
|
|
845
|
+
reasoning: {
|
|
846
|
+
index: idx,
|
|
847
|
+
type: block.type,
|
|
848
|
+
...(block.data ? { encrypted: block.data } : {}),
|
|
849
|
+
},
|
|
850
|
+
},
|
|
851
|
+
}
|
|
852
|
+
break
|
|
853
|
+
}
|
|
621
854
|
if (block?.type === 'tool_use') {
|
|
622
855
|
const toolId = block.id ?? `tool-${Date.now()}`
|
|
623
856
|
activeTools.set(idx, { id: toolId, name: block.name ?? '' })
|
|
@@ -642,6 +875,24 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
642
875
|
const delta = event.delta
|
|
643
876
|
if (delta?.type === 'text_delta' && delta.text) {
|
|
644
877
|
yield { id: messageId, delta: { content: delta.text } }
|
|
878
|
+
} else if (delta?.type === 'thinking_delta' && delta.thinking !== undefined) {
|
|
879
|
+
yield {
|
|
880
|
+
id: messageId,
|
|
881
|
+
delta: { reasoning: { index: idx, text: delta.thinking } },
|
|
882
|
+
}
|
|
883
|
+
} else if (delta?.type === 'signature_delta' && delta.signature !== undefined) {
|
|
884
|
+
// Arrives once, at the end of the block, and has to
|
|
885
|
+
// reach the next request unmodified.
|
|
886
|
+
yield {
|
|
887
|
+
id: messageId,
|
|
888
|
+
delta: { reasoning: { index: idx, signature: delta.signature } },
|
|
889
|
+
}
|
|
890
|
+
} else if (delta?.type === 'citations_delta' && delta.citation) {
|
|
891
|
+
// Not text: a citation lands on the assistant
|
|
892
|
+
// message beside the prose, which is where the
|
|
893
|
+
// runtime's stream aggregator already puts it.
|
|
894
|
+
const citation = toCitation(delta.citation, idx)
|
|
895
|
+
if (citation) yield { id: messageId, delta: { citation } }
|
|
645
896
|
} else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
|
|
646
897
|
const active = activeTools.get(idx)
|
|
647
898
|
yield {
|
|
@@ -670,6 +921,13 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
670
921
|
// — exactly the failure the live cowork test
|
|
671
922
|
// surfaced (Bash + Write both blank-input failed).
|
|
672
923
|
const idx = event.index ?? 0
|
|
924
|
+
if (activeReasoning.delete(idx)) {
|
|
925
|
+
// Closes the block, exactly as toolCallEnd closes a
|
|
926
|
+
// tool call: without it the aggregator cannot know
|
|
927
|
+
// the signature has finished arriving.
|
|
928
|
+
yield { id: messageId, delta: { reasoning: { index: idx, done: true } } }
|
|
929
|
+
break
|
|
930
|
+
}
|
|
673
931
|
const active = activeTools.get(idx)
|
|
674
932
|
if (active) {
|
|
675
933
|
yield {
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import type { ReasoningEffort, ThinkingConfig } from '@namzu/sdk'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What a given model will actually accept for thinking.
|
|
5
|
+
*
|
|
6
|
+
* This exists because the vendor **rejects** a mismatched mode rather than
|
|
7
|
+
* degrading it. A request carrying `thinking: {type: "enabled"}` to a current
|
|
8
|
+
* model comes back 400 with `"thinking.type.enabled" is not supported for this
|
|
9
|
+
* model`; the same request with `"adaptive"` to an older one comes back
|
|
10
|
+
* `adaptive thinking is not supported on this model`. So sending one body to
|
|
11
|
+
* every model is not a compatibility compromise, it is a failed request — and
|
|
12
|
+
* the SDK's `ThinkingConfig` is deliberately a statement of *intent* that each
|
|
13
|
+
* driver resolves against the model it is about to call.
|
|
14
|
+
*
|
|
15
|
+
* The split, from the vendor's per-model table:
|
|
16
|
+
*
|
|
17
|
+
* - **Adaptive only** — Fable 5, Mythos 5, Opus 5, Sonnet 5, Opus 4.8, Opus
|
|
18
|
+
* 4.7. These reject `enabled`. Fable 5 and Mythos 5 additionally reject
|
|
19
|
+
* `disabled` because they cannot stop thinking at all.
|
|
20
|
+
* - **Both** — Opus 4.6, Sonnet 4.6 (manual mode deprecated but working), and
|
|
21
|
+
* Mythos Preview (which rejects `disabled`).
|
|
22
|
+
* - **Manual only** — Opus 4.5, Sonnet 4.5, Haiku 4.5, Opus 4.1. These reject
|
|
23
|
+
* `adaptive`.
|
|
24
|
+
*
|
|
25
|
+
* Unknown models are treated as manual-only, which is the pre-existing
|
|
26
|
+
* behaviour and therefore the safe answer for a name this table has not seen:
|
|
27
|
+
* a third-party gateway serving an older model keeps working, and the failure
|
|
28
|
+
* mode for a newer one is a clear vendor 400 rather than a silently altered
|
|
29
|
+
* request.
|
|
30
|
+
*/
|
|
31
|
+
export interface ThinkingCapability {
|
|
32
|
+
readonly adaptive: boolean
|
|
33
|
+
readonly manual: boolean
|
|
34
|
+
/** False on models that cannot turn thinking off. */
|
|
35
|
+
readonly canDisable: boolean
|
|
36
|
+
readonly effort: boolean
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const MANUAL_ONLY: ThinkingCapability = {
|
|
40
|
+
adaptive: false,
|
|
41
|
+
manual: true,
|
|
42
|
+
canDisable: true,
|
|
43
|
+
effort: false,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Parse `claude-<family>-<major>[.<minor>]`, tolerating a vendor prefix and a
|
|
48
|
+
* date suffix.
|
|
49
|
+
*
|
|
50
|
+
* Deliberately the same shape the driver's `shouldUseStrictToolInputs` already
|
|
51
|
+
* parses. A second, subtly different model matcher in the same file is how two
|
|
52
|
+
* capability decisions drift apart on the same model name.
|
|
53
|
+
*/
|
|
54
|
+
function parseModel(model: string): { family: string; major: number; minor: number } | undefined {
|
|
55
|
+
const normalized = model.toLowerCase()
|
|
56
|
+
const match = normalized.match(
|
|
57
|
+
/^(?:anthropic\/)?claude-(haiku|sonnet|opus|fable|mythos)-(\d+)(?:[-_.](\d+))?(?:-\d{8})?$/,
|
|
58
|
+
)
|
|
59
|
+
if (!match) return undefined
|
|
60
|
+
return {
|
|
61
|
+
family: match[1] as string,
|
|
62
|
+
major: Number(match[2]),
|
|
63
|
+
minor: Number(match[3] ?? 0),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function resolveThinkingCapability(model: string): ThinkingCapability {
|
|
68
|
+
const normalized = model.toLowerCase()
|
|
69
|
+
|
|
70
|
+
// Named rather than versioned: the preview carries no version number the
|
|
71
|
+
// parser can compare, and it is the one model supporting both modes while
|
|
72
|
+
// refusing to be switched off.
|
|
73
|
+
if (/^(?:anthropic\/)?claude-mythos-preview$/.test(normalized)) {
|
|
74
|
+
return { adaptive: true, manual: true, canDisable: false, effort: true }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const parsed = parseModel(model)
|
|
78
|
+
if (!parsed) return MANUAL_ONLY
|
|
79
|
+
|
|
80
|
+
const { family, major, minor } = parsed
|
|
81
|
+
|
|
82
|
+
// Always-on families: thinking cannot be disabled at any version.
|
|
83
|
+
if (family === 'fable' || family === 'mythos') {
|
|
84
|
+
return { adaptive: true, manual: false, canDisable: false, effort: true }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 4.7 and later dropped manual mode outright.
|
|
88
|
+
if (major > 4 || (major === 4 && minor >= 7)) {
|
|
89
|
+
return { adaptive: true, manual: false, canDisable: true, effort: true }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 4.6 accepts both; manual is deprecated there but still functional.
|
|
93
|
+
if (major === 4 && minor === 6) {
|
|
94
|
+
return { adaptive: true, manual: true, canDisable: true, effort: true }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 4.5 and earlier are manual-only. Opus 4.5 is the one that also takes
|
|
98
|
+
// effort, where effort shapes the answer and the budget sets depth.
|
|
99
|
+
const isOpus45 = family === 'opus' && major === 4 && minor === 5
|
|
100
|
+
return { ...MANUAL_ONLY, effort: isOpus45 }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The `thinking` body value, or `undefined` to send no thinking field. */
|
|
104
|
+
export type ResolvedThinkingBody =
|
|
105
|
+
| { type: 'adaptive'; display?: 'summarized' | 'omitted' }
|
|
106
|
+
| { type: 'enabled'; budget_tokens?: number; display?: 'summarized' | 'omitted' }
|
|
107
|
+
| { type: 'disabled' }
|
|
108
|
+
| undefined
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Turn a declared intent into a body this model accepts, or into nothing.
|
|
112
|
+
*
|
|
113
|
+
* Omission is a real answer and the reason this returns `undefined` rather
|
|
114
|
+
* than throwing. A caller asking to disable thinking on a model that cannot
|
|
115
|
+
* disable it has asked for something impossible — but failing the request
|
|
116
|
+
* teaches nothing the vendor's own 400 would not, and it breaks a caller whose
|
|
117
|
+
* config is shared across models. Sending no `thinking` field leaves the model
|
|
118
|
+
* on its documented default, which is the closest honest reading of "I did not
|
|
119
|
+
* want to spend on this".
|
|
120
|
+
*
|
|
121
|
+
* The same holds in reverse: an `enabled` intent on an adaptive-only model
|
|
122
|
+
* becomes `adaptive`, because the caller asked for thinking and this model's
|
|
123
|
+
* way of thinking is adaptive. The budget is dropped with it — it has no
|
|
124
|
+
* meaning there, and `effort` is the depth control instead.
|
|
125
|
+
*/
|
|
126
|
+
export function resolveThinkingBody(
|
|
127
|
+
thinking: ThinkingConfig | undefined,
|
|
128
|
+
capability: ThinkingCapability,
|
|
129
|
+
): ResolvedThinkingBody {
|
|
130
|
+
if (!thinking) return undefined
|
|
131
|
+
|
|
132
|
+
const display = thinking.display ? { display: thinking.display } : {}
|
|
133
|
+
|
|
134
|
+
if (thinking.type === 'disabled') {
|
|
135
|
+
return capability.canDisable ? { type: 'disabled' } : undefined
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (thinking.type === 'adaptive') {
|
|
139
|
+
if (capability.adaptive) return { type: 'adaptive', ...display }
|
|
140
|
+
// Manual-only model: honour the intent to think, with the one mode it
|
|
141
|
+
// has. No budget was given, so the vendor default applies.
|
|
142
|
+
return capability.manual ? { type: 'enabled', ...display } : undefined
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// 'enabled'
|
|
146
|
+
if (capability.manual) {
|
|
147
|
+
return {
|
|
148
|
+
type: 'enabled',
|
|
149
|
+
...(thinking.budgetTokens !== undefined ? { budget_tokens: thinking.budgetTokens } : {}),
|
|
150
|
+
...display,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return capability.adaptive ? { type: 'adaptive', ...display } : undefined
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Whether `effort` may ride on this request.
|
|
158
|
+
*
|
|
159
|
+
* One interaction the table alone does not cover: on Opus 5 and later,
|
|
160
|
+
* `thinking: {type: "disabled"}` is accepted at effort `high` or below and
|
|
161
|
+
* **rejected at `xhigh`/`max`**, enforced per request. Rather than encode
|
|
162
|
+
* "Opus 5 and later" as a second version comparison, this refuses the
|
|
163
|
+
* combination on every model that can disable thinking — the pairing is
|
|
164
|
+
* incoherent anyway, since it asks a model not to think and then to think as
|
|
165
|
+
* hard as possible.
|
|
166
|
+
*/
|
|
167
|
+
export function resolveEffort(
|
|
168
|
+
effort: ReasoningEffort | undefined,
|
|
169
|
+
thinkingBody: ResolvedThinkingBody,
|
|
170
|
+
capability: ThinkingCapability,
|
|
171
|
+
): ReasoningEffort | undefined {
|
|
172
|
+
if (effort === undefined || !capability.effort) return undefined
|
|
173
|
+
if (thinkingBody?.type === 'disabled' && (effort === 'xhigh' || effort === 'max')) {
|
|
174
|
+
return undefined
|
|
175
|
+
}
|
|
176
|
+
return effort
|
|
177
|
+
}
|