-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathanthropic.spec.ts
More file actions
824 lines (731 loc) · 22.9 KB
/
anthropic.spec.ts
File metadata and controls
824 lines (731 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
// npx vitest run src/api/providers/__tests__/anthropic.spec.ts
import { AnthropicHandler } from "../anthropic"
import { ApiHandlerOptions } from "../../../shared/api"
// Mock TelemetryService
vitest.mock("@roo-code/telemetry", () => ({
TelemetryService: {
instance: {
captureException: vitest.fn(),
},
},
}))
const mockCreate = vitest.fn()
vitest.mock("@anthropic-ai/sdk", () => {
const mockAnthropicConstructor = vitest.fn().mockImplementation(() => ({
messages: {
create: mockCreate.mockImplementation(async (options) => {
if (!options.stream) {
return {
id: "test-completion",
content: [{ type: "text", text: "Test response" }],
role: "assistant",
model: options.model,
usage: {
input_tokens: 10,
output_tokens: 5,
},
}
}
return {
async *[Symbol.asyncIterator]() {
yield {
type: "message_start",
message: {
usage: {
input_tokens: 100,
output_tokens: 50,
cache_creation_input_tokens: 20,
cache_read_input_tokens: 10,
},
},
}
yield {
type: "content_block_start",
index: 0,
content_block: {
type: "text",
text: "Hello",
},
}
yield {
type: "content_block_delta",
delta: {
type: "text_delta",
text: " world",
},
}
},
}
}),
},
}))
return {
Anthropic: mockAnthropicConstructor,
}
})
// Import after mock
import { Anthropic } from "@anthropic-ai/sdk"
const mockAnthropicConstructor = vitest.mocked(Anthropic)
describe("AnthropicHandler", () => {
let handler: AnthropicHandler
let mockOptions: ApiHandlerOptions
beforeEach(() => {
mockOptions = {
apiKey: "test-api-key",
apiModelId: "claude-3-5-sonnet-20241022",
}
handler = new AnthropicHandler(mockOptions)
vitest.clearAllMocks()
})
describe("constructor", () => {
it("should initialize with provided options", () => {
expect(handler).toBeInstanceOf(AnthropicHandler)
expect(handler.getModel().id).toBe(mockOptions.apiModelId)
})
it("should initialize with undefined API key", () => {
// The SDK will handle API key validation, so we just verify it initializes
const handlerWithoutKey = new AnthropicHandler({
...mockOptions,
apiKey: undefined,
})
expect(handlerWithoutKey).toBeInstanceOf(AnthropicHandler)
})
it("should use custom base URL if provided", () => {
const customBaseUrl = "https://custom.anthropic.com"
const handlerWithCustomUrl = new AnthropicHandler({
...mockOptions,
anthropicBaseUrl: customBaseUrl,
})
expect(handlerWithCustomUrl).toBeInstanceOf(AnthropicHandler)
})
it("use apiKey for passing token if anthropicUseAuthToken is not set", () => {
const handlerWithCustomUrl = new AnthropicHandler({
...mockOptions,
})
expect(handlerWithCustomUrl).toBeInstanceOf(AnthropicHandler)
expect(mockAnthropicConstructor).toHaveBeenCalledTimes(1)
expect(mockAnthropicConstructor.mock.calls[0]![0]!.apiKey).toEqual("test-api-key")
expect(mockAnthropicConstructor.mock.calls[0]![0]!.authToken).toBeUndefined()
})
it("use apiKey for passing token if anthropicUseAuthToken is set but custom base URL is not given", () => {
const handlerWithCustomUrl = new AnthropicHandler({
...mockOptions,
anthropicUseAuthToken: true,
})
expect(handlerWithCustomUrl).toBeInstanceOf(AnthropicHandler)
expect(mockAnthropicConstructor).toHaveBeenCalledTimes(1)
expect(mockAnthropicConstructor.mock.calls[0]![0]!.apiKey).toEqual("test-api-key")
expect(mockAnthropicConstructor.mock.calls[0]![0]!.authToken).toBeUndefined()
})
it("use authToken for passing token if both of anthropicBaseUrl and anthropicUseAuthToken are set", () => {
const customBaseUrl = "https://custom.anthropic.com"
const handlerWithCustomUrl = new AnthropicHandler({
...mockOptions,
anthropicBaseUrl: customBaseUrl,
anthropicUseAuthToken: true,
})
expect(handlerWithCustomUrl).toBeInstanceOf(AnthropicHandler)
expect(mockAnthropicConstructor).toHaveBeenCalledTimes(1)
expect(mockAnthropicConstructor.mock.calls[0]![0]!.authToken).toEqual("test-api-key")
expect(mockAnthropicConstructor.mock.calls[0]![0]!.apiKey).toBeUndefined()
})
})
describe("createMessage", () => {
const systemPrompt = "You are a helpful assistant."
it("should handle prompt caching for supported models", async () => {
const stream = handler.createMessage(systemPrompt, [
{
role: "user",
content: [{ type: "text" as const, text: "First message" }],
},
{
role: "assistant",
content: [{ type: "text" as const, text: "Response" }],
},
{
role: "user",
content: [{ type: "text" as const, text: "Second message" }],
},
])
const chunks: any[] = []
for await (const chunk of stream) {
chunks.push(chunk)
}
// Verify usage information
const usageChunk = chunks.find((chunk) => chunk.type === "usage")
expect(usageChunk).toBeDefined()
expect(usageChunk?.inputTokens).toBe(100)
expect(usageChunk?.outputTokens).toBe(50)
expect(usageChunk?.cacheWriteTokens).toBe(20)
expect(usageChunk?.cacheReadTokens).toBe(10)
// Verify text content
const textChunks = chunks.filter((chunk) => chunk.type === "text")
expect(textChunks).toHaveLength(2)
expect(textChunks[0].text).toBe("Hello")
expect(textChunks[1].text).toBe(" world")
// Verify API
expect(mockCreate).toHaveBeenCalled()
})
it("should include 1M context beta header for Claude Sonnet 4.6 when enabled", async () => {
const sonnet46Handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-sonnet-4-6",
anthropicBeta1MContext: true,
})
const stream = sonnet46Handler.createMessage(systemPrompt, [
{
role: "user",
content: [{ type: "text" as const, text: "Hello" }],
},
])
for await (const _chunk of stream) {
// Consume stream
}
const requestOptions = mockCreate.mock.calls[mockCreate.mock.calls.length - 1]?.[1]
expect(requestOptions?.headers?.["anthropic-beta"]).toContain("context-1m-2025-08-07")
})
})
describe("completePrompt", () => {
it("should complete prompt successfully", async () => {
const result = await handler.completePrompt("Test prompt")
expect(result).toBe("Test response")
expect(mockCreate).toHaveBeenCalledWith({
model: mockOptions.apiModelId,
messages: [{ role: "user", content: "Test prompt" }],
max_tokens: 8192,
temperature: 0,
thinking: undefined,
stream: false,
})
})
it("should handle API errors", async () => {
mockCreate.mockRejectedValueOnce(new Error("Anthropic completion error: API Error"))
await expect(handler.completePrompt("Test prompt")).rejects.toThrow("Anthropic completion error: API Error")
})
it("should handle non-text content", async () => {
mockCreate.mockImplementationOnce(async () => ({
content: [{ type: "image" }],
}))
const result = await handler.completePrompt("Test prompt")
expect(result).toBe("")
})
it("should handle empty response", async () => {
mockCreate.mockImplementationOnce(async () => ({
content: [{ type: "text", text: "" }],
}))
const result = await handler.completePrompt("Test prompt")
expect(result).toBe("")
})
})
describe("getModel", () => {
it("should return default model if no model ID is provided", () => {
const handlerWithoutModel = new AnthropicHandler({
...mockOptions,
apiModelId: undefined,
})
const model = handlerWithoutModel.getModel()
expect(model.id).toBeDefined()
expect(model.info).toBeDefined()
})
it("should return specified model if valid model ID is provided", () => {
const model = handler.getModel()
expect(model.id).toBe(mockOptions.apiModelId)
expect(model.info).toBeDefined()
expect(model.info.maxTokens).toBe(8192)
expect(model.info.contextWindow).toBe(200_000)
expect(model.info.supportsImages).toBe(true)
expect(model.info.supportsPromptCache).toBe(true)
})
it("honors custom maxTokens for thinking models", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-3-7-sonnet-20250219:thinking",
modelMaxTokens: 32_768,
modelMaxThinkingTokens: 16_384,
})
const result = handler.getModel()
expect(result.maxTokens).toBe(32_768)
expect(result.reasoningBudget).toEqual(16_384)
expect(result.temperature).toBe(1.0)
})
it("does not honor custom maxTokens for non-thinking models", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-3-7-sonnet-20250219",
modelMaxTokens: 32_768,
modelMaxThinkingTokens: 16_384,
})
const result = handler.getModel()
expect(result.maxTokens).toBe(8192)
expect(result.reasoningBudget).toBeUndefined()
expect(result.temperature).toBe(0)
})
it("should handle Claude 4.5 Sonnet model correctly", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-sonnet-4-5",
})
const model = handler.getModel()
expect(model.id).toBe("claude-sonnet-4-5")
expect(model.info.maxTokens).toBe(64000)
expect(model.info.contextWindow).toBe(200000)
expect(model.info.supportsReasoningBudget).toBe(true)
})
it("should handle Claude 4.6 Sonnet model correctly", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-sonnet-4-6",
})
const model = handler.getModel()
expect(model.id).toBe("claude-sonnet-4-6")
expect(model.info.maxTokens).toBe(64000)
expect(model.info.contextWindow).toBe(200000)
expect(model.info.supportsReasoningBudget).toBe(true)
})
it("should enable 1M context for Claude 4.5 Sonnet when beta flag is set", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-sonnet-4-5",
anthropicBeta1MContext: true,
})
const model = handler.getModel()
expect(model.info.contextWindow).toBe(1000000)
expect(model.info.inputPrice).toBe(6.0)
expect(model.info.outputPrice).toBe(22.5)
})
it("should enable 1M context for Claude 4.6 Sonnet when beta flag is set", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-sonnet-4-6",
anthropicBeta1MContext: true,
})
const model = handler.getModel()
expect(model.info.contextWindow).toBe(1000000)
expect(model.info.inputPrice).toBe(6.0)
expect(model.info.outputPrice).toBe(22.5)
})
it("should pass through custom/unknown model IDs instead of falling back to default", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "qwen/qwen3.6-plus",
})
const model = handler.getModel()
expect(model.id).toBe("qwen/qwen3.6-plus")
// Should use default model info as fallback for unknown models
expect(model.info).toBeDefined()
expect(model.info.contextWindow).toBeDefined()
})
it("should use default model ID when no model ID is provided at all", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: undefined,
})
const model = handler.getModel()
expect(model.id).toBeDefined()
// Should fall back to anthropicDefaultModelId, not an empty string
expect(model.id).not.toBe("")
})
it("should preserve custom model ID when using custom base URL", () => {
const handler = new AnthropicHandler({
apiKey: "test-api-key",
anthropicBaseUrl: "http://localhost:3000/api",
apiModelId: "my-custom-model",
})
const model = handler.getModel()
expect(model.id).toBe("my-custom-model")
})
})
describe("reasoning block filtering", () => {
const systemPrompt = "You are a helpful assistant."
it("should filter out internal reasoning blocks before sending to API", async () => {
handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-3-5-sonnet-20241022",
})
// Messages with internal reasoning blocks (from stored conversation history)
const messagesWithReasoning: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: "Hello",
},
{
role: "assistant",
content: [
{
type: "reasoning" as any,
text: "This is internal reasoning that should be filtered",
},
{
type: "text",
text: "This is the response",
},
],
},
{
role: "user",
content: "Continue",
},
]
const stream = handler.createMessage(systemPrompt, messagesWithReasoning)
const chunks: any[] = []
for await (const chunk of stream) {
chunks.push(chunk)
}
// Verify the API was called with filtered messages (no reasoning blocks)
const calledMessages = mockCreate.mock.calls[mockCreate.mock.calls.length - 1][0].messages
expect(calledMessages).toHaveLength(3)
// Check assistant message - should have reasoning block filtered out
const assistantMessage = calledMessages.find((m: any) => m.role === "assistant")
expect(assistantMessage).toBeDefined()
expect(assistantMessage.content).toEqual([{ type: "text", text: "This is the response" }])
// Verify reasoning blocks were NOT sent to the API
expect(assistantMessage.content).not.toContainEqual(expect.objectContaining({ type: "reasoning" }))
})
it("should filter empty messages after removing all reasoning blocks", async () => {
handler = new AnthropicHandler({
apiKey: "test-api-key",
apiModelId: "claude-3-5-sonnet-20241022",
})
// Message with only reasoning content (should be completely filtered)
const messagesWithOnlyReasoning: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: "Hello",
},
{
role: "assistant",
content: [
{
type: "reasoning" as any,
text: "Only reasoning, no actual text",
},
],
},
{
role: "user",
content: "Continue",
},
]
const stream = handler.createMessage(systemPrompt, messagesWithOnlyReasoning)
const chunks: any[] = []
for await (const chunk of stream) {
chunks.push(chunk)
}
// Verify empty message was filtered out
const calledMessages = mockCreate.mock.calls[mockCreate.mock.calls.length - 1][0].messages
expect(calledMessages.length).toBe(2) // Only the two user messages
expect(calledMessages.every((m: any) => m.role === "user")).toBe(true)
})
})
describe("native tool calling", () => {
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [{ type: "text" as const, text: "What's the weather in London?" }],
},
]
const mockTools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get the current weather",
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
},
},
]
it("should include tools in request when tools are provided", async () => {
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tools: expect.arrayContaining([
expect.objectContaining({
name: "get_weather",
description: "Get the current weather",
input_schema: expect.objectContaining({
type: "object",
properties: expect.objectContaining({
location: { type: "string" },
}),
}),
}),
]),
}),
expect.anything(),
)
})
it("should include tools when tools are provided", async () => {
const xmlHandler = new AnthropicHandler({
...mockOptions,
})
const stream = xmlHandler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
// Tool calling is request-driven: if tools are provided, we should include them.
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tools: expect.arrayContaining([
expect.objectContaining({
name: "get_weather",
}),
]),
}),
expect.anything(),
)
})
it("should always include tools in request (tools are always present after PR #10841)", async () => {
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
// Tools are now always present (minimum 6 from ALWAYS_AVAILABLE_TOOLS)
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tools: expect.any(Array),
tool_choice: expect.any(Object),
}),
expect.anything(),
)
})
it("should convert tool_choice 'auto' to Anthropic format", async () => {
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
tool_choice: "auto",
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tool_choice: { type: "auto", disable_parallel_tool_use: false },
}),
expect.anything(),
)
})
it("should convert tool_choice 'required' to Anthropic 'any' format", async () => {
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
tool_choice: "required",
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tool_choice: { type: "any", disable_parallel_tool_use: false },
}),
expect.anything(),
)
})
it("should set tool_choice to undefined when tool_choice is 'none' (tools are still passed)", async () => {
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
tool_choice: "none",
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
// Tools are now always present (minimum 6 from ALWAYS_AVAILABLE_TOOLS)
// When tool_choice is 'none', the converter returns undefined for tool_choice
// but tools are still passed since they're always present
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tools: expect.any(Array),
tool_choice: undefined,
}),
expect.anything(),
)
})
it("should convert specific tool_choice to Anthropic 'tool' format", async () => {
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
tool_choice: { type: "function" as const, function: { name: "get_weather" } },
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tool_choice: { type: "tool", name: "get_weather", disable_parallel_tool_use: false },
}),
expect.anything(),
)
})
it("should enable parallel tool calls when parallelToolCalls is true", async () => {
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
tool_choice: "auto",
parallelToolCalls: true,
})
// Consume the stream to trigger the API call
for await (const _chunk of stream) {
// Just consume
}
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({
tool_choice: { type: "auto", disable_parallel_tool_use: false },
}),
expect.anything(),
)
})
it("should handle tool_use blocks in stream and emit tool_call_partial", async () => {
mockCreate.mockImplementationOnce(async () => ({
async *[Symbol.asyncIterator]() {
yield {
type: "message_start",
message: {
usage: {
input_tokens: 100,
output_tokens: 50,
},
},
}
yield {
type: "content_block_start",
index: 0,
content_block: {
type: "tool_use",
id: "toolu_123",
name: "get_weather",
},
}
},
}))
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
})
const chunks: any[] = []
for await (const chunk of stream) {
chunks.push(chunk)
}
// Find the tool_call_partial chunk
const toolCallChunk = chunks.find((chunk) => chunk.type === "tool_call_partial")
expect(toolCallChunk).toBeDefined()
expect(toolCallChunk).toEqual({
type: "tool_call_partial",
index: 0,
id: "toolu_123",
name: "get_weather",
arguments: undefined,
})
})
it("should handle input_json_delta in stream and emit tool_call_partial arguments", async () => {
mockCreate.mockImplementationOnce(async () => ({
async *[Symbol.asyncIterator]() {
yield {
type: "message_start",
message: {
usage: {
input_tokens: 100,
output_tokens: 50,
},
},
}
yield {
type: "content_block_start",
index: 0,
content_block: {
type: "tool_use",
id: "toolu_123",
name: "get_weather",
},
}
yield {
type: "content_block_delta",
index: 0,
delta: {
type: "input_json_delta",
partial_json: '{"location":',
},
}
yield {
type: "content_block_delta",
index: 0,
delta: {
type: "input_json_delta",
partial_json: '"London"}',
},
}
yield {
type: "content_block_stop",
index: 0,
}
},
}))
// Handler uses native protocol by default
const stream = handler.createMessage(systemPrompt, messages, {
taskId: "test-task",
tools: mockTools,
})
const chunks: any[] = []
for await (const chunk of stream) {
chunks.push(chunk)
}
// Find the tool_call_partial chunks
const toolCallChunks = chunks.filter((chunk) => chunk.type === "tool_call_partial")
expect(toolCallChunks).toHaveLength(3)
// First chunk has id and name
expect(toolCallChunks[0]).toEqual({
type: "tool_call_partial",
index: 0,
id: "toolu_123",
name: "get_weather",
arguments: undefined,
})
// Subsequent chunks have arguments
expect(toolCallChunks[1]).toEqual({
type: "tool_call_partial",
index: 0,
id: undefined,
name: undefined,
arguments: '{"location":',
})
expect(toolCallChunks[2]).toEqual({
type: "tool_call_partial",
index: 0,
id: undefined,
name: undefined,
arguments: '"London"}',
})
})
})
})