@ai-sdk/anthropic 2.0.0-alpha.1 → 2.0.0-alpha.11

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/dist/index.js CHANGED
@@ -51,6 +51,36 @@ var anthropicFailedResponseHandler = (0, import_provider_utils.createJsonErrorRe
51
51
 
52
52
  // src/anthropic-messages-options.ts
53
53
  var import_zod2 = require("zod");
54
+ var webSearchLocationSchema = import_zod2.z.object({
55
+ type: import_zod2.z.literal("approximate"),
56
+ city: import_zod2.z.string().optional(),
57
+ region: import_zod2.z.string().optional(),
58
+ country: import_zod2.z.string(),
59
+ timezone: import_zod2.z.string().optional()
60
+ });
61
+ var anthropicFilePartProviderOptions = import_zod2.z.object({
62
+ /**
63
+ * Citation configuration for this document.
64
+ * When enabled, this document will generate citations in the response.
65
+ */
66
+ citations: import_zod2.z.object({
67
+ /**
68
+ * Enable citations for this document
69
+ */
70
+ enabled: import_zod2.z.boolean()
71
+ }).optional(),
72
+ /**
73
+ * Custom title for the document.
74
+ * If not provided, the filename will be used.
75
+ */
76
+ title: import_zod2.z.string().optional(),
77
+ /**
78
+ * Context about the document that will be passed to the model
79
+ * but not used towards cited content.
80
+ * Useful for storing document metadata as text or stringified JSON.
81
+ */
82
+ context: import_zod2.z.string().optional()
83
+ });
54
84
  var anthropicProviderOptions = import_zod2.z.object({
55
85
  /**
56
86
  Include reasoning content in requests sent to the model. Defaults to `true`.
@@ -61,11 +91,39 @@ var anthropicProviderOptions = import_zod2.z.object({
61
91
  thinking: import_zod2.z.object({
62
92
  type: import_zod2.z.union([import_zod2.z.literal("enabled"), import_zod2.z.literal("disabled")]),
63
93
  budgetTokens: import_zod2.z.number().optional()
94
+ }).optional(),
95
+ /**
96
+ * Web search tool configuration for Claude models that support it.
97
+ * When provided, automatically adds the web search tool to the request.
98
+ */
99
+ webSearch: import_zod2.z.object({
100
+ /**
101
+ * Limit the number of searches per request (optional)
102
+ * Defaults to 5 if not specified
103
+ */
104
+ maxUses: import_zod2.z.number().min(1).max(20).optional(),
105
+ /**
106
+ * Only include results from these domains (optional)
107
+ * Cannot be used with blockedDomains
108
+ */
109
+ allowedDomains: import_zod2.z.array(import_zod2.z.string()).optional(),
110
+ /**
111
+ * Never include results from these domains (optional)
112
+ * Cannot be used with allowedDomains
113
+ */
114
+ blockedDomains: import_zod2.z.array(import_zod2.z.string()).optional(),
115
+ /**
116
+ * Localize search results based on user location (optional)
117
+ */
118
+ userLocation: webSearchLocationSchema.optional()
64
119
  }).optional()
65
120
  });
66
121
 
67
122
  // src/anthropic-prepare-tools.ts
68
123
  var import_provider = require("@ai-sdk/provider");
124
+ function isWebSearchTool(tool) {
125
+ return typeof tool === "object" && tool !== null && "type" in tool && tool.type === "web_search_20250305";
126
+ }
69
127
  function prepareTools({
70
128
  tools,
71
129
  toolChoice
@@ -78,6 +136,10 @@ function prepareTools({
78
136
  }
79
137
  const anthropicTools2 = [];
80
138
  for (const tool of tools) {
139
+ if (isWebSearchTool(tool)) {
140
+ anthropicTools2.push(tool);
141
+ continue;
142
+ }
81
143
  switch (tool.type) {
82
144
  case "function":
83
145
  anthropicTools2.push({
@@ -196,7 +258,7 @@ async function convertToAnthropicMessagesPrompt({
196
258
  sendReasoning,
197
259
  warnings
198
260
  }) {
199
- var _a, _b, _c;
261
+ var _a, _b, _c, _d;
200
262
  const betas = /* @__PURE__ */ new Set();
201
263
  const blocks = groupIntoBlocks(prompt);
202
264
  let system = void 0;
@@ -207,6 +269,26 @@ async function convertToAnthropicMessagesPrompt({
207
269
  const cacheControlValue = (_a2 = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a2 : anthropic2 == null ? void 0 : anthropic2.cache_control;
208
270
  return cacheControlValue;
209
271
  }
272
+ async function shouldEnableCitations(providerMetadata) {
273
+ var _a2, _b2;
274
+ const anthropicOptions = await (0, import_provider_utils2.parseProviderOptions)({
275
+ provider: "anthropic",
276
+ providerOptions: providerMetadata,
277
+ schema: anthropicFilePartProviderOptions
278
+ });
279
+ return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;
280
+ }
281
+ async function getDocumentMetadata(providerMetadata) {
282
+ const anthropicOptions = await (0, import_provider_utils2.parseProviderOptions)({
283
+ provider: "anthropic",
284
+ providerOptions: providerMetadata,
285
+ schema: anthropicFilePartProviderOptions
286
+ });
287
+ return {
288
+ title: anthropicOptions == null ? void 0 : anthropicOptions.title,
289
+ context: anthropicOptions == null ? void 0 : anthropicOptions.context
290
+ };
291
+ }
210
292
  for (let i = 0; i < blocks.length; i++) {
211
293
  const block = blocks[i];
212
294
  const isLastBlock = i === blocks.length - 1;
@@ -260,6 +342,12 @@ async function convertToAnthropicMessagesPrompt({
260
342
  });
261
343
  } else if (part.mediaType === "application/pdf") {
262
344
  betas.add("pdfs-2024-09-25");
345
+ const enableCitations = await shouldEnableCitations(
346
+ part.providerOptions
347
+ );
348
+ const metadata = await getDocumentMetadata(
349
+ part.providerOptions
350
+ );
263
351
  anthropicContent.push({
264
352
  type: "document",
265
353
  source: part.data instanceof URL ? {
@@ -270,6 +358,11 @@ async function convertToAnthropicMessagesPrompt({
270
358
  media_type: "application/pdf",
271
359
  data: (0, import_provider_utils2.convertToBase64)(part.data)
272
360
  },
361
+ title: (_b = metadata.title) != null ? _b : part.filename,
362
+ ...metadata.context && { context: metadata.context },
363
+ ...enableCitations && {
364
+ citations: { enabled: true }
365
+ },
273
366
  cache_control: cacheControl
274
367
  });
275
368
  } else {
@@ -287,7 +380,7 @@ async function convertToAnthropicMessagesPrompt({
287
380
  for (let i2 = 0; i2 < content.length; i2++) {
288
381
  const part = content[i2];
289
382
  const isLastPart = i2 === content.length - 1;
290
- const cacheControl = (_b = getCacheControl(part.providerOptions)) != null ? _b : isLastPart ? getCacheControl(message.providerOptions) : void 0;
383
+ const cacheControl = (_c = getCacheControl(part.providerOptions)) != null ? _c : isLastPart ? getCacheControl(message.providerOptions) : void 0;
291
384
  const toolResultContent = part.content != null ? part.content.map((part2) => {
292
385
  var _a2;
293
386
  switch (part2.type) {
@@ -337,7 +430,7 @@ async function convertToAnthropicMessagesPrompt({
337
430
  for (let k = 0; k < content.length; k++) {
338
431
  const part = content[k];
339
432
  const isLastContentPart = k === content.length - 1;
340
- const cacheControl = (_c = getCacheControl(part.providerOptions)) != null ? _c : isLastContentPart ? getCacheControl(message.providerOptions) : void 0;
433
+ const cacheControl = (_d = getCacheControl(part.providerOptions)) != null ? _d : isLastContentPart ? getCacheControl(message.providerOptions) : void 0;
341
434
  switch (part.type) {
342
435
  case "text": {
343
436
  anthropicContent.push({
@@ -468,13 +561,16 @@ function groupIntoBlocks(prompt) {
468
561
  }
469
562
 
470
563
  // src/map-anthropic-stop-reason.ts
471
- function mapAnthropicStopReason(finishReason) {
564
+ function mapAnthropicStopReason({
565
+ finishReason,
566
+ isJsonResponseFromTool
567
+ }) {
472
568
  switch (finishReason) {
473
569
  case "end_turn":
474
570
  case "stop_sequence":
475
571
  return "stop";
476
572
  case "tool_use":
477
- return "tool-calls";
573
+ return isJsonResponseFromTool ? "stop" : "tool-calls";
478
574
  case "max_tokens":
479
575
  return "length";
480
576
  default:
@@ -483,11 +579,47 @@ function mapAnthropicStopReason(finishReason) {
483
579
  }
484
580
 
485
581
  // src/anthropic-messages-language-model.ts
582
+ function processPageLocationCitation(citation, citationDocuments, generateId3, onSource) {
583
+ if (citation.type === "page_location") {
584
+ const source = createCitationSource(
585
+ citation,
586
+ citationDocuments,
587
+ generateId3
588
+ );
589
+ if (source) {
590
+ onSource(source);
591
+ }
592
+ }
593
+ }
594
+ function createCitationSource(citation, citationDocuments, generateId3) {
595
+ var _a;
596
+ const documentInfo = citationDocuments[citation.document_index];
597
+ if (!documentInfo) {
598
+ return null;
599
+ }
600
+ return {
601
+ type: "source",
602
+ sourceType: "document",
603
+ id: generateId3(),
604
+ mediaType: documentInfo.mediaType,
605
+ title: (_a = citation.document_title) != null ? _a : documentInfo.title,
606
+ filename: documentInfo.filename,
607
+ providerMetadata: {
608
+ anthropic: {
609
+ citedText: citation.cited_text,
610
+ startPageNumber: citation.start_page_number,
611
+ endPageNumber: citation.end_page_number
612
+ }
613
+ }
614
+ };
615
+ }
486
616
  var AnthropicMessagesLanguageModel = class {
487
617
  constructor(modelId, config) {
488
618
  this.specificationVersion = "v2";
619
+ var _a;
489
620
  this.modelId = modelId;
490
621
  this.config = config;
622
+ this.generateId = (_a = config.generateId) != null ? _a : import_provider_utils3.generateId;
491
623
  }
492
624
  supportsUrl(url) {
493
625
  return url.protocol === "https:";
@@ -535,13 +667,27 @@ var AnthropicMessagesLanguageModel = class {
535
667
  setting: "seed"
536
668
  });
537
669
  }
538
- if (responseFormat != null && responseFormat.type !== "text") {
539
- warnings.push({
540
- type: "unsupported-setting",
541
- setting: "responseFormat",
542
- details: "JSON response format is not supported."
543
- });
670
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
671
+ if (responseFormat.schema == null) {
672
+ warnings.push({
673
+ type: "unsupported-setting",
674
+ setting: "responseFormat",
675
+ details: "JSON response format requires a schema. The response format is ignored."
676
+ });
677
+ } else if (tools != null) {
678
+ warnings.push({
679
+ type: "unsupported-setting",
680
+ setting: "tools",
681
+ details: "JSON response format does not support tools. The provided tools are ignored."
682
+ });
683
+ }
544
684
  }
685
+ const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null ? {
686
+ type: "function",
687
+ name: "json",
688
+ description: "Respond with a JSON object.",
689
+ parameters: responseFormat.schema
690
+ } : void 0;
545
691
  const anthropicOptions = await (0, import_provider_utils3.parseProviderOptions)({
546
692
  provider: "anthropic",
547
693
  providerOptions,
@@ -603,12 +749,38 @@ var AnthropicMessagesLanguageModel = class {
603
749
  }
604
750
  baseArgs.max_tokens = maxOutputTokens + thinkingBudget;
605
751
  }
752
+ let modifiedTools = tools;
753
+ let modifiedToolChoice = toolChoice;
754
+ if (anthropicOptions == null ? void 0 : anthropicOptions.webSearch) {
755
+ const webSearchTool = {
756
+ type: "web_search_20250305",
757
+ name: "web_search",
758
+ max_uses: anthropicOptions.webSearch.maxUses,
759
+ allowed_domains: anthropicOptions.webSearch.allowedDomains,
760
+ blocked_domains: anthropicOptions.webSearch.blockedDomains,
761
+ ...anthropicOptions.webSearch.userLocation && {
762
+ user_location: {
763
+ type: anthropicOptions.webSearch.userLocation.type,
764
+ country: anthropicOptions.webSearch.userLocation.country,
765
+ city: anthropicOptions.webSearch.userLocation.city,
766
+ region: anthropicOptions.webSearch.userLocation.region,
767
+ timezone: anthropicOptions.webSearch.userLocation.timezone
768
+ }
769
+ }
770
+ };
771
+ modifiedTools = tools ? [...tools, webSearchTool] : [webSearchTool];
772
+ }
606
773
  const {
607
774
  tools: anthropicTools2,
608
775
  toolChoice: anthropicToolChoice,
609
776
  toolWarnings,
610
777
  betas: toolsBetas
611
- } = prepareTools({ tools, toolChoice });
778
+ } = prepareTools(
779
+ jsonResponseTool != null ? {
780
+ tools: [jsonResponseTool],
781
+ toolChoice: { type: "tool", toolName: jsonResponseTool.name }
782
+ } : { tools: modifiedTools, toolChoice: modifiedToolChoice }
783
+ );
612
784
  return {
613
785
  args: {
614
786
  ...baseArgs,
@@ -616,7 +788,8 @@ var AnthropicMessagesLanguageModel = class {
616
788
  tool_choice: anthropicToolChoice
617
789
  },
618
790
  warnings: [...warnings, ...toolWarnings],
619
- betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas])
791
+ betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas]),
792
+ jsonResponseTool
620
793
  };
621
794
  }
622
795
  async getHeaders({
@@ -637,9 +810,29 @@ var AnthropicMessagesLanguageModel = class {
637
810
  var _a, _b, _c;
638
811
  return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
639
812
  }
813
+ extractCitationDocuments(prompt) {
814
+ const isCitationEnabled = (part) => {
815
+ var _a, _b;
816
+ const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;
817
+ const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;
818
+ return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;
819
+ };
820
+ return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(
821
+ (part) => part.type === "file" && part.mediaType === "application/pdf" && isCitationEnabled(part)
822
+ ).map((part) => {
823
+ var _a;
824
+ const filePart = part;
825
+ return {
826
+ title: (_a = filePart.filename) != null ? _a : "Untitled Document",
827
+ filename: filePart.filename,
828
+ mediaType: filePart.mediaType
829
+ };
830
+ });
831
+ }
640
832
  async doGenerate(options) {
641
- var _a, _b, _c, _d;
642
- const { args, warnings, betas } = await this.getArgs(options);
833
+ var _a, _b, _c, _d, _e;
834
+ const { args, warnings, betas, jsonResponseTool } = await this.getArgs(options);
835
+ const citationDocuments = this.extractCitationDocuments(options.prompt);
643
836
  const {
644
837
  responseHeaders,
645
838
  value: response,
@@ -659,7 +852,19 @@ var AnthropicMessagesLanguageModel = class {
659
852
  for (const part of response.content) {
660
853
  switch (part.type) {
661
854
  case "text": {
662
- content.push({ type: "text", text: part.text });
855
+ if (jsonResponseTool == null) {
856
+ content.push({ type: "text", text: part.text });
857
+ if (part.citations) {
858
+ for (const citation of part.citations) {
859
+ processPageLocationCitation(
860
+ citation,
861
+ citationDocuments,
862
+ this.generateId,
863
+ (source) => content.push(source)
864
+ );
865
+ }
866
+ }
867
+ }
663
868
  break;
664
869
  }
665
870
  case "thinking": {
@@ -687,43 +892,85 @@ var AnthropicMessagesLanguageModel = class {
687
892
  break;
688
893
  }
689
894
  case "tool_use": {
690
- content.push({
691
- type: "tool-call",
692
- toolCallType: "function",
693
- toolCallId: part.id,
694
- toolName: part.name,
695
- args: JSON.stringify(part.input)
696
- });
895
+ content.push(
896
+ // when a json response tool is used, the tool call becomes the text:
897
+ jsonResponseTool != null ? {
898
+ type: "text",
899
+ text: JSON.stringify(part.input)
900
+ } : {
901
+ type: "tool-call",
902
+ toolCallType: "function",
903
+ toolCallId: part.id,
904
+ toolName: part.name,
905
+ args: JSON.stringify(part.input)
906
+ }
907
+ );
908
+ break;
909
+ }
910
+ case "server_tool_use": {
911
+ continue;
912
+ }
913
+ case "web_search_tool_result": {
914
+ if (Array.isArray(part.content)) {
915
+ for (const result of part.content) {
916
+ if (result.type === "web_search_result") {
917
+ content.push({
918
+ type: "source",
919
+ sourceType: "url",
920
+ id: this.generateId(),
921
+ url: result.url,
922
+ title: result.title,
923
+ providerMetadata: {
924
+ anthropic: {
925
+ encryptedContent: result.encrypted_content,
926
+ pageAge: (_a = result.page_age) != null ? _a : null
927
+ }
928
+ }
929
+ });
930
+ }
931
+ }
932
+ } else if (part.content.type === "web_search_tool_result_error") {
933
+ throw new import_provider3.APICallError({
934
+ message: `Web search failed: ${part.content.error_code}`,
935
+ url: "web_search_api",
936
+ requestBodyValues: { tool_use_id: part.tool_use_id },
937
+ data: { error_code: part.content.error_code }
938
+ });
939
+ }
697
940
  break;
698
941
  }
699
942
  }
700
943
  }
701
944
  return {
702
945
  content,
703
- finishReason: mapAnthropicStopReason(response.stop_reason),
946
+ finishReason: mapAnthropicStopReason({
947
+ finishReason: response.stop_reason,
948
+ isJsonResponseFromTool: jsonResponseTool != null
949
+ }),
704
950
  usage: {
705
951
  inputTokens: response.usage.input_tokens,
706
952
  outputTokens: response.usage.output_tokens,
707
953
  totalTokens: response.usage.input_tokens + response.usage.output_tokens,
708
- cachedInputTokens: (_a = response.usage.cache_read_input_tokens) != null ? _a : void 0
954
+ cachedInputTokens: (_b = response.usage.cache_read_input_tokens) != null ? _b : void 0
709
955
  },
710
956
  request: { body: args },
711
957
  response: {
712
- id: (_b = response.id) != null ? _b : void 0,
713
- modelId: (_c = response.model) != null ? _c : void 0,
958
+ id: (_c = response.id) != null ? _c : void 0,
959
+ modelId: (_d = response.model) != null ? _d : void 0,
714
960
  headers: responseHeaders,
715
961
  body: rawResponse
716
962
  },
717
963
  warnings,
718
964
  providerMetadata: {
719
965
  anthropic: {
720
- cacheCreationInputTokens: (_d = response.usage.cache_creation_input_tokens) != null ? _d : null
966
+ cacheCreationInputTokens: (_e = response.usage.cache_creation_input_tokens) != null ? _e : null
721
967
  }
722
968
  }
723
969
  };
724
970
  }
725
971
  async doStream(options) {
726
- const { args, warnings, betas } = await this.getArgs(options);
972
+ const { args, warnings, betas, jsonResponseTool } = await this.getArgs(options);
973
+ const citationDocuments = this.extractCitationDocuments(options.prompt);
727
974
  const body = { ...args, stream: true };
728
975
  const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
729
976
  url: this.buildRequestUrl(true),
@@ -745,6 +992,8 @@ var AnthropicMessagesLanguageModel = class {
745
992
  const toolCallContentBlocks = {};
746
993
  let providerMetadata = void 0;
747
994
  let blockType = void 0;
995
+ const config = this.config;
996
+ const generateId3 = this.generateId;
748
997
  return {
749
998
  stream: response.pipeThrough(
750
999
  new TransformStream({
@@ -752,7 +1001,7 @@ var AnthropicMessagesLanguageModel = class {
752
1001
  controller.enqueue({ type: "stream-start", warnings });
753
1002
  },
754
1003
  transform(chunk, controller) {
755
- var _a, _b, _c, _d, _e, _f;
1004
+ var _a, _b, _c, _d, _e, _f, _g;
756
1005
  if (!chunk.success) {
757
1006
  controller.enqueue({ type: "error", error: chunk.error });
758
1007
  return;
@@ -791,6 +1040,40 @@ var AnthropicMessagesLanguageModel = class {
791
1040
  };
792
1041
  return;
793
1042
  }
1043
+ case "server_tool_use": {
1044
+ return;
1045
+ }
1046
+ case "web_search_tool_result": {
1047
+ if (Array.isArray(value.content_block.content)) {
1048
+ for (const result of value.content_block.content) {
1049
+ if (result.type === "web_search_result") {
1050
+ controller.enqueue({
1051
+ type: "source",
1052
+ sourceType: "url",
1053
+ id: generateId3(),
1054
+ url: result.url,
1055
+ title: result.title,
1056
+ providerMetadata: {
1057
+ anthropic: {
1058
+ encryptedContent: result.encrypted_content,
1059
+ pageAge: (_a = result.page_age) != null ? _a : null
1060
+ }
1061
+ }
1062
+ });
1063
+ }
1064
+ }
1065
+ } else if (value.content_block.content.type === "web_search_tool_result_error") {
1066
+ controller.enqueue({
1067
+ type: "error",
1068
+ error: {
1069
+ type: "web-search-error",
1070
+ message: `Web search failed: ${value.content_block.content.error_code}`,
1071
+ code: value.content_block.content.error_code
1072
+ }
1073
+ });
1074
+ }
1075
+ return;
1076
+ }
794
1077
  default: {
795
1078
  const _exhaustiveCheck = contentBlockType;
796
1079
  throw new Error(
@@ -802,13 +1085,15 @@ var AnthropicMessagesLanguageModel = class {
802
1085
  case "content_block_stop": {
803
1086
  if (toolCallContentBlocks[value.index] != null) {
804
1087
  const contentBlock = toolCallContentBlocks[value.index];
805
- controller.enqueue({
806
- type: "tool-call",
807
- toolCallType: "function",
808
- toolCallId: contentBlock.toolCallId,
809
- toolName: contentBlock.toolName,
810
- args: contentBlock.jsonText
811
- });
1088
+ if (jsonResponseTool == null) {
1089
+ controller.enqueue({
1090
+ type: "tool-call",
1091
+ toolCallType: "function",
1092
+ toolCallId: contentBlock.toolCallId,
1093
+ toolName: contentBlock.toolName,
1094
+ args: contentBlock.jsonText
1095
+ });
1096
+ }
812
1097
  delete toolCallContentBlocks[value.index];
813
1098
  }
814
1099
  blockType = void 0;
@@ -818,6 +1103,9 @@ var AnthropicMessagesLanguageModel = class {
818
1103
  const deltaType = value.delta.type;
819
1104
  switch (deltaType) {
820
1105
  case "text_delta": {
1106
+ if (jsonResponseTool != null) {
1107
+ return;
1108
+ }
821
1109
  controller.enqueue({
822
1110
  type: "text",
823
1111
  text: value.delta.text
@@ -848,16 +1136,34 @@ var AnthropicMessagesLanguageModel = class {
848
1136
  }
849
1137
  case "input_json_delta": {
850
1138
  const contentBlock = toolCallContentBlocks[value.index];
851
- controller.enqueue({
852
- type: "tool-call-delta",
853
- toolCallType: "function",
854
- toolCallId: contentBlock.toolCallId,
855
- toolName: contentBlock.toolName,
856
- argsTextDelta: value.delta.partial_json
857
- });
1139
+ if (!contentBlock) {
1140
+ return;
1141
+ }
1142
+ controller.enqueue(
1143
+ jsonResponseTool != null ? {
1144
+ type: "text",
1145
+ text: value.delta.partial_json
1146
+ } : {
1147
+ type: "tool-call-delta",
1148
+ toolCallType: "function",
1149
+ toolCallId: contentBlock.toolCallId,
1150
+ toolName: contentBlock.toolName,
1151
+ argsTextDelta: value.delta.partial_json
1152
+ }
1153
+ );
858
1154
  contentBlock.jsonText += value.delta.partial_json;
859
1155
  return;
860
1156
  }
1157
+ case "citations_delta": {
1158
+ const citation = value.delta.citation;
1159
+ processPageLocationCitation(
1160
+ citation,
1161
+ citationDocuments,
1162
+ generateId3,
1163
+ (source) => controller.enqueue(source)
1164
+ );
1165
+ return;
1166
+ }
861
1167
  default: {
862
1168
  const _exhaustiveCheck = deltaType;
863
1169
  throw new Error(
@@ -868,23 +1174,26 @@ var AnthropicMessagesLanguageModel = class {
868
1174
  }
869
1175
  case "message_start": {
870
1176
  usage.inputTokens = value.message.usage.input_tokens;
871
- usage.cachedInputTokens = (_a = value.message.usage.cache_read_input_tokens) != null ? _a : void 0;
1177
+ usage.cachedInputTokens = (_b = value.message.usage.cache_read_input_tokens) != null ? _b : void 0;
872
1178
  providerMetadata = {
873
1179
  anthropic: {
874
- cacheCreationInputTokens: (_b = value.message.usage.cache_creation_input_tokens) != null ? _b : null
1180
+ cacheCreationInputTokens: (_c = value.message.usage.cache_creation_input_tokens) != null ? _c : null
875
1181
  }
876
1182
  };
877
1183
  controller.enqueue({
878
1184
  type: "response-metadata",
879
- id: (_c = value.message.id) != null ? _c : void 0,
880
- modelId: (_d = value.message.model) != null ? _d : void 0
1185
+ id: (_d = value.message.id) != null ? _d : void 0,
1186
+ modelId: (_e = value.message.model) != null ? _e : void 0
881
1187
  });
882
1188
  return;
883
1189
  }
884
1190
  case "message_delta": {
885
1191
  usage.outputTokens = value.usage.output_tokens;
886
- usage.totalTokens = ((_e = usage.inputTokens) != null ? _e : 0) + ((_f = value.usage.output_tokens) != null ? _f : 0);
887
- finishReason = mapAnthropicStopReason(value.delta.stop_reason);
1192
+ usage.totalTokens = ((_f = usage.inputTokens) != null ? _f : 0) + ((_g = value.usage.output_tokens) != null ? _g : 0);
1193
+ finishReason = mapAnthropicStopReason({
1194
+ finishReason: value.delta.stop_reason,
1195
+ isJsonResponseFromTool: jsonResponseTool != null
1196
+ });
888
1197
  return;
889
1198
  }
890
1199
  case "message_stop": {
@@ -921,7 +1230,26 @@ var anthropicMessagesResponseSchema = import_zod3.z.object({
921
1230
  import_zod3.z.discriminatedUnion("type", [
922
1231
  import_zod3.z.object({
923
1232
  type: import_zod3.z.literal("text"),
924
- text: import_zod3.z.string()
1233
+ text: import_zod3.z.string(),
1234
+ citations: import_zod3.z.array(
1235
+ import_zod3.z.discriminatedUnion("type", [
1236
+ import_zod3.z.object({
1237
+ type: import_zod3.z.literal("web_search_result_location"),
1238
+ cited_text: import_zod3.z.string(),
1239
+ url: import_zod3.z.string(),
1240
+ title: import_zod3.z.string(),
1241
+ encrypted_index: import_zod3.z.string()
1242
+ }),
1243
+ import_zod3.z.object({
1244
+ type: import_zod3.z.literal("page_location"),
1245
+ cited_text: import_zod3.z.string(),
1246
+ document_index: import_zod3.z.number(),
1247
+ document_title: import_zod3.z.string().nullable(),
1248
+ start_page_number: import_zod3.z.number(),
1249
+ end_page_number: import_zod3.z.number()
1250
+ })
1251
+ ])
1252
+ ).optional()
925
1253
  }),
926
1254
  import_zod3.z.object({
927
1255
  type: import_zod3.z.literal("thinking"),
@@ -937,6 +1265,31 @@ var anthropicMessagesResponseSchema = import_zod3.z.object({
937
1265
  id: import_zod3.z.string(),
938
1266
  name: import_zod3.z.string(),
939
1267
  input: import_zod3.z.unknown()
1268
+ }),
1269
+ import_zod3.z.object({
1270
+ type: import_zod3.z.literal("server_tool_use"),
1271
+ id: import_zod3.z.string(),
1272
+ name: import_zod3.z.string(),
1273
+ input: import_zod3.z.record(import_zod3.z.unknown()).nullish()
1274
+ }),
1275
+ import_zod3.z.object({
1276
+ type: import_zod3.z.literal("web_search_tool_result"),
1277
+ tool_use_id: import_zod3.z.string(),
1278
+ content: import_zod3.z.union([
1279
+ import_zod3.z.array(
1280
+ import_zod3.z.object({
1281
+ type: import_zod3.z.literal("web_search_result"),
1282
+ url: import_zod3.z.string(),
1283
+ title: import_zod3.z.string(),
1284
+ encrypted_content: import_zod3.z.string(),
1285
+ page_age: import_zod3.z.string().nullish()
1286
+ })
1287
+ ),
1288
+ import_zod3.z.object({
1289
+ type: import_zod3.z.literal("web_search_tool_result_error"),
1290
+ error_code: import_zod3.z.string()
1291
+ })
1292
+ ])
940
1293
  })
941
1294
  ])
942
1295
  ),
@@ -945,7 +1298,10 @@ var anthropicMessagesResponseSchema = import_zod3.z.object({
945
1298
  input_tokens: import_zod3.z.number(),
946
1299
  output_tokens: import_zod3.z.number(),
947
1300
  cache_creation_input_tokens: import_zod3.z.number().nullish(),
948
- cache_read_input_tokens: import_zod3.z.number().nullish()
1301
+ cache_read_input_tokens: import_zod3.z.number().nullish(),
1302
+ server_tool_use: import_zod3.z.object({
1303
+ web_search_requests: import_zod3.z.number()
1304
+ }).nullish()
949
1305
  })
950
1306
  });
951
1307
  var anthropicMessagesChunkSchema = import_zod3.z.discriminatedUnion("type", [
@@ -982,6 +1338,31 @@ var anthropicMessagesChunkSchema = import_zod3.z.discriminatedUnion("type", [
982
1338
  import_zod3.z.object({
983
1339
  type: import_zod3.z.literal("redacted_thinking"),
984
1340
  data: import_zod3.z.string()
1341
+ }),
1342
+ import_zod3.z.object({
1343
+ type: import_zod3.z.literal("server_tool_use"),
1344
+ id: import_zod3.z.string(),
1345
+ name: import_zod3.z.string(),
1346
+ input: import_zod3.z.record(import_zod3.z.unknown()).nullish()
1347
+ }),
1348
+ import_zod3.z.object({
1349
+ type: import_zod3.z.literal("web_search_tool_result"),
1350
+ tool_use_id: import_zod3.z.string(),
1351
+ content: import_zod3.z.union([
1352
+ import_zod3.z.array(
1353
+ import_zod3.z.object({
1354
+ type: import_zod3.z.literal("web_search_result"),
1355
+ url: import_zod3.z.string(),
1356
+ title: import_zod3.z.string(),
1357
+ encrypted_content: import_zod3.z.string(),
1358
+ page_age: import_zod3.z.string().nullish()
1359
+ })
1360
+ ),
1361
+ import_zod3.z.object({
1362
+ type: import_zod3.z.literal("web_search_tool_result_error"),
1363
+ error_code: import_zod3.z.string()
1364
+ })
1365
+ ])
985
1366
  })
986
1367
  ])
987
1368
  }),
@@ -1004,6 +1385,26 @@ var anthropicMessagesChunkSchema = import_zod3.z.discriminatedUnion("type", [
1004
1385
  import_zod3.z.object({
1005
1386
  type: import_zod3.z.literal("signature_delta"),
1006
1387
  signature: import_zod3.z.string()
1388
+ }),
1389
+ import_zod3.z.object({
1390
+ type: import_zod3.z.literal("citations_delta"),
1391
+ citation: import_zod3.z.discriminatedUnion("type", [
1392
+ import_zod3.z.object({
1393
+ type: import_zod3.z.literal("web_search_result_location"),
1394
+ cited_text: import_zod3.z.string(),
1395
+ url: import_zod3.z.string(),
1396
+ title: import_zod3.z.string(),
1397
+ encrypted_index: import_zod3.z.string()
1398
+ }),
1399
+ import_zod3.z.object({
1400
+ type: import_zod3.z.literal("page_location"),
1401
+ cited_text: import_zod3.z.string(),
1402
+ document_index: import_zod3.z.number(),
1403
+ document_title: import_zod3.z.string().nullable(),
1404
+ start_page_number: import_zod3.z.number(),
1405
+ end_page_number: import_zod3.z.number()
1406
+ })
1407
+ ])
1007
1408
  })
1008
1409
  ])
1009
1410
  }),
@@ -1195,15 +1596,19 @@ function createAnthropic(options = {}) {
1195
1596
  }),
1196
1597
  ...options.headers
1197
1598
  });
1198
- const createChatModel = (modelId) => new AnthropicMessagesLanguageModel(modelId, {
1199
- provider: "anthropic.messages",
1200
- baseURL,
1201
- headers: getHeaders,
1202
- fetch: options.fetch,
1203
- supportedUrls: () => ({
1204
- "image/*": [/^https?:\/\/.*$/]
1205
- })
1206
- });
1599
+ const createChatModel = (modelId) => {
1600
+ var _a2;
1601
+ return new AnthropicMessagesLanguageModel(modelId, {
1602
+ provider: "anthropic.messages",
1603
+ baseURL,
1604
+ headers: getHeaders,
1605
+ fetch: options.fetch,
1606
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils4.generateId,
1607
+ supportedUrls: () => ({
1608
+ "image/*": [/^https?:\/\/.*$/]
1609
+ })
1610
+ });
1611
+ };
1207
1612
  const provider = function(modelId) {
1208
1613
  if (new.target) {
1209
1614
  throw new Error(