@ai-sdk/anthropic 3.0.137 → 3.0.139

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.
@@ -1,6 +1,7 @@
1
1
  // src/anthropic-messages-language-model.ts
2
2
  import {
3
3
  APICallError,
4
+ InvalidArgumentError,
4
5
  InvalidResponseDataError
5
6
  } from "@ai-sdk/provider";
6
7
  import {
@@ -912,17 +913,43 @@ var anthropicSystemMessageProviderOptions = lazySchema3(
912
913
  * initial system prompt). A system message carrying tool changes must come
913
914
  * right before an assistant message or at the end of the messages.
914
915
  *
915
- * Tools referenced by a `tool_addition` must be declared in the `tools`
916
- * option (typically with `deferLoading: true` so they are not loaded until
917
- * the addition surfaces them). The required
918
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
916
+ * A `tool_addition` either references a tool by `toolName` or defines it
917
+ * by value with `tool`:
918
+ * - By reference: the tool must be declared in the `tools` option
919
+ * (typically with `deferLoading: true` so it is not loaded until the
920
+ * addition surfaces it). The required
921
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
922
+ * automatically.
923
+ * - By value: `tool` is a function or provider tool, in the same shape as
924
+ * an entry of the `tools` option. The tool does not need to be declared
925
+ * in `tools`, and defining a tool under an existing name replaces it
926
+ * from that point on. The required `inline-tools-2026-09-15` beta is
927
+ * added automatically.
928
+ *
929
+ * A `tool_removal` always references the tool by `toolName`.
919
930
  */
920
931
  toolChanges: z3.array(
921
- z3.discriminatedUnion("type", [
932
+ z3.union([
922
933
  z3.object({
923
934
  type: z3.literal("tool_addition"),
924
935
  toolName: z3.string()
925
936
  }),
937
+ z3.object({
938
+ type: z3.literal("tool_addition"),
939
+ tool: z3.union([
940
+ z3.looseObject({
941
+ type: z3.literal("function"),
942
+ name: z3.string(),
943
+ inputSchema: z3.record(z3.string(), z3.unknown())
944
+ }),
945
+ z3.looseObject({
946
+ type: z3.literal("provider"),
947
+ id: z3.string(),
948
+ name: z3.string(),
949
+ args: z3.record(z3.string(), z3.unknown())
950
+ })
951
+ ])
952
+ }),
926
953
  z3.object({
927
954
  type: z3.literal("tool_removal"),
928
955
  toolName: z3.string()
@@ -1650,6 +1677,7 @@ import { validateTypes } from "@ai-sdk/provider-utils";
1650
1677
  async function prepareTools({
1651
1678
  tools,
1652
1679
  toolChoice,
1680
+ hasInlineTools = false,
1653
1681
  disableParallelToolUse,
1654
1682
  cacheControlValidator,
1655
1683
  supportsStructuredOutput,
@@ -1662,11 +1690,11 @@ async function prepareTools({
1662
1690
  const toolWarnings = [];
1663
1691
  const betas = /* @__PURE__ */ new Set();
1664
1692
  const validator = cacheControlValidator || new CacheControlValidator();
1665
- if (tools == null) {
1693
+ if (tools == null && !hasInlineTools) {
1666
1694
  return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
1667
1695
  }
1668
1696
  const anthropicTools2 = [];
1669
- for (const tool of tools) {
1697
+ for (const tool of tools != null ? tools : []) {
1670
1698
  switch (tool.type) {
1671
1699
  case "function": {
1672
1700
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
@@ -1978,9 +2006,10 @@ async function prepareTools({
1978
2006
  }
1979
2007
  }
1980
2008
  }
2009
+ const declaredTools = tools == null ? void 0 : anthropicTools2;
1981
2010
  if (toolChoice == null) {
1982
2011
  return {
1983
- tools: anthropicTools2,
2012
+ tools: declaredTools,
1984
2013
  toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0,
1985
2014
  toolWarnings,
1986
2015
  betas
@@ -1990,7 +2019,7 @@ async function prepareTools({
1990
2019
  switch (type) {
1991
2020
  case "auto":
1992
2021
  return {
1993
- tools: anthropicTools2,
2022
+ tools: declaredTools,
1994
2023
  toolChoice: {
1995
2024
  type: "auto",
1996
2025
  disable_parallel_tool_use: disableParallelToolUse
@@ -2006,7 +2035,7 @@ async function prepareTools({
2006
2035
  details: `toolChoice 'required' is not supported with this model or thinking configuration. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made.`
2007
2036
  });
2008
2037
  return {
2009
- tools: anthropicTools2,
2038
+ tools: declaredTools,
2010
2039
  toolChoice: {
2011
2040
  type: "auto",
2012
2041
  disable_parallel_tool_use: disableParallelToolUse
@@ -2016,7 +2045,7 @@ async function prepareTools({
2016
2045
  };
2017
2046
  }
2018
2047
  return {
2019
- tools: anthropicTools2,
2048
+ tools: declaredTools,
2020
2049
  toolChoice: {
2021
2050
  type: "any",
2022
2051
  disable_parallel_tool_use: disableParallelToolUse
@@ -2026,7 +2055,7 @@ async function prepareTools({
2026
2055
  };
2027
2056
  case "none":
2028
2057
  return {
2029
- tools: anthropicTools2,
2058
+ tools: declaredTools,
2030
2059
  toolChoice: { type: "none" },
2031
2060
  toolWarnings,
2032
2061
  betas
@@ -2039,7 +2068,7 @@ async function prepareTools({
2039
2068
  details: `toolChoice 'tool' is not supported with this model or thinking configuration. Only the '${toolChoice.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`
2040
2069
  });
2041
2070
  return {
2042
- tools: anthropicTools2.filter(
2071
+ tools: declaredTools == null ? void 0 : declaredTools.filter(
2043
2072
  (tool) => "name" in tool && tool.name === toolChoice.toolName
2044
2073
  ),
2045
2074
  toolChoice: {
@@ -2051,7 +2080,7 @@ async function prepareTools({
2051
2080
  };
2052
2081
  }
2053
2082
  return {
2054
- tools: anthropicTools2,
2083
+ tools: declaredTools,
2055
2084
  toolChoice: {
2056
2085
  type: "tool",
2057
2086
  name: toolChoice.toolName,
@@ -2126,6 +2155,7 @@ import {
2126
2155
  UnsupportedFunctionalityError as UnsupportedFunctionalityError2
2127
2156
  } from "@ai-sdk/provider";
2128
2157
  import {
2158
+ stringifyWithBigIntAndCycles,
2129
2159
  convertBase64ToUint8Array,
2130
2160
  convertToBase64,
2131
2161
  parseProviderOptions,
@@ -2497,6 +2527,32 @@ async function extractErrorValue(value) {
2497
2527
  }
2498
2528
  return {};
2499
2529
  }
2530
+ function isComputerTool(tool) {
2531
+ return tool.type === "provider" && tool.id.startsWith("anthropic.computer_");
2532
+ }
2533
+ async function getInlineToolsFromPrompt(prompt) {
2534
+ var _a;
2535
+ const inlineTools = [];
2536
+ for (const message of prompt) {
2537
+ if (message.role !== "system" || message.providerOptions == null) {
2538
+ continue;
2539
+ }
2540
+ const options = await parseProviderOptions({
2541
+ provider: "anthropic",
2542
+ providerOptions: message.providerOptions,
2543
+ schema: anthropicSystemMessageProviderOptions
2544
+ });
2545
+ for (const toolChange of (_a = options == null ? void 0 : options.toolChanges) != null ? _a : []) {
2546
+ if ("tool" in toolChange) {
2547
+ const tool = toolChange.tool;
2548
+ if (!isComputerTool(tool)) {
2549
+ inlineTools.push(tool);
2550
+ }
2551
+ }
2552
+ }
2553
+ }
2554
+ return inlineTools;
2555
+ }
2500
2556
  async function convertToAnthropicMessagesPrompt({
2501
2557
  prompt,
2502
2558
  sendReasoning,
@@ -2504,7 +2560,8 @@ async function convertToAnthropicMessagesPrompt({
2504
2560
  cacheControlValidator,
2505
2561
  toolNameMapping,
2506
2562
  toolsetNames = {},
2507
- convertMediaPart
2563
+ convertMediaPart,
2564
+ convertInlineTool
2508
2565
  }) {
2509
2566
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
2510
2567
  const betas = /* @__PURE__ */ new Set();
@@ -2541,6 +2598,7 @@ async function convertToAnthropicMessagesPrompt({
2541
2598
  case "system": {
2542
2599
  const systemMessages = [];
2543
2600
  let toolChangeCount = 0;
2601
+ let hasInlineToolDefinition = false;
2544
2602
  let hasMidConversationOptions = false;
2545
2603
  for (const { content: text, providerOptions } of block.messages) {
2546
2604
  const systemMessageOptions = await parseProviderOptions({
@@ -2563,6 +2621,40 @@ async function convertToAnthropicMessagesPrompt({
2563
2621
  });
2564
2622
  }
2565
2623
  for (const toolChange of toolChanges) {
2624
+ if ("tool" in toolChange) {
2625
+ if (convertInlineTool == null) {
2626
+ throw new UnsupportedFunctionalityError2({
2627
+ functionality: "tool additions by value in mid-conversation tool changes"
2628
+ });
2629
+ }
2630
+ const tool = toolChange.tool;
2631
+ if (isComputerTool(tool)) {
2632
+ warnings.push({
2633
+ type: "other",
2634
+ message: `The tool '${tool.name}' cannot be added by value in a tool change. Declare it in the tools option and add it by reference with toolName. The tool change has been ignored.`
2635
+ });
2636
+ continue;
2637
+ }
2638
+ const {
2639
+ definition,
2640
+ warnings: toolWarnings,
2641
+ betas: toolBetas
2642
+ } = await convertInlineTool(tool);
2643
+ warnings.push(...toolWarnings);
2644
+ for (const beta of toolBetas) {
2645
+ betas.add(beta);
2646
+ }
2647
+ if (definition == null) {
2648
+ continue;
2649
+ }
2650
+ content.push({
2651
+ type: "tool_addition",
2652
+ tool: { type: "tool_definition", definition }
2653
+ });
2654
+ toolChangeCount++;
2655
+ hasInlineToolDefinition = true;
2656
+ continue;
2657
+ }
2566
2658
  toolChangeCount++;
2567
2659
  content.push({
2568
2660
  type: toolChange.type,
@@ -2572,6 +2664,9 @@ async function convertToAnthropicMessagesPrompt({
2572
2664
  }
2573
2665
  });
2574
2666
  }
2667
+ if (content.length === 0 && clearAt == null && effort == null) {
2668
+ continue;
2669
+ }
2575
2670
  hasMidConversationOptions || (hasMidConversationOptions = clearAt != null || effort != null);
2576
2671
  systemMessages.push({
2577
2672
  role: "system",
@@ -2606,7 +2701,9 @@ async function convertToAnthropicMessagesPrompt({
2606
2701
  } else {
2607
2702
  messages.push(...systemMessages);
2608
2703
  betas.add("mid-conversation-system-2026-04-07");
2609
- if (toolChangeCount > 0) {
2704
+ if (hasInlineToolDefinition) {
2705
+ betas.add("inline-tools-2026-09-15");
2706
+ } else if (toolChangeCount > 0) {
2610
2707
  betas.add("mid-conversation-tool-changes-2026-07-01");
2611
2708
  }
2612
2709
  if (systemMessages.some((message) => message.clear_at != null)) {
@@ -2840,7 +2937,7 @@ async function convertToAnthropicMessagesPrompt({
2840
2937
  case "json":
2841
2938
  case "error-json":
2842
2939
  default:
2843
- contentValue = JSON.stringify(output.value);
2940
+ contentValue = stringifyWithBigIntAndCycles(output.value);
2844
2941
  break;
2845
2942
  }
2846
2943
  const toolsetName = getAnthropicToolsetName({
@@ -3078,7 +3175,7 @@ async function convertToAnthropicMessagesPrompt({
3078
3175
  type: "tool_use",
3079
3176
  id: part.toolCallId,
3080
3177
  name: part.toolName,
3081
- input: part.input,
3178
+ input: parseToolCallInput(part.input),
3082
3179
  ...caller && { caller },
3083
3180
  cache_control: cacheControl
3084
3181
  });
@@ -3563,6 +3660,18 @@ function getAnthropicCaller(providerOptions) {
3563
3660
  }
3564
3661
  return (caller == null ? void 0 : caller.type) === "direct" ? { type: "direct" } : void 0;
3565
3662
  }
3663
+ function parseToolCallInput(input) {
3664
+ if (typeof input === "string") {
3665
+ try {
3666
+ const parsed = secureJsonParse(input);
3667
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3668
+ return parsed;
3669
+ }
3670
+ } catch (e) {
3671
+ }
3672
+ }
3673
+ return input;
3674
+ }
3566
3675
 
3567
3676
  // src/map-anthropic-stop-reason.ts
3568
3677
  function mapAnthropicStopReason({
@@ -4155,9 +4264,10 @@ var AnthropicMessagesLanguageModel = class {
4155
4264
  }
4156
4265
  const isAnthropicModel = isKnownModel || this.modelId.includes("claude-");
4157
4266
  const supportsStructuredOutput = ((_b = this.config.supportsNativeStructuredOutput) != null ? _b : true) && modelSupportsStructuredOutput;
4267
+ const supportsResponseSchema = (responseFormat == null ? void 0 : responseFormat.type) !== "json" || responseFormat.schema == null || supportsNativeStructuredOutputSchema(responseFormat.schema);
4158
4268
  const supportsStrictTools = ((_c = this.config.supportsStrictTools) != null ? _c : true) && modelSupportsStructuredOutput;
4159
4269
  const structureOutputMode = (_d = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _d : "auto";
4160
- let useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput;
4270
+ let useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput && supportsResponseSchema;
4161
4271
  if (!useStructuredOutput && rejectsForcedToolUse && modelSupportsStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && supportsNativeStructuredOutputSchema(responseFormat.schema)) {
4162
4272
  warnings.push({
4163
4273
  type: "unsupported",
@@ -4183,8 +4293,22 @@ var AnthropicMessagesLanguageModel = class {
4183
4293
  const cacheControlValidator = new CacheControlValidator(
4184
4294
  this.config.cacheControlProviderOptionsName
4185
4295
  );
4296
+ const defaultEagerInputStreaming = stream && ((_e = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _e : true);
4297
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
4298
+ const declaredFunctionToolNames = new Set(
4299
+ (tools != null ? tools : []).flatMap(
4300
+ (tool) => tool.type === "function" ? [tool.name] : []
4301
+ )
4302
+ );
4186
4303
  const toolNameMapping = createToolNameMapping({
4187
- tools,
4304
+ // later entries win when provider tool names collide, so the declared
4305
+ // tools go last and an inline tool cannot take over their mapping:
4306
+ tools: [
4307
+ ...inlineTools.filter(
4308
+ (tool) => !(tool.type === "provider" && declaredFunctionToolNames.has(tool.name))
4309
+ ),
4310
+ ...tools != null ? tools : []
4311
+ ],
4188
4312
  providerToolNames: {
4189
4313
  "anthropic.code_execution_20250522": "code_execution",
4190
4314
  "anthropic.code_execution_20250825": "code_execution",
@@ -4210,14 +4334,43 @@ var AnthropicMessagesLanguageModel = class {
4210
4334
  }
4211
4335
  });
4212
4336
  const toolsetNames = getAnthropicToolsetNames(tools);
4337
+ const inlineToolDefinitions = [];
4213
4338
  const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
4214
4339
  prompt,
4215
- sendReasoning: (_e = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _e : true,
4340
+ sendReasoning: (_f = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _f : true,
4216
4341
  warnings,
4217
4342
  cacheControlValidator,
4218
4343
  toolNameMapping,
4219
4344
  toolsetNames,
4220
- convertMediaPart: this.config.convertMediaPart
4345
+ convertMediaPart: this.config.convertMediaPart,
4346
+ convertInlineTool: async (tool) => {
4347
+ const {
4348
+ tools: definitions,
4349
+ toolWarnings: toolWarnings2,
4350
+ betas: betas2
4351
+ } = await prepareTools({
4352
+ tools: [tool],
4353
+ toolChoice: void 0,
4354
+ cacheControlValidator,
4355
+ supportsStructuredOutput,
4356
+ supportsStrictTools
4357
+ // no stream-dependent defaults (eager input streaming): the
4358
+ // definition is replayed on every request and has to stay
4359
+ // identical between streaming and non-streaming calls to keep
4360
+ // the cache.
4361
+ });
4362
+ if ((definitions == null ? void 0 : definitions[0]) != null) {
4363
+ inlineToolDefinitions.push({
4364
+ sdkName: tool.name,
4365
+ definition: definitions[0]
4366
+ });
4367
+ }
4368
+ return {
4369
+ definition: definitions == null ? void 0 : definitions[0],
4370
+ warnings: toolWarnings2,
4371
+ betas: betas2
4372
+ };
4373
+ }
4221
4374
  });
4222
4375
  if (rejectsThinkingDisabled && (anthropicOptions == null ? void 0 : anthropicOptions.thinking) != null) {
4223
4376
  const requestedThinking = anthropicOptions.thinking;
@@ -4327,7 +4480,7 @@ var AnthropicMessagesLanguageModel = class {
4327
4480
  ...(anthropicOptions == null ? void 0 : anthropicOptions.cacheControl) && {
4328
4481
  cache_control: anthropicOptions.cacheControl
4329
4482
  },
4330
- ...((_f = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _f.userId) != null && {
4483
+ ...((_g = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _g.userId) != null && {
4331
4484
  metadata: { user_id: anthropicOptions.metadata.userId }
4332
4485
  },
4333
4486
  // mcp servers:
@@ -4522,7 +4675,6 @@ var AnthropicMessagesLanguageModel = class {
4522
4675
  } else if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0) {
4523
4676
  betas.add("server-side-fallback-2026-06-01");
4524
4677
  }
4525
- const defaultEagerInputStreaming = stream && ((_g = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _g : true);
4526
4678
  const {
4527
4679
  tools: anthropicTools2,
4528
4680
  toolChoice: anthropicToolChoice,
@@ -4530,7 +4682,12 @@ var AnthropicMessagesLanguageModel = class {
4530
4682
  betas: toolsBetas
4531
4683
  } = await prepareTools(
4532
4684
  jsonResponseTool != null ? {
4533
- tools: [...tools != null ? tools : [], jsonResponseTool],
4685
+ tools: [
4686
+ ...(tools != null ? tools : []).filter(
4687
+ (tool) => (toolChoice == null ? void 0 : toolChoice.type) !== "none" && ((toolChoice == null ? void 0 : toolChoice.type) !== "tool" || tool.name === toolChoice.toolName)
4688
+ ),
4689
+ jsonResponseTool
4690
+ ],
4534
4691
  toolChoice: { type: "required" },
4535
4692
  disableParallelToolUse: true,
4536
4693
  cacheControlValidator,
@@ -4541,6 +4698,9 @@ var AnthropicMessagesLanguageModel = class {
4541
4698
  } : {
4542
4699
  tools: tools != null ? tools : [],
4543
4700
  toolChoice,
4701
+ // tool changes can add tools when `tools` is empty, so the tool
4702
+ // choice and parallel tool use settings still apply:
4703
+ hasInlineTools: inlineTools.length > 0,
4544
4704
  disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
4545
4705
  cacheControlValidator,
4546
4706
  supportsStructuredOutput,
@@ -4549,6 +4709,31 @@ var AnthropicMessagesLanguageModel = class {
4549
4709
  rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
4550
4710
  }
4551
4711
  );
4712
+ if ((toolChoice == null ? void 0 : toolChoice.type) === "tool" && ((anthropicToolChoice == null ? void 0 : anthropicToolChoice.type) === "auto" || jsonResponseTool != null) || (toolChoice == null ? void 0 : toolChoice.type) === "none" && jsonResponseTool != null) {
4713
+ const emittedInlineDefinitions = new Set(
4714
+ messagesPrompt.messages.flatMap(
4715
+ (message) => message.role === "system" ? message.content.flatMap(
4716
+ (part) => part.type === "tool_addition" && part.tool.type === "tool_definition" ? [part.tool.definition] : []
4717
+ ) : []
4718
+ )
4719
+ );
4720
+ const selectedSdkName = toolChoice.type === "tool" ? toolChoice.toolName : void 0;
4721
+ const selectedTool = tools == null ? void 0 : tools.find((tool) => tool.name === selectedSdkName);
4722
+ const selectedProviderName = jsonResponseTool != null && selectedSdkName != null && (selectedTool == null ? void 0 : selectedTool.type) !== "function" ? toolNameMapping.toProviderToolName(selectedSdkName) : selectedSdkName;
4723
+ const conflictingTool = inlineToolDefinitions.find(
4724
+ ({ sdkName, definition }) => emittedInlineDefinitions.has(definition) && (toolChoice.type === "none" || // The JSON-tool path filters application tools by SDK name before
4725
+ // conversion; the forced-choice fallback filters by provider name.
4726
+ jsonResponseTool != null && sdkName !== selectedSdkName || !("name" in definition) || definition.name !== selectedProviderName)
4727
+ );
4728
+ if (conflictingTool != null) {
4729
+ const toolName = "name" in conflictingTool.definition ? conflictingTool.definition.name : conflictingTool.definition.type;
4730
+ const choice = toolChoice.type === "tool" ? `named tool choice '${toolChoice.toolName}'` : `tool choice 'none'`;
4731
+ throw new InvalidArgumentError({
4732
+ argument: "toolChoice",
4733
+ message: `Inline tool '${toolName}' conflicts with ${choice}. Inline definitions must respect the tool choice when forced tool use falls back or the JSON response tool is used.`
4734
+ });
4735
+ }
4736
+ }
4552
4737
  const cacheWarnings = cacheControlValidator.getWarnings();
4553
4738
  return {
4554
4739
  args: {
@@ -6988,6 +7173,7 @@ export {
6988
7173
  anthropicTools,
6989
7174
  getModelCapabilities,
6990
7175
  prepareTools,
6991
- sanitizeJsonSchema
7176
+ sanitizeJsonSchema,
7177
+ supportsNativeStructuredOutputSchema
6992
7178
  };
6993
7179
  //# sourceMappingURL=index.mjs.map