@ai-sdk/anthropic 3.0.138 → 3.0.140

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.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/anthropic-provider.ts
2
2
  import {
3
- InvalidArgumentError,
3
+ InvalidArgumentError as InvalidArgumentError2,
4
4
  NoSuchModelError
5
5
  } from "@ai-sdk/provider";
6
6
  import {
@@ -12,11 +12,12 @@ import {
12
12
  } from "@ai-sdk/provider-utils";
13
13
 
14
14
  // src/version.ts
15
- var VERSION = true ? "3.0.138" : "0.0.0-test";
15
+ var VERSION = true ? "3.0.140" : "0.0.0-test";
16
16
 
17
17
  // src/anthropic-messages-language-model.ts
18
18
  import {
19
19
  APICallError,
20
+ InvalidArgumentError,
20
21
  InvalidResponseDataError
21
22
  } from "@ai-sdk/provider";
22
23
  import {
@@ -928,17 +929,43 @@ var anthropicSystemMessageProviderOptions = lazySchema3(
928
929
  * initial system prompt). A system message carrying tool changes must come
929
930
  * right before an assistant message or at the end of the messages.
930
931
  *
931
- * Tools referenced by a `tool_addition` must be declared in the `tools`
932
- * option (typically with `deferLoading: true` so they are not loaded until
933
- * the addition surfaces them). The required
934
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
932
+ * A `tool_addition` either references a tool by `toolName` or defines it
933
+ * by value with `tool`:
934
+ * - By reference: the tool must be declared in the `tools` option
935
+ * (typically with `deferLoading: true` so it is not loaded until the
936
+ * addition surfaces it). The required
937
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
938
+ * automatically.
939
+ * - By value: `tool` is a function or provider tool, in the same shape as
940
+ * an entry of the `tools` option. The tool does not need to be declared
941
+ * in `tools`, and defining a tool under an existing name replaces it
942
+ * from that point on. The required `inline-tools-2026-09-15` beta is
943
+ * added automatically.
944
+ *
945
+ * A `tool_removal` always references the tool by `toolName`.
935
946
  */
936
947
  toolChanges: z3.array(
937
- z3.discriminatedUnion("type", [
948
+ z3.union([
938
949
  z3.object({
939
950
  type: z3.literal("tool_addition"),
940
951
  toolName: z3.string()
941
952
  }),
953
+ z3.object({
954
+ type: z3.literal("tool_addition"),
955
+ tool: z3.union([
956
+ z3.looseObject({
957
+ type: z3.literal("function"),
958
+ name: z3.string(),
959
+ inputSchema: z3.record(z3.string(), z3.unknown())
960
+ }),
961
+ z3.looseObject({
962
+ type: z3.literal("provider"),
963
+ id: z3.string(),
964
+ name: z3.string(),
965
+ args: z3.record(z3.string(), z3.unknown())
966
+ })
967
+ ])
968
+ }),
942
969
  z3.object({
943
970
  type: z3.literal("tool_removal"),
944
971
  toolName: z3.string()
@@ -1666,6 +1693,7 @@ import { validateTypes } from "@ai-sdk/provider-utils";
1666
1693
  async function prepareTools({
1667
1694
  tools,
1668
1695
  toolChoice,
1696
+ hasInlineTools = false,
1669
1697
  disableParallelToolUse,
1670
1698
  cacheControlValidator,
1671
1699
  supportsStructuredOutput,
@@ -1678,11 +1706,11 @@ async function prepareTools({
1678
1706
  const toolWarnings = [];
1679
1707
  const betas = /* @__PURE__ */ new Set();
1680
1708
  const validator = cacheControlValidator || new CacheControlValidator();
1681
- if (tools == null) {
1709
+ if (tools == null && !hasInlineTools) {
1682
1710
  return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
1683
1711
  }
1684
1712
  const anthropicTools2 = [];
1685
- for (const tool of tools) {
1713
+ for (const tool of tools != null ? tools : []) {
1686
1714
  switch (tool.type) {
1687
1715
  case "function": {
1688
1716
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
@@ -1994,9 +2022,10 @@ async function prepareTools({
1994
2022
  }
1995
2023
  }
1996
2024
  }
2025
+ const declaredTools = tools == null ? void 0 : anthropicTools2;
1997
2026
  if (toolChoice == null) {
1998
2027
  return {
1999
- tools: anthropicTools2,
2028
+ tools: declaredTools,
2000
2029
  toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0,
2001
2030
  toolWarnings,
2002
2031
  betas
@@ -2006,7 +2035,7 @@ async function prepareTools({
2006
2035
  switch (type) {
2007
2036
  case "auto":
2008
2037
  return {
2009
- tools: anthropicTools2,
2038
+ tools: declaredTools,
2010
2039
  toolChoice: {
2011
2040
  type: "auto",
2012
2041
  disable_parallel_tool_use: disableParallelToolUse
@@ -2022,7 +2051,7 @@ async function prepareTools({
2022
2051
  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.`
2023
2052
  });
2024
2053
  return {
2025
- tools: anthropicTools2,
2054
+ tools: declaredTools,
2026
2055
  toolChoice: {
2027
2056
  type: "auto",
2028
2057
  disable_parallel_tool_use: disableParallelToolUse
@@ -2032,7 +2061,7 @@ async function prepareTools({
2032
2061
  };
2033
2062
  }
2034
2063
  return {
2035
- tools: anthropicTools2,
2064
+ tools: declaredTools,
2036
2065
  toolChoice: {
2037
2066
  type: "any",
2038
2067
  disable_parallel_tool_use: disableParallelToolUse
@@ -2042,7 +2071,7 @@ async function prepareTools({
2042
2071
  };
2043
2072
  case "none":
2044
2073
  return {
2045
- tools: anthropicTools2,
2074
+ tools: declaredTools,
2046
2075
  toolChoice: { type: "none" },
2047
2076
  toolWarnings,
2048
2077
  betas
@@ -2055,7 +2084,7 @@ async function prepareTools({
2055
2084
  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.`
2056
2085
  });
2057
2086
  return {
2058
- tools: anthropicTools2.filter(
2087
+ tools: declaredTools == null ? void 0 : declaredTools.filter(
2059
2088
  (tool) => "name" in tool && tool.name === toolChoice.toolName
2060
2089
  ),
2061
2090
  toolChoice: {
@@ -2067,7 +2096,7 @@ async function prepareTools({
2067
2096
  };
2068
2097
  }
2069
2098
  return {
2070
- tools: anthropicTools2,
2099
+ tools: declaredTools,
2071
2100
  toolChoice: {
2072
2101
  type: "tool",
2073
2102
  name: toolChoice.toolName,
@@ -2514,6 +2543,32 @@ async function extractErrorValue(value) {
2514
2543
  }
2515
2544
  return {};
2516
2545
  }
2546
+ function isComputerTool(tool) {
2547
+ return tool.type === "provider" && tool.id.startsWith("anthropic.computer_");
2548
+ }
2549
+ async function getInlineToolsFromPrompt(prompt) {
2550
+ var _a;
2551
+ const inlineTools = [];
2552
+ for (const message of prompt) {
2553
+ if (message.role !== "system" || message.providerOptions == null) {
2554
+ continue;
2555
+ }
2556
+ const options = await parseProviderOptions({
2557
+ provider: "anthropic",
2558
+ providerOptions: message.providerOptions,
2559
+ schema: anthropicSystemMessageProviderOptions
2560
+ });
2561
+ for (const toolChange of (_a = options == null ? void 0 : options.toolChanges) != null ? _a : []) {
2562
+ if ("tool" in toolChange) {
2563
+ const tool = toolChange.tool;
2564
+ if (!isComputerTool(tool)) {
2565
+ inlineTools.push(tool);
2566
+ }
2567
+ }
2568
+ }
2569
+ }
2570
+ return inlineTools;
2571
+ }
2517
2572
  async function convertToAnthropicMessagesPrompt({
2518
2573
  prompt,
2519
2574
  sendReasoning,
@@ -2521,7 +2576,8 @@ async function convertToAnthropicMessagesPrompt({
2521
2576
  cacheControlValidator,
2522
2577
  toolNameMapping,
2523
2578
  toolsetNames = {},
2524
- convertMediaPart
2579
+ convertMediaPart,
2580
+ convertInlineTool
2525
2581
  }) {
2526
2582
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
2527
2583
  const betas = /* @__PURE__ */ new Set();
@@ -2558,6 +2614,7 @@ async function convertToAnthropicMessagesPrompt({
2558
2614
  case "system": {
2559
2615
  const systemMessages = [];
2560
2616
  let toolChangeCount = 0;
2617
+ let hasInlineToolDefinition = false;
2561
2618
  let hasMidConversationOptions = false;
2562
2619
  for (const { content: text, providerOptions } of block.messages) {
2563
2620
  const systemMessageOptions = await parseProviderOptions({
@@ -2580,6 +2637,40 @@ async function convertToAnthropicMessagesPrompt({
2580
2637
  });
2581
2638
  }
2582
2639
  for (const toolChange of toolChanges) {
2640
+ if ("tool" in toolChange) {
2641
+ if (convertInlineTool == null) {
2642
+ throw new UnsupportedFunctionalityError2({
2643
+ functionality: "tool additions by value in mid-conversation tool changes"
2644
+ });
2645
+ }
2646
+ const tool = toolChange.tool;
2647
+ if (isComputerTool(tool)) {
2648
+ warnings.push({
2649
+ type: "other",
2650
+ 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.`
2651
+ });
2652
+ continue;
2653
+ }
2654
+ const {
2655
+ definition,
2656
+ warnings: toolWarnings,
2657
+ betas: toolBetas
2658
+ } = await convertInlineTool(tool);
2659
+ warnings.push(...toolWarnings);
2660
+ for (const beta of toolBetas) {
2661
+ betas.add(beta);
2662
+ }
2663
+ if (definition == null) {
2664
+ continue;
2665
+ }
2666
+ content.push({
2667
+ type: "tool_addition",
2668
+ tool: { type: "tool_definition", definition }
2669
+ });
2670
+ toolChangeCount++;
2671
+ hasInlineToolDefinition = true;
2672
+ continue;
2673
+ }
2583
2674
  toolChangeCount++;
2584
2675
  content.push({
2585
2676
  type: toolChange.type,
@@ -2589,6 +2680,9 @@ async function convertToAnthropicMessagesPrompt({
2589
2680
  }
2590
2681
  });
2591
2682
  }
2683
+ if (content.length === 0 && clearAt == null && effort == null) {
2684
+ continue;
2685
+ }
2592
2686
  hasMidConversationOptions || (hasMidConversationOptions = clearAt != null || effort != null);
2593
2687
  systemMessages.push({
2594
2688
  role: "system",
@@ -2623,7 +2717,9 @@ async function convertToAnthropicMessagesPrompt({
2623
2717
  } else {
2624
2718
  messages.push(...systemMessages);
2625
2719
  betas.add("mid-conversation-system-2026-04-07");
2626
- if (toolChangeCount > 0) {
2720
+ if (hasInlineToolDefinition) {
2721
+ betas.add("inline-tools-2026-09-15");
2722
+ } else if (toolChangeCount > 0) {
2627
2723
  betas.add("mid-conversation-tool-changes-2026-07-01");
2628
2724
  }
2629
2725
  if (systemMessages.some((message) => message.clear_at != null)) {
@@ -4084,7 +4180,7 @@ var AnthropicMessagesLanguageModel = class {
4084
4180
  providerOptions,
4085
4181
  stream
4086
4182
  }) {
4087
- var _a, _b, _c, _d, _e, _f, _g, _h;
4183
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4088
4184
  const warnings = [];
4089
4185
  if (frequencyPenalty != null) {
4090
4186
  warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
@@ -4213,8 +4309,22 @@ var AnthropicMessagesLanguageModel = class {
4213
4309
  const cacheControlValidator = new CacheControlValidator(
4214
4310
  this.config.cacheControlProviderOptionsName
4215
4311
  );
4312
+ const defaultEagerInputStreaming = stream && ((_e = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _e : true);
4313
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
4314
+ const declaredFunctionToolNames = new Set(
4315
+ (tools != null ? tools : []).flatMap(
4316
+ (tool) => tool.type === "function" ? [tool.name] : []
4317
+ )
4318
+ );
4216
4319
  const toolNameMapping = createToolNameMapping({
4217
- tools,
4320
+ // later entries win when provider tool names collide, so the declared
4321
+ // tools go last and an inline tool cannot take over their mapping:
4322
+ tools: [
4323
+ ...inlineTools.filter(
4324
+ (tool) => !(tool.type === "provider" && declaredFunctionToolNames.has(tool.name))
4325
+ ),
4326
+ ...tools != null ? tools : []
4327
+ ],
4218
4328
  providerToolNames: {
4219
4329
  "anthropic.code_execution_20250522": "code_execution",
4220
4330
  "anthropic.code_execution_20250825": "code_execution",
@@ -4240,14 +4350,43 @@ var AnthropicMessagesLanguageModel = class {
4240
4350
  }
4241
4351
  });
4242
4352
  const toolsetNames = getAnthropicToolsetNames(tools);
4353
+ const inlineToolDefinitions = [];
4243
4354
  const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
4244
4355
  prompt,
4245
- sendReasoning: (_e = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _e : true,
4356
+ sendReasoning: (_f = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _f : true,
4246
4357
  warnings,
4247
4358
  cacheControlValidator,
4248
4359
  toolNameMapping,
4249
4360
  toolsetNames,
4250
- convertMediaPart: this.config.convertMediaPart
4361
+ convertMediaPart: this.config.convertMediaPart,
4362
+ convertInlineTool: async (tool) => {
4363
+ const {
4364
+ tools: definitions,
4365
+ toolWarnings: toolWarnings2,
4366
+ betas: betas2
4367
+ } = await prepareTools({
4368
+ tools: [tool],
4369
+ toolChoice: void 0,
4370
+ cacheControlValidator,
4371
+ supportsStructuredOutput,
4372
+ supportsStrictTools
4373
+ // no stream-dependent defaults (eager input streaming): the
4374
+ // definition is replayed on every request and has to stay
4375
+ // identical between streaming and non-streaming calls to keep
4376
+ // the cache.
4377
+ });
4378
+ if ((definitions == null ? void 0 : definitions[0]) != null) {
4379
+ inlineToolDefinitions.push({
4380
+ sdkName: tool.name,
4381
+ definition: definitions[0]
4382
+ });
4383
+ }
4384
+ return {
4385
+ definition: definitions == null ? void 0 : definitions[0],
4386
+ warnings: toolWarnings2,
4387
+ betas: betas2
4388
+ };
4389
+ }
4251
4390
  });
4252
4391
  if (rejectsThinkingDisabled && (anthropicOptions == null ? void 0 : anthropicOptions.thinking) != null) {
4253
4392
  const requestedThinking = anthropicOptions.thinking;
@@ -4357,7 +4496,7 @@ var AnthropicMessagesLanguageModel = class {
4357
4496
  ...(anthropicOptions == null ? void 0 : anthropicOptions.cacheControl) && {
4358
4497
  cache_control: anthropicOptions.cacheControl
4359
4498
  },
4360
- ...((_f = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _f.userId) != null && {
4499
+ ...((_g = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _g.userId) != null && {
4361
4500
  metadata: { user_id: anthropicOptions.metadata.userId }
4362
4501
  },
4363
4502
  // mcp servers:
@@ -4552,7 +4691,6 @@ var AnthropicMessagesLanguageModel = class {
4552
4691
  } else if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0) {
4553
4692
  betas.add("server-side-fallback-2026-06-01");
4554
4693
  }
4555
- const defaultEagerInputStreaming = stream && ((_g = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _g : true);
4556
4694
  const {
4557
4695
  tools: anthropicTools2,
4558
4696
  toolChoice: anthropicToolChoice,
@@ -4576,6 +4714,9 @@ var AnthropicMessagesLanguageModel = class {
4576
4714
  } : {
4577
4715
  tools: tools != null ? tools : [],
4578
4716
  toolChoice,
4717
+ // tool changes can add tools when `tools` is empty, so the tool
4718
+ // choice and parallel tool use settings still apply:
4719
+ hasInlineTools: inlineTools.length > 0,
4579
4720
  disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
4580
4721
  cacheControlValidator,
4581
4722
  supportsStructuredOutput,
@@ -4584,6 +4725,37 @@ var AnthropicMessagesLanguageModel = class {
4584
4725
  rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
4585
4726
  }
4586
4727
  );
4728
+ 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) {
4729
+ for (const server of (_h = baseArgs.mcp_servers) != null ? _h : []) {
4730
+ server.tool_configuration = {
4731
+ allowed_tools: (_i = server.tool_configuration) == null ? void 0 : _i.allowed_tools,
4732
+ enabled: false
4733
+ };
4734
+ }
4735
+ const emittedInlineDefinitions = new Set(
4736
+ messagesPrompt.messages.flatMap(
4737
+ (message) => message.role === "system" ? message.content.flatMap(
4738
+ (part) => part.type === "tool_addition" && part.tool.type === "tool_definition" ? [part.tool.definition] : []
4739
+ ) : []
4740
+ )
4741
+ );
4742
+ const selectedSdkName = toolChoice.type === "tool" ? toolChoice.toolName : void 0;
4743
+ const selectedTool = tools == null ? void 0 : tools.find((tool) => tool.name === selectedSdkName);
4744
+ const selectedProviderName = jsonResponseTool != null && selectedSdkName != null && (selectedTool == null ? void 0 : selectedTool.type) !== "function" ? toolNameMapping.toProviderToolName(selectedSdkName) : selectedSdkName;
4745
+ const conflictingTool = inlineToolDefinitions.find(
4746
+ ({ sdkName, definition }) => emittedInlineDefinitions.has(definition) && (toolChoice.type === "none" || // The JSON-tool path filters application tools by SDK name before
4747
+ // conversion; the forced-choice fallback filters by provider name.
4748
+ jsonResponseTool != null && sdkName !== selectedSdkName || !("name" in definition) || definition.name !== selectedProviderName)
4749
+ );
4750
+ if (conflictingTool != null) {
4751
+ const toolName = "name" in conflictingTool.definition ? conflictingTool.definition.name : conflictingTool.definition.type;
4752
+ const choice = toolChoice.type === "tool" ? `named tool choice '${toolChoice.toolName}'` : `tool choice 'none'`;
4753
+ throw new InvalidArgumentError({
4754
+ argument: "toolChoice",
4755
+ 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.`
4756
+ });
4757
+ }
4758
+ }
4587
4759
  const cacheWarnings = cacheControlValidator.getWarnings();
4588
4760
  return {
4589
4761
  args: {
@@ -4598,7 +4770,7 @@ var AnthropicMessagesLanguageModel = class {
4598
4770
  ...betas,
4599
4771
  ...toolsBetas,
4600
4772
  ...userSuppliedBetas,
4601
- ...(_h = anthropicOptions == null ? void 0 : anthropicOptions.anthropicBeta) != null ? _h : []
4773
+ ...(_j = anthropicOptions == null ? void 0 : anthropicOptions.anthropicBeta) != null ? _j : []
4602
4774
  ]),
4603
4775
  usesJsonResponseTool: jsonResponseTool != null,
4604
4776
  toolNameMapping,
@@ -7036,7 +7208,7 @@ function createAnthropic(options = {}) {
7036
7208
  )) != null ? _a : ANTHROPIC_API_VERSIONED_URL;
7037
7209
  const providerName = (_b = options.name) != null ? _b : "anthropic.messages";
7038
7210
  if (options.apiKey && options.authToken) {
7039
- throw new InvalidArgumentError({
7211
+ throw new InvalidArgumentError2({
7040
7212
  argument: "apiKey/authToken",
7041
7213
  message: "Both apiKey and authToken were provided. Please use only one authentication method."
7042
7214
  });