@ai-sdk/anthropic 3.0.138 → 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,
@@ -2498,6 +2527,32 @@ async function extractErrorValue(value) {
2498
2527
  }
2499
2528
  return {};
2500
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
+ }
2501
2556
  async function convertToAnthropicMessagesPrompt({
2502
2557
  prompt,
2503
2558
  sendReasoning,
@@ -2505,7 +2560,8 @@ async function convertToAnthropicMessagesPrompt({
2505
2560
  cacheControlValidator,
2506
2561
  toolNameMapping,
2507
2562
  toolsetNames = {},
2508
- convertMediaPart
2563
+ convertMediaPart,
2564
+ convertInlineTool
2509
2565
  }) {
2510
2566
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
2511
2567
  const betas = /* @__PURE__ */ new Set();
@@ -2542,6 +2598,7 @@ async function convertToAnthropicMessagesPrompt({
2542
2598
  case "system": {
2543
2599
  const systemMessages = [];
2544
2600
  let toolChangeCount = 0;
2601
+ let hasInlineToolDefinition = false;
2545
2602
  let hasMidConversationOptions = false;
2546
2603
  for (const { content: text, providerOptions } of block.messages) {
2547
2604
  const systemMessageOptions = await parseProviderOptions({
@@ -2564,6 +2621,40 @@ async function convertToAnthropicMessagesPrompt({
2564
2621
  });
2565
2622
  }
2566
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
+ }
2567
2658
  toolChangeCount++;
2568
2659
  content.push({
2569
2660
  type: toolChange.type,
@@ -2573,6 +2664,9 @@ async function convertToAnthropicMessagesPrompt({
2573
2664
  }
2574
2665
  });
2575
2666
  }
2667
+ if (content.length === 0 && clearAt == null && effort == null) {
2668
+ continue;
2669
+ }
2576
2670
  hasMidConversationOptions || (hasMidConversationOptions = clearAt != null || effort != null);
2577
2671
  systemMessages.push({
2578
2672
  role: "system",
@@ -2607,7 +2701,9 @@ async function convertToAnthropicMessagesPrompt({
2607
2701
  } else {
2608
2702
  messages.push(...systemMessages);
2609
2703
  betas.add("mid-conversation-system-2026-04-07");
2610
- if (toolChangeCount > 0) {
2704
+ if (hasInlineToolDefinition) {
2705
+ betas.add("inline-tools-2026-09-15");
2706
+ } else if (toolChangeCount > 0) {
2611
2707
  betas.add("mid-conversation-tool-changes-2026-07-01");
2612
2708
  }
2613
2709
  if (systemMessages.some((message) => message.clear_at != null)) {
@@ -4197,8 +4293,22 @@ var AnthropicMessagesLanguageModel = class {
4197
4293
  const cacheControlValidator = new CacheControlValidator(
4198
4294
  this.config.cacheControlProviderOptionsName
4199
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
+ );
4200
4303
  const toolNameMapping = createToolNameMapping({
4201
- 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
+ ],
4202
4312
  providerToolNames: {
4203
4313
  "anthropic.code_execution_20250522": "code_execution",
4204
4314
  "anthropic.code_execution_20250825": "code_execution",
@@ -4224,14 +4334,43 @@ var AnthropicMessagesLanguageModel = class {
4224
4334
  }
4225
4335
  });
4226
4336
  const toolsetNames = getAnthropicToolsetNames(tools);
4337
+ const inlineToolDefinitions = [];
4227
4338
  const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
4228
4339
  prompt,
4229
- sendReasoning: (_e = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _e : true,
4340
+ sendReasoning: (_f = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _f : true,
4230
4341
  warnings,
4231
4342
  cacheControlValidator,
4232
4343
  toolNameMapping,
4233
4344
  toolsetNames,
4234
- 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
+ }
4235
4374
  });
4236
4375
  if (rejectsThinkingDisabled && (anthropicOptions == null ? void 0 : anthropicOptions.thinking) != null) {
4237
4376
  const requestedThinking = anthropicOptions.thinking;
@@ -4341,7 +4480,7 @@ var AnthropicMessagesLanguageModel = class {
4341
4480
  ...(anthropicOptions == null ? void 0 : anthropicOptions.cacheControl) && {
4342
4481
  cache_control: anthropicOptions.cacheControl
4343
4482
  },
4344
- ...((_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 && {
4345
4484
  metadata: { user_id: anthropicOptions.metadata.userId }
4346
4485
  },
4347
4486
  // mcp servers:
@@ -4536,7 +4675,6 @@ var AnthropicMessagesLanguageModel = class {
4536
4675
  } else if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0) {
4537
4676
  betas.add("server-side-fallback-2026-06-01");
4538
4677
  }
4539
- const defaultEagerInputStreaming = stream && ((_g = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _g : true);
4540
4678
  const {
4541
4679
  tools: anthropicTools2,
4542
4680
  toolChoice: anthropicToolChoice,
@@ -4560,6 +4698,9 @@ var AnthropicMessagesLanguageModel = class {
4560
4698
  } : {
4561
4699
  tools: tools != null ? tools : [],
4562
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,
4563
4704
  disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
4564
4705
  cacheControlValidator,
4565
4706
  supportsStructuredOutput,
@@ -4568,6 +4709,31 @@ var AnthropicMessagesLanguageModel = class {
4568
4709
  rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
4569
4710
  }
4570
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
+ }
4571
4737
  const cacheWarnings = cacheControlValidator.getWarnings();
4572
4738
  return {
4573
4739
  args: {