@ai-sdk/anthropic 1.0.3 → 1.0.5

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.
@@ -0,0 +1,900 @@
1
+ // src/anthropic-messages-language-model.ts
2
+ import {
3
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError3
4
+ } from "@ai-sdk/provider";
5
+ import {
6
+ combineHeaders,
7
+ createEventSourceResponseHandler,
8
+ createJsonResponseHandler,
9
+ postJsonToApi,
10
+ resolve
11
+ } from "@ai-sdk/provider-utils";
12
+ import { z as z2 } from "zod";
13
+
14
+ // src/anthropic-error.ts
15
+ import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
16
+ import { z } from "zod";
17
+ var anthropicErrorDataSchema = z.object({
18
+ type: z.literal("error"),
19
+ error: z.object({
20
+ type: z.string(),
21
+ message: z.string()
22
+ })
23
+ });
24
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
25
+ errorSchema: anthropicErrorDataSchema,
26
+ errorToMessage: (data) => data.error.message
27
+ });
28
+
29
+ // src/convert-to-anthropic-messages-prompt.ts
30
+ import {
31
+ UnsupportedFunctionalityError
32
+ } from "@ai-sdk/provider";
33
+ import { convertUint8ArrayToBase64 } from "@ai-sdk/provider-utils";
34
+ function convertToAnthropicMessagesPrompt({
35
+ prompt,
36
+ cacheControl: isCacheControlEnabled
37
+ }) {
38
+ var _a, _b, _c, _d;
39
+ const betas = /* @__PURE__ */ new Set();
40
+ const blocks = groupIntoBlocks(prompt);
41
+ let system = void 0;
42
+ const messages = [];
43
+ function getCacheControl(providerMetadata) {
44
+ var _a2;
45
+ if (isCacheControlEnabled === false) {
46
+ return void 0;
47
+ }
48
+ const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
49
+ const cacheControlValue = (_a2 = anthropic == null ? void 0 : anthropic.cacheControl) != null ? _a2 : anthropic == null ? void 0 : anthropic.cache_control;
50
+ return cacheControlValue;
51
+ }
52
+ for (let i = 0; i < blocks.length; i++) {
53
+ const block = blocks[i];
54
+ const isLastBlock = i === blocks.length - 1;
55
+ const type = block.type;
56
+ switch (type) {
57
+ case "system": {
58
+ if (system != null) {
59
+ throw new UnsupportedFunctionalityError({
60
+ functionality: "Multiple system messages that are separated by user/assistant messages"
61
+ });
62
+ }
63
+ system = block.messages.map(({ content, providerMetadata }) => ({
64
+ type: "text",
65
+ text: content,
66
+ cache_control: getCacheControl(providerMetadata)
67
+ }));
68
+ break;
69
+ }
70
+ case "user": {
71
+ const anthropicContent = [];
72
+ for (const message of block.messages) {
73
+ const { role, content } = message;
74
+ switch (role) {
75
+ case "user": {
76
+ for (let j = 0; j < content.length; j++) {
77
+ const part = content[j];
78
+ const isLastPart = j === content.length - 1;
79
+ const cacheControl = (_a = getCacheControl(part.providerMetadata)) != null ? _a : isLastPart ? getCacheControl(message.providerMetadata) : void 0;
80
+ switch (part.type) {
81
+ case "text": {
82
+ anthropicContent.push({
83
+ type: "text",
84
+ text: part.text,
85
+ cache_control: cacheControl
86
+ });
87
+ break;
88
+ }
89
+ case "image": {
90
+ if (part.image instanceof URL) {
91
+ throw new UnsupportedFunctionalityError({
92
+ functionality: "Image URLs in user messages"
93
+ });
94
+ }
95
+ anthropicContent.push({
96
+ type: "image",
97
+ source: {
98
+ type: "base64",
99
+ media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
100
+ data: convertUint8ArrayToBase64(part.image)
101
+ },
102
+ cache_control: cacheControl
103
+ });
104
+ break;
105
+ }
106
+ case "file": {
107
+ if (part.data instanceof URL) {
108
+ throw new UnsupportedFunctionalityError({
109
+ functionality: "Image URLs in user messages"
110
+ });
111
+ }
112
+ if (part.mimeType !== "application/pdf") {
113
+ throw new UnsupportedFunctionalityError({
114
+ functionality: "Non-PDF files in user messages"
115
+ });
116
+ }
117
+ betas.add("pdfs-2024-09-25");
118
+ anthropicContent.push({
119
+ type: "document",
120
+ source: {
121
+ type: "base64",
122
+ media_type: "application/pdf",
123
+ data: part.data
124
+ },
125
+ cache_control: cacheControl
126
+ });
127
+ break;
128
+ }
129
+ }
130
+ }
131
+ break;
132
+ }
133
+ case "tool": {
134
+ for (let i2 = 0; i2 < content.length; i2++) {
135
+ const part = content[i2];
136
+ const isLastPart = i2 === content.length - 1;
137
+ const cacheControl = (_c = getCacheControl(part.providerMetadata)) != null ? _c : isLastPart ? getCacheControl(message.providerMetadata) : void 0;
138
+ const toolResultContent = part.content != null ? part.content.map((part2) => {
139
+ var _a2;
140
+ switch (part2.type) {
141
+ case "text":
142
+ return {
143
+ type: "text",
144
+ text: part2.text,
145
+ cache_control: void 0
146
+ };
147
+ case "image":
148
+ return {
149
+ type: "image",
150
+ source: {
151
+ type: "base64",
152
+ media_type: (_a2 = part2.mimeType) != null ? _a2 : "image/jpeg",
153
+ data: part2.data
154
+ },
155
+ cache_control: void 0
156
+ };
157
+ }
158
+ }) : JSON.stringify(part.result);
159
+ anthropicContent.push({
160
+ type: "tool_result",
161
+ tool_use_id: part.toolCallId,
162
+ content: toolResultContent,
163
+ is_error: part.isError,
164
+ cache_control: cacheControl
165
+ });
166
+ }
167
+ break;
168
+ }
169
+ default: {
170
+ const _exhaustiveCheck = role;
171
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
172
+ }
173
+ }
174
+ }
175
+ messages.push({ role: "user", content: anthropicContent });
176
+ break;
177
+ }
178
+ case "assistant": {
179
+ const anthropicContent = [];
180
+ for (let j = 0; j < block.messages.length; j++) {
181
+ const message = block.messages[j];
182
+ const isLastMessage = j === block.messages.length - 1;
183
+ const { content } = message;
184
+ for (let k = 0; k < content.length; k++) {
185
+ const part = content[k];
186
+ const isLastContentPart = k === content.length - 1;
187
+ const cacheControl = (_d = getCacheControl(part.providerMetadata)) != null ? _d : isLastContentPart ? getCacheControl(message.providerMetadata) : void 0;
188
+ switch (part.type) {
189
+ case "text": {
190
+ anthropicContent.push({
191
+ type: "text",
192
+ text: (
193
+ // trim the last text part if it's the last message in the block
194
+ // because Anthropic does not allow trailing whitespace
195
+ // in pre-filled assistant responses
196
+ isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text
197
+ ),
198
+ cache_control: cacheControl
199
+ });
200
+ break;
201
+ }
202
+ case "tool-call": {
203
+ anthropicContent.push({
204
+ type: "tool_use",
205
+ id: part.toolCallId,
206
+ name: part.toolName,
207
+ input: part.args,
208
+ cache_control: cacheControl
209
+ });
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ }
215
+ messages.push({ role: "assistant", content: anthropicContent });
216
+ break;
217
+ }
218
+ default: {
219
+ const _exhaustiveCheck = type;
220
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
221
+ }
222
+ }
223
+ }
224
+ return {
225
+ prompt: { system, messages },
226
+ betas
227
+ };
228
+ }
229
+ function groupIntoBlocks(prompt) {
230
+ const blocks = [];
231
+ let currentBlock = void 0;
232
+ for (const message of prompt) {
233
+ const { role } = message;
234
+ switch (role) {
235
+ case "system": {
236
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
237
+ currentBlock = { type: "system", messages: [] };
238
+ blocks.push(currentBlock);
239
+ }
240
+ currentBlock.messages.push(message);
241
+ break;
242
+ }
243
+ case "assistant": {
244
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
245
+ currentBlock = { type: "assistant", messages: [] };
246
+ blocks.push(currentBlock);
247
+ }
248
+ currentBlock.messages.push(message);
249
+ break;
250
+ }
251
+ case "user": {
252
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
253
+ currentBlock = { type: "user", messages: [] };
254
+ blocks.push(currentBlock);
255
+ }
256
+ currentBlock.messages.push(message);
257
+ break;
258
+ }
259
+ case "tool": {
260
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
261
+ currentBlock = { type: "user", messages: [] };
262
+ blocks.push(currentBlock);
263
+ }
264
+ currentBlock.messages.push(message);
265
+ break;
266
+ }
267
+ default: {
268
+ const _exhaustiveCheck = role;
269
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
270
+ }
271
+ }
272
+ }
273
+ return blocks;
274
+ }
275
+
276
+ // src/map-anthropic-stop-reason.ts
277
+ function mapAnthropicStopReason(finishReason) {
278
+ switch (finishReason) {
279
+ case "end_turn":
280
+ case "stop_sequence":
281
+ return "stop";
282
+ case "tool_use":
283
+ return "tool-calls";
284
+ case "max_tokens":
285
+ return "length";
286
+ default:
287
+ return "unknown";
288
+ }
289
+ }
290
+
291
+ // src/anthropic-prepare-tools.ts
292
+ import {
293
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError2
294
+ } from "@ai-sdk/provider";
295
+ function prepareTools(mode) {
296
+ var _a;
297
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
298
+ const toolWarnings = [];
299
+ const betas = /* @__PURE__ */ new Set();
300
+ if (tools == null) {
301
+ return { tools: void 0, tool_choice: void 0, toolWarnings, betas };
302
+ }
303
+ const anthropicTools2 = [];
304
+ for (const tool of tools) {
305
+ switch (tool.type) {
306
+ case "function":
307
+ anthropicTools2.push({
308
+ name: tool.name,
309
+ description: tool.description,
310
+ input_schema: tool.parameters
311
+ });
312
+ break;
313
+ case "provider-defined":
314
+ betas.add("computer-use-2024-10-22");
315
+ switch (tool.id) {
316
+ case "anthropic.computer_20241022":
317
+ anthropicTools2.push({
318
+ name: tool.name,
319
+ type: "computer_20241022",
320
+ display_width_px: tool.args.displayWidthPx,
321
+ display_height_px: tool.args.displayHeightPx,
322
+ display_number: tool.args.displayNumber
323
+ });
324
+ break;
325
+ case "anthropic.text_editor_20241022":
326
+ anthropicTools2.push({
327
+ name: tool.name,
328
+ type: "text_editor_20241022"
329
+ });
330
+ break;
331
+ case "anthropic.bash_20241022":
332
+ anthropicTools2.push({
333
+ name: tool.name,
334
+ type: "bash_20241022"
335
+ });
336
+ break;
337
+ default:
338
+ toolWarnings.push({ type: "unsupported-tool", tool });
339
+ break;
340
+ }
341
+ break;
342
+ default:
343
+ toolWarnings.push({ type: "unsupported-tool", tool });
344
+ break;
345
+ }
346
+ }
347
+ const toolChoice = mode.toolChoice;
348
+ if (toolChoice == null) {
349
+ return {
350
+ tools: anthropicTools2,
351
+ tool_choice: void 0,
352
+ toolWarnings,
353
+ betas
354
+ };
355
+ }
356
+ const type = toolChoice.type;
357
+ switch (type) {
358
+ case "auto":
359
+ return {
360
+ tools: anthropicTools2,
361
+ tool_choice: { type: "auto" },
362
+ toolWarnings,
363
+ betas
364
+ };
365
+ case "required":
366
+ return {
367
+ tools: anthropicTools2,
368
+ tool_choice: { type: "any" },
369
+ toolWarnings,
370
+ betas
371
+ };
372
+ case "none":
373
+ return { tools: void 0, tool_choice: void 0, toolWarnings, betas };
374
+ case "tool":
375
+ return {
376
+ tools: anthropicTools2,
377
+ tool_choice: { type: "tool", name: toolChoice.toolName },
378
+ toolWarnings,
379
+ betas
380
+ };
381
+ default: {
382
+ const _exhaustiveCheck = type;
383
+ throw new UnsupportedFunctionalityError2({
384
+ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
385
+ });
386
+ }
387
+ }
388
+ }
389
+
390
+ // src/anthropic-messages-language-model.ts
391
+ var AnthropicMessagesLanguageModel = class {
392
+ constructor(modelId, settings, config) {
393
+ this.specificationVersion = "v1";
394
+ this.defaultObjectGenerationMode = "tool";
395
+ this.supportsImageUrls = false;
396
+ this.modelId = modelId;
397
+ this.settings = settings;
398
+ this.config = config;
399
+ }
400
+ get provider() {
401
+ return this.config.provider;
402
+ }
403
+ async getArgs({
404
+ mode,
405
+ prompt,
406
+ maxTokens,
407
+ temperature,
408
+ topP,
409
+ topK,
410
+ frequencyPenalty,
411
+ presencePenalty,
412
+ stopSequences,
413
+ responseFormat,
414
+ seed
415
+ }) {
416
+ var _a;
417
+ const type = mode.type;
418
+ const warnings = [];
419
+ if (frequencyPenalty != null) {
420
+ warnings.push({
421
+ type: "unsupported-setting",
422
+ setting: "frequencyPenalty"
423
+ });
424
+ }
425
+ if (presencePenalty != null) {
426
+ warnings.push({
427
+ type: "unsupported-setting",
428
+ setting: "presencePenalty"
429
+ });
430
+ }
431
+ if (seed != null) {
432
+ warnings.push({
433
+ type: "unsupported-setting",
434
+ setting: "seed"
435
+ });
436
+ }
437
+ if (responseFormat != null && responseFormat.type !== "text") {
438
+ warnings.push({
439
+ type: "unsupported-setting",
440
+ setting: "responseFormat",
441
+ details: "JSON response format is not supported."
442
+ });
443
+ }
444
+ const { prompt: messagesPrompt, betas: messagesBetas } = convertToAnthropicMessagesPrompt({
445
+ prompt,
446
+ cacheControl: (_a = this.settings.cacheControl) != null ? _a : false
447
+ });
448
+ const baseArgs = {
449
+ // model id:
450
+ model: this.modelId,
451
+ // standardized settings:
452
+ max_tokens: maxTokens != null ? maxTokens : 4096,
453
+ // 4096: max model output tokens TODO remove
454
+ temperature,
455
+ top_k: topK,
456
+ top_p: topP,
457
+ stop_sequences: stopSequences,
458
+ // prompt:
459
+ system: messagesPrompt.system,
460
+ messages: messagesPrompt.messages
461
+ };
462
+ switch (type) {
463
+ case "regular": {
464
+ const {
465
+ tools,
466
+ tool_choice,
467
+ toolWarnings,
468
+ betas: toolsBetas
469
+ } = prepareTools(mode);
470
+ return {
471
+ args: { ...baseArgs, tools, tool_choice },
472
+ warnings: [...warnings, ...toolWarnings],
473
+ betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas])
474
+ };
475
+ }
476
+ case "object-json": {
477
+ throw new UnsupportedFunctionalityError3({
478
+ functionality: "json-mode object generation"
479
+ });
480
+ }
481
+ case "object-tool": {
482
+ const { name, description, parameters } = mode.tool;
483
+ return {
484
+ args: {
485
+ ...baseArgs,
486
+ tools: [{ name, description, input_schema: parameters }],
487
+ tool_choice: { type: "tool", name }
488
+ },
489
+ warnings,
490
+ betas: messagesBetas
491
+ };
492
+ }
493
+ default: {
494
+ const _exhaustiveCheck = type;
495
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
496
+ }
497
+ }
498
+ }
499
+ async getHeaders({
500
+ betas,
501
+ headers
502
+ }) {
503
+ if (this.settings.cacheControl) {
504
+ betas.add("prompt-caching-2024-07-31");
505
+ }
506
+ return combineHeaders(
507
+ await resolve(this.config.headers),
508
+ betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
509
+ headers
510
+ );
511
+ }
512
+ buildRequestUrl(isStreaming) {
513
+ var _a, _b, _c;
514
+ return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
515
+ }
516
+ transformRequestBody(args) {
517
+ var _a, _b, _c;
518
+ return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
519
+ }
520
+ async doGenerate(options) {
521
+ var _a, _b, _c, _d;
522
+ const { args, warnings, betas } = await this.getArgs(options);
523
+ const { responseHeaders, value: response } = await postJsonToApi({
524
+ url: this.buildRequestUrl(false),
525
+ headers: await this.getHeaders({ betas, headers: options.headers }),
526
+ body: this.transformRequestBody(args),
527
+ failedResponseHandler: anthropicFailedResponseHandler,
528
+ successfulResponseHandler: createJsonResponseHandler(
529
+ anthropicMessagesResponseSchema
530
+ ),
531
+ abortSignal: options.abortSignal,
532
+ fetch: this.config.fetch
533
+ });
534
+ const { messages: rawPrompt, ...rawSettings } = args;
535
+ let text = "";
536
+ for (const content of response.content) {
537
+ if (content.type === "text") {
538
+ text += content.text;
539
+ }
540
+ }
541
+ let toolCalls = void 0;
542
+ if (response.content.some((content) => content.type === "tool_use")) {
543
+ toolCalls = [];
544
+ for (const content of response.content) {
545
+ if (content.type === "tool_use") {
546
+ toolCalls.push({
547
+ toolCallType: "function",
548
+ toolCallId: content.id,
549
+ toolName: content.name,
550
+ args: JSON.stringify(content.input)
551
+ });
552
+ }
553
+ }
554
+ }
555
+ return {
556
+ text,
557
+ toolCalls,
558
+ finishReason: mapAnthropicStopReason(response.stop_reason),
559
+ usage: {
560
+ promptTokens: response.usage.input_tokens,
561
+ completionTokens: response.usage.output_tokens
562
+ },
563
+ rawCall: { rawPrompt, rawSettings },
564
+ rawResponse: { headers: responseHeaders },
565
+ response: {
566
+ id: (_a = response.id) != null ? _a : void 0,
567
+ modelId: (_b = response.model) != null ? _b : void 0
568
+ },
569
+ warnings,
570
+ providerMetadata: this.settings.cacheControl === true ? {
571
+ anthropic: {
572
+ cacheCreationInputTokens: (_c = response.usage.cache_creation_input_tokens) != null ? _c : null,
573
+ cacheReadInputTokens: (_d = response.usage.cache_read_input_tokens) != null ? _d : null
574
+ }
575
+ } : void 0,
576
+ request: { body: JSON.stringify(args) }
577
+ };
578
+ }
579
+ async doStream(options) {
580
+ const { args, warnings, betas } = await this.getArgs(options);
581
+ const body = { ...args, stream: true };
582
+ const { responseHeaders, value: response } = await postJsonToApi({
583
+ url: this.buildRequestUrl(true),
584
+ headers: await this.getHeaders({ betas, headers: options.headers }),
585
+ body: this.transformRequestBody(body),
586
+ failedResponseHandler: anthropicFailedResponseHandler,
587
+ successfulResponseHandler: createEventSourceResponseHandler(
588
+ anthropicMessagesChunkSchema
589
+ ),
590
+ abortSignal: options.abortSignal,
591
+ fetch: this.config.fetch
592
+ });
593
+ const { messages: rawPrompt, ...rawSettings } = args;
594
+ let finishReason = "unknown";
595
+ const usage = {
596
+ promptTokens: Number.NaN,
597
+ completionTokens: Number.NaN
598
+ };
599
+ const toolCallContentBlocks = {};
600
+ let providerMetadata = void 0;
601
+ const self = this;
602
+ return {
603
+ stream: response.pipeThrough(
604
+ new TransformStream({
605
+ transform(chunk, controller) {
606
+ var _a, _b, _c, _d;
607
+ if (!chunk.success) {
608
+ controller.enqueue({ type: "error", error: chunk.error });
609
+ return;
610
+ }
611
+ const value = chunk.value;
612
+ switch (value.type) {
613
+ case "ping": {
614
+ return;
615
+ }
616
+ case "content_block_start": {
617
+ const contentBlockType = value.content_block.type;
618
+ switch (contentBlockType) {
619
+ case "text": {
620
+ return;
621
+ }
622
+ case "tool_use": {
623
+ toolCallContentBlocks[value.index] = {
624
+ toolCallId: value.content_block.id,
625
+ toolName: value.content_block.name,
626
+ jsonText: ""
627
+ };
628
+ return;
629
+ }
630
+ default: {
631
+ const _exhaustiveCheck = contentBlockType;
632
+ throw new Error(
633
+ `Unsupported content block type: ${_exhaustiveCheck}`
634
+ );
635
+ }
636
+ }
637
+ }
638
+ case "content_block_stop": {
639
+ if (toolCallContentBlocks[value.index] != null) {
640
+ const contentBlock = toolCallContentBlocks[value.index];
641
+ controller.enqueue({
642
+ type: "tool-call",
643
+ toolCallType: "function",
644
+ toolCallId: contentBlock.toolCallId,
645
+ toolName: contentBlock.toolName,
646
+ args: contentBlock.jsonText
647
+ });
648
+ delete toolCallContentBlocks[value.index];
649
+ }
650
+ return;
651
+ }
652
+ case "content_block_delta": {
653
+ const deltaType = value.delta.type;
654
+ switch (deltaType) {
655
+ case "text_delta": {
656
+ controller.enqueue({
657
+ type: "text-delta",
658
+ textDelta: value.delta.text
659
+ });
660
+ return;
661
+ }
662
+ case "input_json_delta": {
663
+ const contentBlock = toolCallContentBlocks[value.index];
664
+ controller.enqueue({
665
+ type: "tool-call-delta",
666
+ toolCallType: "function",
667
+ toolCallId: contentBlock.toolCallId,
668
+ toolName: contentBlock.toolName,
669
+ argsTextDelta: value.delta.partial_json
670
+ });
671
+ contentBlock.jsonText += value.delta.partial_json;
672
+ return;
673
+ }
674
+ default: {
675
+ const _exhaustiveCheck = deltaType;
676
+ throw new Error(
677
+ `Unsupported delta type: ${_exhaustiveCheck}`
678
+ );
679
+ }
680
+ }
681
+ }
682
+ case "message_start": {
683
+ usage.promptTokens = value.message.usage.input_tokens;
684
+ usage.completionTokens = value.message.usage.output_tokens;
685
+ if (self.settings.cacheControl === true) {
686
+ providerMetadata = {
687
+ anthropic: {
688
+ cacheCreationInputTokens: (_a = value.message.usage.cache_creation_input_tokens) != null ? _a : null,
689
+ cacheReadInputTokens: (_b = value.message.usage.cache_read_input_tokens) != null ? _b : null
690
+ }
691
+ };
692
+ }
693
+ controller.enqueue({
694
+ type: "response-metadata",
695
+ id: (_c = value.message.id) != null ? _c : void 0,
696
+ modelId: (_d = value.message.model) != null ? _d : void 0
697
+ });
698
+ return;
699
+ }
700
+ case "message_delta": {
701
+ usage.completionTokens = value.usage.output_tokens;
702
+ finishReason = mapAnthropicStopReason(value.delta.stop_reason);
703
+ return;
704
+ }
705
+ case "message_stop": {
706
+ controller.enqueue({
707
+ type: "finish",
708
+ finishReason,
709
+ usage,
710
+ providerMetadata
711
+ });
712
+ return;
713
+ }
714
+ case "error": {
715
+ controller.enqueue({ type: "error", error: value.error });
716
+ return;
717
+ }
718
+ default: {
719
+ const _exhaustiveCheck = value;
720
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
721
+ }
722
+ }
723
+ }
724
+ })
725
+ ),
726
+ rawCall: { rawPrompt, rawSettings },
727
+ rawResponse: { headers: responseHeaders },
728
+ warnings,
729
+ request: { body: JSON.stringify(body) }
730
+ };
731
+ }
732
+ };
733
+ var anthropicMessagesResponseSchema = z2.object({
734
+ type: z2.literal("message"),
735
+ id: z2.string().nullish(),
736
+ model: z2.string().nullish(),
737
+ content: z2.array(
738
+ z2.discriminatedUnion("type", [
739
+ z2.object({
740
+ type: z2.literal("text"),
741
+ text: z2.string()
742
+ }),
743
+ z2.object({
744
+ type: z2.literal("tool_use"),
745
+ id: z2.string(),
746
+ name: z2.string(),
747
+ input: z2.unknown()
748
+ })
749
+ ])
750
+ ),
751
+ stop_reason: z2.string().nullish(),
752
+ usage: z2.object({
753
+ input_tokens: z2.number(),
754
+ output_tokens: z2.number(),
755
+ cache_creation_input_tokens: z2.number().nullish(),
756
+ cache_read_input_tokens: z2.number().nullish()
757
+ })
758
+ });
759
+ var anthropicMessagesChunkSchema = z2.discriminatedUnion("type", [
760
+ z2.object({
761
+ type: z2.literal("message_start"),
762
+ message: z2.object({
763
+ id: z2.string().nullish(),
764
+ model: z2.string().nullish(),
765
+ usage: z2.object({
766
+ input_tokens: z2.number(),
767
+ output_tokens: z2.number(),
768
+ cache_creation_input_tokens: z2.number().nullish(),
769
+ cache_read_input_tokens: z2.number().nullish()
770
+ })
771
+ })
772
+ }),
773
+ z2.object({
774
+ type: z2.literal("content_block_start"),
775
+ index: z2.number(),
776
+ content_block: z2.discriminatedUnion("type", [
777
+ z2.object({
778
+ type: z2.literal("text"),
779
+ text: z2.string()
780
+ }),
781
+ z2.object({
782
+ type: z2.literal("tool_use"),
783
+ id: z2.string(),
784
+ name: z2.string()
785
+ })
786
+ ])
787
+ }),
788
+ z2.object({
789
+ type: z2.literal("content_block_delta"),
790
+ index: z2.number(),
791
+ delta: z2.discriminatedUnion("type", [
792
+ z2.object({
793
+ type: z2.literal("input_json_delta"),
794
+ partial_json: z2.string()
795
+ }),
796
+ z2.object({
797
+ type: z2.literal("text_delta"),
798
+ text: z2.string()
799
+ })
800
+ ])
801
+ }),
802
+ z2.object({
803
+ type: z2.literal("content_block_stop"),
804
+ index: z2.number()
805
+ }),
806
+ z2.object({
807
+ type: z2.literal("error"),
808
+ error: z2.object({
809
+ type: z2.string(),
810
+ message: z2.string()
811
+ })
812
+ }),
813
+ z2.object({
814
+ type: z2.literal("message_delta"),
815
+ delta: z2.object({ stop_reason: z2.string().nullish() }),
816
+ usage: z2.object({ output_tokens: z2.number() })
817
+ }),
818
+ z2.object({
819
+ type: z2.literal("message_stop")
820
+ }),
821
+ z2.object({
822
+ type: z2.literal("ping")
823
+ })
824
+ ]);
825
+
826
+ // src/anthropic-tools.ts
827
+ import { z as z3 } from "zod";
828
+ var Bash20241022Parameters = z3.object({
829
+ command: z3.string(),
830
+ restart: z3.boolean().optional()
831
+ });
832
+ function bashTool_20241022(options = {}) {
833
+ return {
834
+ type: "provider-defined",
835
+ id: "anthropic.bash_20241022",
836
+ args: {},
837
+ parameters: Bash20241022Parameters,
838
+ execute: options.execute,
839
+ experimental_toToolResultContent: options.experimental_toToolResultContent
840
+ };
841
+ }
842
+ var TextEditor20241022Parameters = z3.object({
843
+ command: z3.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
844
+ path: z3.string(),
845
+ file_text: z3.string().optional(),
846
+ insert_line: z3.number().int().optional(),
847
+ new_str: z3.string().optional(),
848
+ old_str: z3.string().optional(),
849
+ view_range: z3.array(z3.number().int()).optional()
850
+ });
851
+ function textEditorTool_20241022(options = {}) {
852
+ return {
853
+ type: "provider-defined",
854
+ id: "anthropic.text_editor_20241022",
855
+ args: {},
856
+ parameters: TextEditor20241022Parameters,
857
+ execute: options.execute,
858
+ experimental_toToolResultContent: options.experimental_toToolResultContent
859
+ };
860
+ }
861
+ var Computer20241022Parameters = z3.object({
862
+ action: z3.enum([
863
+ "key",
864
+ "type",
865
+ "mouse_move",
866
+ "left_click",
867
+ "left_click_drag",
868
+ "right_click",
869
+ "middle_click",
870
+ "double_click",
871
+ "screenshot",
872
+ "cursor_position"
873
+ ]),
874
+ coordinate: z3.array(z3.number().int()).optional(),
875
+ text: z3.string().optional()
876
+ });
877
+ function computerTool_20241022(options) {
878
+ return {
879
+ type: "provider-defined",
880
+ id: "anthropic.computer_20241022",
881
+ args: {
882
+ displayWidthPx: options.displayWidthPx,
883
+ displayHeightPx: options.displayHeightPx,
884
+ displayNumber: options.displayNumber
885
+ },
886
+ parameters: Computer20241022Parameters,
887
+ execute: options.execute,
888
+ experimental_toToolResultContent: options.experimental_toToolResultContent
889
+ };
890
+ }
891
+ var anthropicTools = {
892
+ bash_20241022: bashTool_20241022,
893
+ textEditor_20241022: textEditorTool_20241022,
894
+ computer_20241022: computerTool_20241022
895
+ };
896
+ export {
897
+ AnthropicMessagesLanguageModel,
898
+ anthropicTools
899
+ };
900
+ //# sourceMappingURL=index.mjs.map