@namzu/anthropic 1.2.0 → 1.3.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 +280 -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/client.d.ts.map +1 -1
- package/dist/client.js +174 -3
- package/dist/client.js.map +1 -1
- 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/client.ts +241 -7
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import type { ChatCompletionParams, StreamChunk } from '@namzu/sdk'
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
3
|
+
|
|
4
|
+
import { AnthropicProvider } from '../client.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Extended thinking was fully specified in the SDK and entirely absent
|
|
8
|
+
* from this driver.
|
|
9
|
+
*
|
|
10
|
+
* The stream chunk carried a `reasoning` channel whose own comment named
|
|
11
|
+
* the bug — "`thinking_delta` and `signature_delta` fell through the
|
|
12
|
+
* driver's `default: // ignore`" — the run's aggregator bucketed fragments
|
|
13
|
+
* by index and closed them on `done`, and `ReasoningBlock` recorded the
|
|
14
|
+
* signature with a note that replaying it unchanged is mandatory. The
|
|
15
|
+
* driver requested no thinking, parsed none, and replayed none.
|
|
16
|
+
*
|
|
17
|
+
* The close matters as much as the content. A block is only complete once
|
|
18
|
+
* its signature has arrived, and the signature arrives last: without a
|
|
19
|
+
* `done` the aggregator cannot tell a finished block from one still
|
|
20
|
+
* streaming, and a block replayed without its signature invalidates the
|
|
21
|
+
* whole conversation upstream — not just that block.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
function providerOver(events: unknown[], seen: { body?: Record<string, unknown> } = {}) {
|
|
25
|
+
const provider = new AnthropicProvider({ apiKey: 'test-key' })
|
|
26
|
+
;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
|
|
27
|
+
messages: {
|
|
28
|
+
create: vi.fn(async (body: Record<string, unknown>) => {
|
|
29
|
+
seen.body = body
|
|
30
|
+
return (async function* () {
|
|
31
|
+
for (const event of events) yield event
|
|
32
|
+
})()
|
|
33
|
+
}),
|
|
34
|
+
},
|
|
35
|
+
}
|
|
36
|
+
return provider
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function chunksOf(events: unknown[]): Promise<StreamChunk[]> {
|
|
40
|
+
const out: StreamChunk[] = []
|
|
41
|
+
for await (const chunk of providerOver(events).chatStream({
|
|
42
|
+
model: 'm',
|
|
43
|
+
messages: [{ role: 'user', content: 'q' }],
|
|
44
|
+
} as ChatCompletionParams)) {
|
|
45
|
+
out.push(chunk)
|
|
46
|
+
}
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const THINKING_STREAM = [
|
|
51
|
+
{ type: 'message_start', message: { id: 'msg_1' } },
|
|
52
|
+
{ type: 'content_block_start', index: 0, content_block: { type: 'thinking' } },
|
|
53
|
+
{
|
|
54
|
+
type: 'content_block_delta',
|
|
55
|
+
index: 0,
|
|
56
|
+
delta: { type: 'thinking_delta', thinking: 'step one' },
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
type: 'content_block_delta',
|
|
60
|
+
index: 0,
|
|
61
|
+
delta: { type: 'thinking_delta', thinking: ' then two' },
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
type: 'content_block_delta',
|
|
65
|
+
index: 0,
|
|
66
|
+
delta: { type: 'signature_delta', signature: 'sig-abc' },
|
|
67
|
+
},
|
|
68
|
+
{ type: 'content_block_stop', index: 0 },
|
|
69
|
+
{ type: 'content_block_start', index: 1, content_block: { type: 'text' } },
|
|
70
|
+
{ type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: 'the answer' } },
|
|
71
|
+
{ type: 'message_delta', delta: { stop_reason: 'end_turn' } },
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
function reasoningOf(chunks: StreamChunk[]) {
|
|
75
|
+
return chunks.map((c) => c.delta.reasoning).filter((r): r is NonNullable<typeof r> => Boolean(r))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
describe('a reasoning block streams, then closes', () => {
|
|
79
|
+
it('opens the block with its kind', async () => {
|
|
80
|
+
const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
|
|
81
|
+
|
|
82
|
+
expect(reasoning[0]).toMatchObject({ index: 0, type: 'thinking' })
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('carries each fragment through in order', async () => {
|
|
86
|
+
const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
|
|
87
|
+
|
|
88
|
+
expect(reasoning.map((r) => r.text).filter(Boolean)).toEqual(['step one', ' then two'])
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it('carries the signature, which arrives once at the end', async () => {
|
|
92
|
+
const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
|
|
93
|
+
|
|
94
|
+
expect(reasoning.find((r) => r.signature)?.signature).toBe('sig-abc')
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('closes the block so the aggregator knows the signature has landed', async () => {
|
|
98
|
+
const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
|
|
99
|
+
|
|
100
|
+
expect(reasoning.at(-1)).toEqual({ index: 0, done: true })
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('closes it before the text block starts, not after', async () => {
|
|
104
|
+
const chunks = await chunksOf(THINKING_STREAM)
|
|
105
|
+
const closeAt = chunks.findIndex((c) => c.delta.reasoning?.done)
|
|
106
|
+
const textAt = chunks.findIndex((c) => c.delta.content === 'the answer')
|
|
107
|
+
|
|
108
|
+
expect(closeAt).toBeGreaterThan(-1)
|
|
109
|
+
expect(closeAt).toBeLessThan(textAt)
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it('does not leak reasoning into the visible text', async () => {
|
|
113
|
+
const chunks = await chunksOf(THINKING_STREAM)
|
|
114
|
+
|
|
115
|
+
expect(chunks.map((c) => c.delta.content).filter(Boolean)).toEqual(['the answer'])
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('groups two blocks by their own index', async () => {
|
|
119
|
+
const reasoning = reasoningOf(
|
|
120
|
+
await chunksOf([
|
|
121
|
+
{ type: 'message_start', message: { id: 'm' } },
|
|
122
|
+
{ type: 'content_block_start', index: 0, content_block: { type: 'thinking' } },
|
|
123
|
+
{ type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'a' } },
|
|
124
|
+
{ type: 'content_block_stop', index: 0 },
|
|
125
|
+
{ type: 'content_block_start', index: 1, content_block: { type: 'thinking' } },
|
|
126
|
+
{ type: 'content_block_delta', index: 1, delta: { type: 'thinking_delta', thinking: 'b' } },
|
|
127
|
+
{ type: 'content_block_stop', index: 1 },
|
|
128
|
+
]),
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
expect(reasoning.filter((r) => r.done).map((r) => r.index)).toEqual([0, 1])
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it('carries a redacted block as an opaque payload rather than text', async () => {
|
|
135
|
+
const reasoning = reasoningOf(
|
|
136
|
+
await chunksOf([
|
|
137
|
+
{ type: 'message_start', message: { id: 'm' } },
|
|
138
|
+
{
|
|
139
|
+
type: 'content_block_start',
|
|
140
|
+
index: 0,
|
|
141
|
+
content_block: { type: 'redacted_thinking', data: 'opaque-bytes' },
|
|
142
|
+
},
|
|
143
|
+
{ type: 'content_block_stop', index: 0 },
|
|
144
|
+
]),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
expect(reasoning[0]).toMatchObject({ type: 'redacted_thinking', encrypted: 'opaque-bytes' })
|
|
148
|
+
expect(reasoning[0]?.text).toBeUndefined()
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('still closes a tool call, which shares the same stop event', async () => {
|
|
152
|
+
const chunks = await chunksOf([
|
|
153
|
+
{ type: 'message_start', message: { id: 'm' } },
|
|
154
|
+
{
|
|
155
|
+
type: 'content_block_start',
|
|
156
|
+
index: 0,
|
|
157
|
+
content_block: { type: 'tool_use', id: 'call_1', name: 'read' },
|
|
158
|
+
},
|
|
159
|
+
{ type: 'content_block_stop', index: 0 },
|
|
160
|
+
])
|
|
161
|
+
|
|
162
|
+
expect(chunks.some((c) => c.delta.toolCallEnd?.id === 'call_1')).toBe(true)
|
|
163
|
+
})
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
describe('thinking can be asked for', () => {
|
|
167
|
+
async function bodyFor(thinking: unknown): Promise<Record<string, unknown>> {
|
|
168
|
+
const seen: { body?: Record<string, unknown> } = {}
|
|
169
|
+
const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen)
|
|
170
|
+
for await (const _chunk of provider.chatStream({
|
|
171
|
+
model: 'm',
|
|
172
|
+
messages: [{ role: 'user', content: 'q' }],
|
|
173
|
+
...(thinking !== undefined ? { thinking } : {}),
|
|
174
|
+
} as ChatCompletionParams)) {
|
|
175
|
+
// drain
|
|
176
|
+
}
|
|
177
|
+
return seen.body ?? {}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
it('sends the budget the caller set', async () => {
|
|
181
|
+
expect(await bodyFor({ type: 'enabled', budgetTokens: 4096 })).toMatchObject({
|
|
182
|
+
thinking: { type: 'enabled', budget_tokens: 4096 },
|
|
183
|
+
})
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
it('enables it without a budget when none was named', async () => {
|
|
187
|
+
expect((await bodyFor({ type: 'enabled' })).thinking).toEqual({ type: 'enabled' })
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
it('can turn it off on a model where it is on by default', async () => {
|
|
191
|
+
expect((await bodyFor({ type: 'disabled' })).thinking).toEqual({ type: 'disabled' })
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
it('says nothing at all when the caller did not ask', async () => {
|
|
195
|
+
expect(await bodyFor(undefined)).not.toHaveProperty('thinking')
|
|
196
|
+
})
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
describe('a reasoned turn is replayed verbatim on the next request', () => {
|
|
200
|
+
async function messagesFor(assistant: Record<string, unknown>) {
|
|
201
|
+
const seen: { body?: Record<string, unknown> } = {}
|
|
202
|
+
const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen)
|
|
203
|
+
for await (const _chunk of provider.chatStream({
|
|
204
|
+
model: 'm',
|
|
205
|
+
messages: [{ role: 'user', content: 'q' }, assistant, { role: 'user', content: 'and then?' }],
|
|
206
|
+
} as unknown as ChatCompletionParams)) {
|
|
207
|
+
// drain
|
|
208
|
+
}
|
|
209
|
+
return seen.body?.messages as Array<{ role: string; content: unknown }>
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
it('replays the block with its signature intact', async () => {
|
|
213
|
+
const messages = await messagesFor({
|
|
214
|
+
role: 'assistant',
|
|
215
|
+
content: 'because of that',
|
|
216
|
+
reasoning: [{ type: 'thinking', text: 'step one', signature: 'sig-abc' }],
|
|
217
|
+
})
|
|
218
|
+
const blocks = messages[1]?.content as Record<string, unknown>[]
|
|
219
|
+
|
|
220
|
+
expect(blocks[0]).toEqual({ type: 'thinking', thinking: 'step one', signature: 'sig-abc' })
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
it('puts the reasoning first, as the wire requires', async () => {
|
|
224
|
+
const messages = await messagesFor({
|
|
225
|
+
role: 'assistant',
|
|
226
|
+
content: 'because of that',
|
|
227
|
+
reasoning: [{ type: 'thinking', text: 'step one', signature: 'sig' }],
|
|
228
|
+
})
|
|
229
|
+
const blocks = messages[1]?.content as Record<string, unknown>[]
|
|
230
|
+
|
|
231
|
+
expect(blocks.map((b) => b.type)).toEqual(['thinking', 'text'])
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
it('replays it ahead of a tool call too', async () => {
|
|
235
|
+
const messages = await messagesFor({
|
|
236
|
+
role: 'assistant',
|
|
237
|
+
content: null,
|
|
238
|
+
reasoning: [{ type: 'thinking', text: 'i should read it', signature: 'sig' }],
|
|
239
|
+
toolCalls: [{ id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } }],
|
|
240
|
+
})
|
|
241
|
+
const blocks = messages[1]?.content as Record<string, unknown>[]
|
|
242
|
+
|
|
243
|
+
expect(blocks.map((b) => b.type)).toEqual(['thinking', 'tool_use'])
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
it('replays a redacted block as its opaque payload', async () => {
|
|
247
|
+
const messages = await messagesFor({
|
|
248
|
+
role: 'assistant',
|
|
249
|
+
content: 'answer',
|
|
250
|
+
reasoning: [{ type: 'redacted_thinking', encrypted: 'opaque-bytes' }],
|
|
251
|
+
})
|
|
252
|
+
const blocks = messages[1]?.content as Record<string, unknown>[]
|
|
253
|
+
|
|
254
|
+
expect(blocks[0]).toEqual({ type: 'redacted_thinking', data: 'opaque-bytes' })
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
it('leaves an assistant turn that did not reason as a plain string', async () => {
|
|
258
|
+
const messages = await messagesFor({ role: 'assistant', content: 'just an answer' })
|
|
259
|
+
|
|
260
|
+
expect(messages[1]?.content).toBe('just an answer')
|
|
261
|
+
})
|
|
262
|
+
})
|
package/src/client.ts
CHANGED
|
@@ -3,18 +3,22 @@ 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'
|
|
19
23
|
import type { AnthropicConfig } from './types.js'
|
|
20
24
|
|
|
@@ -92,7 +96,8 @@ interface AnthropicToolUseBlock {
|
|
|
92
96
|
interface AnthropicToolResultBlock {
|
|
93
97
|
type: 'tool_result'
|
|
94
98
|
tool_use_id: string
|
|
95
|
-
|
|
99
|
+
/** Text, or the blocks this wire accepts inside a tool result. */
|
|
100
|
+
content: string | Array<AnthropicTextBlock | AnthropicImageBlock>
|
|
96
101
|
cache_control?: AnthropicCacheControl
|
|
97
102
|
}
|
|
98
103
|
|
|
@@ -110,10 +115,38 @@ interface AnthropicToolParam {
|
|
|
110
115
|
cache_control?: AnthropicCacheControl
|
|
111
116
|
}
|
|
112
117
|
|
|
113
|
-
/** Shape of an SDK `
|
|
118
|
+
/** Shape of an SDK `MessageAttachment` (read structurally to avoid coupling). */
|
|
114
119
|
interface AttachmentLike {
|
|
120
|
+
readonly type?: 'image' | 'document'
|
|
115
121
|
readonly data: string
|
|
116
122
|
readonly mediaType: string
|
|
123
|
+
readonly name?: string
|
|
124
|
+
readonly citations?: boolean
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A reasoning block, replayed exactly as it arrived.
|
|
129
|
+
*
|
|
130
|
+
* The signature is cryptographic and verified upstream: a block echoed
|
|
131
|
+
* back with its text edited, its signature dropped, or its order changed
|
|
132
|
+
* is rejected, which fails the whole conversation rather than one block.
|
|
133
|
+
* So this is a passthrough, never a re-render.
|
|
134
|
+
*/
|
|
135
|
+
interface AnthropicThinkingBlock {
|
|
136
|
+
type: 'thinking' | 'redacted_thinking'
|
|
137
|
+
thinking?: string
|
|
138
|
+
signature?: string
|
|
139
|
+
data?: string
|
|
140
|
+
cache_control?: AnthropicCacheControl
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface AnthropicDocumentBlock {
|
|
144
|
+
type: 'document'
|
|
145
|
+
source: { type: 'base64'; media_type: string; data: string }
|
|
146
|
+
title?: string
|
|
147
|
+
citations?: { enabled: true }
|
|
148
|
+
/** A document is the block most worth a breakpoint, being the largest. */
|
|
149
|
+
cache_control?: AnthropicCacheControl
|
|
117
150
|
}
|
|
118
151
|
|
|
119
152
|
type AnthropicContentBlock =
|
|
@@ -121,6 +154,8 @@ type AnthropicContentBlock =
|
|
|
121
154
|
| AnthropicToolUseBlock
|
|
122
155
|
| AnthropicToolResultBlock
|
|
123
156
|
| AnthropicImageBlock
|
|
157
|
+
| AnthropicDocumentBlock
|
|
158
|
+
| AnthropicThinkingBlock
|
|
124
159
|
|
|
125
160
|
interface AnthropicMessageParam {
|
|
126
161
|
role: 'user' | 'assistant'
|
|
@@ -155,6 +190,64 @@ function extractSystem(
|
|
|
155
190
|
return blocks
|
|
156
191
|
}
|
|
157
192
|
|
|
193
|
+
/**
|
|
194
|
+
* The reasoning blocks an assistant message carries, in wire form.
|
|
195
|
+
*
|
|
196
|
+
* Verbatim by contract, and first in the message: the API requires
|
|
197
|
+
* thinking blocks to lead, and the signature is verified, so re-rendering
|
|
198
|
+
* or reordering them invalidates the turn they belong to.
|
|
199
|
+
*/
|
|
200
|
+
function replayReasoning(msg: { reasoning?: readonly ReasoningBlock[] }): AnthropicThinkingBlock[] {
|
|
201
|
+
if (!msg.reasoning || msg.reasoning.length === 0) return []
|
|
202
|
+
return msg.reasoning.map((block) =>
|
|
203
|
+
block.type === 'redacted_thinking'
|
|
204
|
+
? {
|
|
205
|
+
type: 'redacted_thinking' as const,
|
|
206
|
+
...(block.encrypted ? { data: block.encrypted } : {}),
|
|
207
|
+
}
|
|
208
|
+
: {
|
|
209
|
+
type: 'thinking' as const,
|
|
210
|
+
thinking: block.text ?? '',
|
|
211
|
+
...(block.signature ? { signature: block.signature } : {}),
|
|
212
|
+
},
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* A tool result, in the richest form this wire accepts.
|
|
218
|
+
*
|
|
219
|
+
* The blocks used to be `JSON.stringify`d, so a screenshot reached the
|
|
220
|
+
* model as a wall of quoted base64 — the one thing the SDK's own degrade
|
|
221
|
+
* helper exists to avoid, and pure cost besides: the model paid for every
|
|
222
|
+
* character and could read none of them. This wire carries image blocks in
|
|
223
|
+
* a tool result natively, so they are sent as images.
|
|
224
|
+
*
|
|
225
|
+
* A document block still degrades to the named placeholder: tool results
|
|
226
|
+
* on this wire take text and images, not documents, and inventing an image
|
|
227
|
+
* block around a PDF would fail the request instead of the block.
|
|
228
|
+
*/
|
|
229
|
+
function toolResultContent(
|
|
230
|
+
content: ToolResultContent | undefined,
|
|
231
|
+
): string | Array<AnthropicTextBlock | AnthropicImageBlock> {
|
|
232
|
+
if (content === undefined) return ''
|
|
233
|
+
if (typeof content === 'string') return content
|
|
234
|
+
|
|
235
|
+
const blocks: Array<AnthropicTextBlock | AnthropicImageBlock> = []
|
|
236
|
+
for (const block of content) {
|
|
237
|
+
if (block.type === 'image') {
|
|
238
|
+
blocks.push({
|
|
239
|
+
type: 'image',
|
|
240
|
+
source: { type: 'base64', media_type: block.mediaType, data: block.data },
|
|
241
|
+
})
|
|
242
|
+
continue
|
|
243
|
+
}
|
|
244
|
+
const text = toolResultToText([block])
|
|
245
|
+
if (text.length > 0) blocks.push({ type: 'text', text })
|
|
246
|
+
}
|
|
247
|
+
// An empty array is rejected upstream; an empty string is not.
|
|
248
|
+
return blocks.length > 0 ? blocks : ''
|
|
249
|
+
}
|
|
250
|
+
|
|
158
251
|
function toAnthropicMessages(messages: ChatCompletionParams['messages']): AnthropicMessageParam[] {
|
|
159
252
|
const out: AnthropicMessageParam[] = []
|
|
160
253
|
let pendingToolResults: AnthropicToolResultBlock[] = []
|
|
@@ -170,12 +263,11 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
170
263
|
if (msg.role === 'system') continue
|
|
171
264
|
|
|
172
265
|
if (msg.role === 'tool') {
|
|
173
|
-
const toolMsg = msg as { toolCallId?: string; content?:
|
|
266
|
+
const toolMsg = msg as { toolCallId?: string; content?: ToolResultContent }
|
|
174
267
|
pendingToolResults.push({
|
|
175
268
|
type: 'tool_result',
|
|
176
269
|
tool_use_id: toolMsg.toolCallId ?? 'unknown',
|
|
177
|
-
content:
|
|
178
|
-
typeof toolMsg.content === 'string' ? toolMsg.content : JSON.stringify(toolMsg.content),
|
|
270
|
+
content: toolResultContent(toolMsg.content),
|
|
179
271
|
})
|
|
180
272
|
continue
|
|
181
273
|
}
|
|
@@ -183,7 +275,7 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
183
275
|
flushToolResults()
|
|
184
276
|
|
|
185
277
|
if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
|
|
186
|
-
const blocks: AnthropicContentBlock[] = []
|
|
278
|
+
const blocks: AnthropicContentBlock[] = [...replayReasoning(msg)]
|
|
187
279
|
if (msg.content && typeof msg.content === 'string') {
|
|
188
280
|
blocks.push({ type: 'text', text: msg.content })
|
|
189
281
|
}
|
|
@@ -205,7 +297,16 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
205
297
|
continue
|
|
206
298
|
}
|
|
207
299
|
|
|
300
|
+
// An assistant turn that reasoned replays those blocks even when it
|
|
301
|
+
// called no tool: dropping them invalidates the turn upstream.
|
|
302
|
+
const replayed = msg.role === 'assistant' ? replayReasoning(msg) : []
|
|
208
303
|
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
|
|
304
|
+
if (replayed.length > 0) {
|
|
305
|
+
const trailing: AnthropicContentBlock[] =
|
|
306
|
+
content.length > 0 ? [{ type: 'text', text: content }] : []
|
|
307
|
+
out.push({ role: 'assistant', content: [...replayed, ...trailing] })
|
|
308
|
+
continue
|
|
309
|
+
}
|
|
209
310
|
// User message with image attachments → multimodal content blocks
|
|
210
311
|
// (text first, then each image as a base64 image block).
|
|
211
312
|
const attachments = (msg as { attachments?: readonly AttachmentLike[] }).attachments
|
|
@@ -213,6 +314,23 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
213
314
|
const blocks: AnthropicContentBlock[] = []
|
|
214
315
|
if (content.length > 0) blocks.push({ type: 'text', text: content })
|
|
215
316
|
for (const att of attachments) {
|
|
317
|
+
// A document is not an image with a different media type. It
|
|
318
|
+
// used to be mapped as one, so a PDF went up as an image block
|
|
319
|
+
// the API rejects — while the capability set claimed documents
|
|
320
|
+
// were supported. The native block buys page structure, OCR,
|
|
321
|
+
// and the citations the SDK contract already has a slot for.
|
|
322
|
+
if (att.type === 'document') {
|
|
323
|
+
blocks.push({
|
|
324
|
+
type: 'document',
|
|
325
|
+
source: { type: 'base64', media_type: att.mediaType, data: att.data },
|
|
326
|
+
...(att.name ? { title: att.name } : {}),
|
|
327
|
+
// Opt-in: citations cost tokens, so they are requested
|
|
328
|
+
// only when the caller asked to be able to check the
|
|
329
|
+
// answer.
|
|
330
|
+
...(att.citations ? { citations: { enabled: true as const } } : {}),
|
|
331
|
+
})
|
|
332
|
+
continue
|
|
333
|
+
}
|
|
216
334
|
blocks.push({
|
|
217
335
|
type: 'image',
|
|
218
336
|
source: { type: 'base64', media_type: att.mediaType, data: att.data },
|
|
@@ -382,16 +500,77 @@ function mapStopReason(reason?: string | null): NamzuFinishReason {
|
|
|
382
500
|
// Stream event types
|
|
383
501
|
// --------------------------------------------------------------------------------------
|
|
384
502
|
|
|
503
|
+
/**
|
|
504
|
+
* A cited passage as it arrives on the wire.
|
|
505
|
+
*
|
|
506
|
+
* The location is reported three different ways depending on how the
|
|
507
|
+
* provider segmented the source, which is why the SDK's `Citation` keeps
|
|
508
|
+
* a discriminated union rather than flattening everything to a page
|
|
509
|
+
* number: two of the three shapes have no page to report.
|
|
510
|
+
*/
|
|
511
|
+
interface RawAnthropicCitation {
|
|
512
|
+
type?: string
|
|
513
|
+
cited_text?: string
|
|
514
|
+
document_index?: number
|
|
515
|
+
document_title?: string | null
|
|
516
|
+
start_page_number?: number
|
|
517
|
+
end_page_number?: number
|
|
518
|
+
start_char_index?: number
|
|
519
|
+
end_char_index?: number
|
|
520
|
+
start_block_index?: number
|
|
521
|
+
end_block_index?: number
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Map a wire citation onto the SDK's shape.
|
|
526
|
+
*
|
|
527
|
+
* Returns undefined rather than inventing a location: a citation whose
|
|
528
|
+
* source segment cannot be named is worse than none, because it looks
|
|
529
|
+
* checkable and is not.
|
|
530
|
+
*/
|
|
531
|
+
function toCitation(raw: RawAnthropicCitation, index: number): Citation | undefined {
|
|
532
|
+
const citedText = raw.cited_text
|
|
533
|
+
if (!citedText) return undefined
|
|
534
|
+
|
|
535
|
+
const location = (():
|
|
536
|
+
| { kind: 'page'; start: number; end: number }
|
|
537
|
+
| { kind: 'char'; start: number; end: number }
|
|
538
|
+
| { kind: 'block'; start: number; end: number }
|
|
539
|
+
| undefined => {
|
|
540
|
+
if (raw.start_page_number !== undefined && raw.end_page_number !== undefined) {
|
|
541
|
+
return { kind: 'page', start: raw.start_page_number, end: raw.end_page_number }
|
|
542
|
+
}
|
|
543
|
+
if (raw.start_char_index !== undefined && raw.end_char_index !== undefined) {
|
|
544
|
+
return { kind: 'char', start: raw.start_char_index, end: raw.end_char_index }
|
|
545
|
+
}
|
|
546
|
+
if (raw.start_block_index !== undefined && raw.end_block_index !== undefined) {
|
|
547
|
+
return { kind: 'block', start: raw.start_block_index, end: raw.end_block_index }
|
|
548
|
+
}
|
|
549
|
+
return undefined
|
|
550
|
+
})()
|
|
551
|
+
if (!location) return undefined
|
|
552
|
+
|
|
553
|
+
return {
|
|
554
|
+
citedText,
|
|
555
|
+
documentIndex: raw.document_index ?? index,
|
|
556
|
+
...(raw.document_title ? { documentTitle: raw.document_title } : {}),
|
|
557
|
+
location,
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
385
561
|
interface StreamEvent {
|
|
386
562
|
type: string
|
|
387
563
|
message?: { id?: string; usage?: RawAnthropicUsage }
|
|
388
564
|
index?: number
|
|
389
|
-
content_block?: { type?: string; id?: string; name?: string }
|
|
565
|
+
content_block?: { type?: string; id?: string; name?: string; data?: string }
|
|
390
566
|
delta?: {
|
|
391
567
|
type?: string
|
|
392
568
|
text?: string
|
|
393
569
|
partial_json?: string
|
|
394
570
|
stop_reason?: string | null
|
|
571
|
+
citation?: RawAnthropicCitation
|
|
572
|
+
thinking?: string
|
|
573
|
+
signature?: string
|
|
395
574
|
}
|
|
396
575
|
usage?: RawAnthropicUsage
|
|
397
576
|
}
|
|
@@ -410,6 +589,7 @@ export const ANTHROPIC_CAPABILITIES: ProviderCapabilities = {
|
|
|
410
589
|
supportsStreaming: true,
|
|
411
590
|
supportsFunctionCalling: true,
|
|
412
591
|
supportsVision: true,
|
|
592
|
+
supportsDocuments: true,
|
|
413
593
|
}
|
|
414
594
|
|
|
415
595
|
export class AnthropicProvider implements LLMProvider {
|
|
@@ -506,6 +686,20 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
506
686
|
// otherwise) — this also drops a parallelToolCalls-derived choice on
|
|
507
687
|
// tool-less requests.
|
|
508
688
|
if (tools && toolChoice) body.tool_choice = toolChoice
|
|
689
|
+
if (params.thinking) {
|
|
690
|
+
// Thinking could not be REQUESTED at all before this: on a model
|
|
691
|
+
// where it is off by default the feature was unreachable, and on
|
|
692
|
+
// one where it is on by default its budget could not be tuned.
|
|
693
|
+
body.thinking =
|
|
694
|
+
params.thinking.type === 'enabled'
|
|
695
|
+
? {
|
|
696
|
+
type: 'enabled',
|
|
697
|
+
...(params.thinking.budgetTokens !== undefined
|
|
698
|
+
? { budget_tokens: params.thinking.budgetTokens }
|
|
699
|
+
: {}),
|
|
700
|
+
}
|
|
701
|
+
: { type: 'disabled' }
|
|
702
|
+
}
|
|
509
703
|
if (params.temperature !== undefined) body.temperature = params.temperature
|
|
510
704
|
if (params.topP !== undefined) body.top_p = params.topP
|
|
511
705
|
if (params.topK !== undefined) body.top_k = params.topK
|
|
@@ -558,6 +752,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
558
752
|
// Track active tool-use blocks by content_block index so input_json_delta
|
|
559
753
|
// fragments can reference the right tool call.
|
|
560
754
|
const activeTools = new Map<number, { id: string; name: string }>()
|
|
755
|
+
const activeReasoning = new Set<number>()
|
|
561
756
|
|
|
562
757
|
// Anthropic Messages API streams over SSE. Do not impose a
|
|
563
758
|
// provider-local 90s idle cutoff by default: long reasoning or
|
|
@@ -618,6 +813,20 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
618
813
|
case 'content_block_start': {
|
|
619
814
|
const idx = event.index ?? 0
|
|
620
815
|
const block = event.content_block
|
|
816
|
+
if (block?.type === 'thinking' || block?.type === 'redacted_thinking') {
|
|
817
|
+
activeReasoning.add(idx)
|
|
818
|
+
yield {
|
|
819
|
+
id: messageId,
|
|
820
|
+
delta: {
|
|
821
|
+
reasoning: {
|
|
822
|
+
index: idx,
|
|
823
|
+
type: block.type,
|
|
824
|
+
...(block.data ? { encrypted: block.data } : {}),
|
|
825
|
+
},
|
|
826
|
+
},
|
|
827
|
+
}
|
|
828
|
+
break
|
|
829
|
+
}
|
|
621
830
|
if (block?.type === 'tool_use') {
|
|
622
831
|
const toolId = block.id ?? `tool-${Date.now()}`
|
|
623
832
|
activeTools.set(idx, { id: toolId, name: block.name ?? '' })
|
|
@@ -642,6 +851,24 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
642
851
|
const delta = event.delta
|
|
643
852
|
if (delta?.type === 'text_delta' && delta.text) {
|
|
644
853
|
yield { id: messageId, delta: { content: delta.text } }
|
|
854
|
+
} else if (delta?.type === 'thinking_delta' && delta.thinking !== undefined) {
|
|
855
|
+
yield {
|
|
856
|
+
id: messageId,
|
|
857
|
+
delta: { reasoning: { index: idx, text: delta.thinking } },
|
|
858
|
+
}
|
|
859
|
+
} else if (delta?.type === 'signature_delta' && delta.signature !== undefined) {
|
|
860
|
+
// Arrives once, at the end of the block, and has to
|
|
861
|
+
// reach the next request unmodified.
|
|
862
|
+
yield {
|
|
863
|
+
id: messageId,
|
|
864
|
+
delta: { reasoning: { index: idx, signature: delta.signature } },
|
|
865
|
+
}
|
|
866
|
+
} else if (delta?.type === 'citations_delta' && delta.citation) {
|
|
867
|
+
// Not text: a citation lands on the assistant
|
|
868
|
+
// message beside the prose, which is where the
|
|
869
|
+
// runtime's stream aggregator already puts it.
|
|
870
|
+
const citation = toCitation(delta.citation, idx)
|
|
871
|
+
if (citation) yield { id: messageId, delta: { citation } }
|
|
645
872
|
} else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
|
|
646
873
|
const active = activeTools.get(idx)
|
|
647
874
|
yield {
|
|
@@ -670,6 +897,13 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
670
897
|
// — exactly the failure the live cowork test
|
|
671
898
|
// surfaced (Bash + Write both blank-input failed).
|
|
672
899
|
const idx = event.index ?? 0
|
|
900
|
+
if (activeReasoning.delete(idx)) {
|
|
901
|
+
// Closes the block, exactly as toolCallEnd closes a
|
|
902
|
+
// tool call: without it the aggregator cannot know
|
|
903
|
+
// the signature has finished arriving.
|
|
904
|
+
yield { id: messageId, delta: { reasoning: { index: idx, done: true } } }
|
|
905
|
+
break
|
|
906
|
+
}
|
|
673
907
|
const active = activeTools.get(idx)
|
|
674
908
|
if (active) {
|
|
675
909
|
yield {
|