@ai-sdk/anthropic 4.0.96 → 4.0.98

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.
@@ -2,6 +2,7 @@ import {
2
2
  APICallError,
3
3
  InvalidArgumentError,
4
4
  InvalidResponseDataError,
5
+ UnsupportedFunctionalityError,
5
6
  type JSONObject,
6
7
  type LanguageModelV4,
7
8
  type LanguageModelV4CallOptions,
@@ -72,6 +73,7 @@ import {
72
73
  } from './convert-anthropic-usage';
73
74
  import {
74
75
  convertToAnthropicPrompt,
76
+ getInlineToolsFromPrompt,
75
77
  type AnthropicMediaPartConverter,
76
78
  } from './convert-to-anthropic-prompt';
77
79
  import { CacheControlValidator } from './get-cache-control';
@@ -272,6 +274,8 @@ export type AnthropicLanguageModelConfig = {
272
274
  generateId?: () => string;
273
275
  supportsNativeStructuredOutput?: boolean;
274
276
  supportsStrictTools?: boolean;
277
+ /** Opt in only for platforms that support Anthropic message threads. */
278
+ supportsMessageThreads?: boolean;
275
279
  /** Maximum temperature for compatible providers. Defaults to 1. */
276
280
  maxTemperature?: number;
277
281
  /** Preserve temperature and topP with thinking for compatible providers. */
@@ -466,6 +470,26 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
466
470
  customProviderOptions ?? {},
467
471
  );
468
472
 
473
+ if (anthropicOptions.serviceTier != null) {
474
+ const supportedTiers =
475
+ providerOptionsName === 'anthropic'
476
+ ? ['auto', 'standard_only']
477
+ : providerOptionsName === 'minimax'
478
+ ? ['standard', 'priority']
479
+ : undefined;
480
+ if (
481
+ supportedTiers != null &&
482
+ !supportedTiers.includes(anthropicOptions.serviceTier)
483
+ ) {
484
+ warnings.push({
485
+ type: 'unsupported',
486
+ feature: 'serviceTier',
487
+ details: `serviceTier "${anthropicOptions.serviceTier}" is not supported by ${providerOptionsName}. Use ${supportedTiers.map(tier => `"${tier}"`).join(' or ')}.`,
488
+ });
489
+ anthropicOptions.serviceTier = undefined;
490
+ }
491
+ }
492
+
469
493
  const {
470
494
  maxOutputTokens: maxOutputTokensForModel,
471
495
  supportsStructuredOutput: modelSupportsStructuredOutput,
@@ -598,13 +622,44 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
598
622
  });
599
623
  }
600
624
 
625
+ const thread = anthropicOptions?.thread;
626
+ if (thread != null && config.supportsMessageThreads !== true) {
627
+ throw new UnsupportedFunctionalityError({
628
+ functionality: 'Anthropic message threads',
629
+ message: `${config.provider} does not support Anthropic message threads.`,
630
+ });
631
+ }
632
+ if (
633
+ thread != null &&
634
+ (compaction != null ||
635
+ contextManagement?.edits.some(
636
+ edit =>
637
+ edit.type !== 'clear_thinking_20251015' || edit.keep !== 'all',
638
+ ))
639
+ ) {
640
+ throw new InvalidArgumentError({
641
+ argument: 'providerOptions.anthropic.thread',
642
+ message:
643
+ 'Anthropic message threads do not support compaction or context editing, except clear_thinking_20251015 with keep: "all".',
644
+ });
645
+ }
646
+
601
647
  // Create a shared cache control validator to track breakpoints across tools and messages
602
648
  const cacheControlValidator = new CacheControlValidator(
603
649
  config.cacheControlProviderOptionsName,
650
+ thread != null && anthropicOptions?.cacheControl != null ? 1 : 0,
604
651
  );
605
652
 
653
+ const defaultEagerInputStreaming =
654
+ stream && (anthropicOptions?.toolStreaming ?? true);
655
+
656
+ // Tools that tool changes add by value are only known from the prompt.
657
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
658
+
606
659
  const toolNameMapping = createToolNameMapping({
607
- tools,
660
+ // later entries win when provider tool names collide, so the declared
661
+ // tools go last and an inline tool cannot take over their mapping:
662
+ tools: [...inlineTools, ...(tools ?? [])],
608
663
  providerToolNames: {
609
664
  'anthropic.code_execution_20250522': 'code_execution',
610
665
  'anthropic.code_execution_20250825': 'code_execution',
@@ -642,8 +697,59 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
642
697
  toolNameMapping,
643
698
  toolsetNames,
644
699
  convertMediaPart: config.convertMediaPart,
700
+ convertInlineTool: async tool => {
701
+ const {
702
+ tools: definitions,
703
+ toolWarnings,
704
+ betas,
705
+ } = await prepareTools({
706
+ tools: [tool],
707
+ toolChoice: undefined,
708
+ cacheControlValidator,
709
+ supportsStructuredOutput,
710
+ supportsStrictTools,
711
+ // no stream-dependent defaults (eager input streaming): the
712
+ // definition is replayed on every request and has to stay identical
713
+ // between streaming and non-streaming calls to keep the cache.
714
+ });
715
+
716
+ return {
717
+ definition: definitions?.[0],
718
+ warnings: toolWarnings,
719
+ betas,
720
+ };
721
+ },
645
722
  });
646
723
 
724
+ if (thread != null) {
725
+ const unpinnedBetas = [...betas].filter(
726
+ beta =>
727
+ !userSuppliedBetas.has(beta) &&
728
+ !anthropicOptions?.anthropicBeta?.includes(beta),
729
+ );
730
+ if (unpinnedBetas.length > 0) {
731
+ warnings.push({
732
+ type: 'compatibility',
733
+ feature: 'providerOptions.anthropic.thread',
734
+ details:
735
+ `Message content enabled beta headers: ${unpinnedBetas.join(', ')}. ` +
736
+ 'Thread requests require the same beta set on every turn. Pin these values with anthropicBeta on every request, or start a new thread when the set changes.',
737
+ });
738
+ }
739
+ if (
740
+ thread.type === 'continue' &&
741
+ (messagesPrompt.system != null || (tools?.length ?? 0) > 0)
742
+ ) {
743
+ warnings.push({
744
+ type: 'compatibility',
745
+ feature: 'providerOptions.anthropic.thread',
746
+ details:
747
+ 'Continuation uses the system prompt and tool definitions stored by the create request; supplied definitions are omitted from the wire request. ' +
748
+ 'Supply identical tools for local tool handling and fixed request settings. To change system instructions or tools, start a new thread.',
749
+ });
750
+ }
751
+ }
752
+
647
753
  /*
648
754
  * Map top-level `reasoning` to Anthropic thinking/effort when provider
649
755
  * options don't already specify them. Provider options always take precedence.
@@ -897,7 +1003,16 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
897
1003
  }),
898
1004
 
899
1005
  // prompt:
900
- system: messagesPrompt.system,
1006
+ system: thread?.type === 'continue' ? undefined : messagesPrompt.system,
1007
+ ...(thread != null && {
1008
+ thread:
1009
+ thread.type === 'create'
1010
+ ? { type: 'create' as const }
1011
+ : {
1012
+ type: 'continue' as const,
1013
+ previous_message_id: thread.previousMessageId,
1014
+ },
1015
+ }),
901
1016
  messages: messagesPrompt.messages,
902
1017
 
903
1018
  ...(anthropicOptions?.safeguards &&
@@ -1130,9 +1245,6 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1130
1245
  betas.add('server-side-fallback-2026-06-01');
1131
1246
  }
1132
1247
 
1133
- const defaultEagerInputStreaming =
1134
- stream && (anthropicOptions?.toolStreaming ?? true);
1135
-
1136
1248
  const {
1137
1249
  tools: anthropicTools,
1138
1250
  toolChoice: anthropicToolChoice,
@@ -1162,6 +1274,9 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1162
1274
  : {
1163
1275
  tools: tools ?? [],
1164
1276
  toolChoice,
1277
+ // tool changes can add tools when `tools` is empty, so the tool
1278
+ // choice and parallel tool use settings still apply:
1279
+ hasInlineTools: inlineTools.length > 0,
1165
1280
  disableParallelToolUse: anthropicOptions?.disableParallelToolUse,
1166
1281
  cacheControlValidator,
1167
1282
  supportsStructuredOutput,
@@ -1178,18 +1293,22 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1178
1293
  return {
1179
1294
  args: {
1180
1295
  ...baseArgs,
1181
- tools: anthropicTools,
1296
+ tools: thread?.type === 'continue' ? undefined : anthropicTools,
1182
1297
  tool_choice: anthropicToolChoice,
1183
1298
  stream: stream === true ? true : undefined, // do not send when not streaming
1184
1299
  },
1185
1300
  warnings: [...warnings, ...toolWarnings, ...cacheWarnings],
1186
1301
  betas: new Set([
1302
+ ...(thread != null ? ['message-threads-2026-08-12'] : []),
1187
1303
  ...betas,
1188
1304
  ...toolsBetas,
1189
1305
  ...userSuppliedBetas,
1190
1306
  ...(anthropicOptions?.anthropicBeta ?? []),
1191
1307
  ]),
1308
+ markCodeExecutionDynamic:
1309
+ hasDynamicFilteringWebToolWithoutCodeExecution(anthropicTools),
1192
1310
  usesJsonResponseTool: jsonResponseTool != null,
1311
+ includePings: stream === true && anthropicOptions?.includePings === true,
1193
1312
  toolNameMapping,
1194
1313
  providerOptionsName,
1195
1314
  usedCustomProviderKey,
@@ -1317,6 +1436,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1317
1436
  warnings,
1318
1437
  betas,
1319
1438
  usesJsonResponseTool,
1439
+ markCodeExecutionDynamic,
1320
1440
  toolNameMapping,
1321
1441
  providerOptionsName,
1322
1442
  usedCustomProviderKey,
@@ -1334,9 +1454,6 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1334
1454
  ...this.extractCitationDocuments(options.prompt),
1335
1455
  ];
1336
1456
 
1337
- const markCodeExecutionDynamic =
1338
- hasDynamicFilteringWebToolWithoutCodeExecution(args.tools);
1339
-
1340
1457
  const {
1341
1458
  responseHeaders,
1342
1459
  value: response,
@@ -1902,10 +2019,13 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1902
2019
  warnings,
1903
2020
  providerMetadata: (() => {
1904
2021
  const stopDetails = mapAnthropicStopDetails(response.stop_details);
2022
+ const serviceTier =
2023
+ response.usage.service_tier ?? response.service_tier;
1905
2024
 
1906
2025
  const anthropicMetadata = {
1907
2026
  usage: response.usage as JSONObject,
1908
2027
  stopSequence: response.stop_sequence ?? null,
2028
+ ...(serviceTier != null ? { serviceTier } : {}),
1909
2029
  ...(stopDetails != null ? { stopDetails } : {}),
1910
2030
  ...(response.input_transformations != null
1911
2031
  ? { inputTransformations: response.input_transformations }
@@ -1981,6 +2101,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1981
2101
  warnings,
1982
2102
  betas,
1983
2103
  usesJsonResponseTool,
2104
+ markCodeExecutionDynamic,
2105
+ includePings,
1984
2106
  toolNameMapping,
1985
2107
  providerOptionsName,
1986
2108
  usedCustomProviderKey,
@@ -1998,9 +2120,6 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
1998
2120
  ...this.extractCitationDocuments(options.prompt),
1999
2121
  ];
2000
2122
 
2001
- const markCodeExecutionDynamic =
2002
- hasDynamicFilteringWebToolWithoutCodeExecution(body.tools);
2003
-
2004
2123
  const url = this.buildRequestUrl(true);
2005
2124
  const { responseHeaders, value: response } = await postJsonToApi({
2006
2125
  url,
@@ -2066,6 +2185,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
2066
2185
  | null = null;
2067
2186
  let rawUsage: JSONObject | undefined = undefined;
2068
2187
  let stopSequence: string | null = null;
2188
+ let serviceTier: string | null = null;
2069
2189
  let stopDetails: AnthropicMessageMetadata['stopDetails'] = undefined;
2070
2190
  let inputTransformations: AnthropicMessageMetadata['inputTransformations'];
2071
2191
  let safeguardResults: AnthropicMessageMetadata['safeguardResults'];
@@ -2144,7 +2264,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
2144
2264
 
2145
2265
  switch (value.type) {
2146
2266
  case 'ping': {
2147
- return; // ignored
2267
+ if (includePings) controller.enqueue({ type: 'ping' });
2268
+ return;
2148
2269
  }
2149
2270
 
2150
2271
  case 'content_block_start': {
@@ -3056,6 +3177,10 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
3056
3177
  return;
3057
3178
  }
3058
3179
 
3180
+ serviceTier =
3181
+ value.message.usage.service_tier ??
3182
+ value.message.service_tier ??
3183
+ null;
3059
3184
  isMessageOpen = true;
3060
3185
  activeMessageId = value.message.id;
3061
3186
  heldBackTextByIndex.clear();
@@ -3224,6 +3349,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
3224
3349
  safeguardResults = value.delta.safeguard_results;
3225
3350
  }
3226
3351
 
3352
+ serviceTier = value.usage.service_tier ?? serviceTier;
3353
+
3227
3354
  rawUsage = {
3228
3355
  ...rawUsage,
3229
3356
  ...(value.usage as JSONObject),
@@ -3239,6 +3366,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
3239
3366
  const anthropicMetadata = {
3240
3367
  usage: (rawUsage as JSONObject) ?? null,
3241
3368
  stopSequence,
3369
+ ...(serviceTier != null ? { serviceTier } : {}),
3242
3370
  ...(stopDetails != null ? { stopDetails } : {}),
3243
3371
  ...(inputTransformations != null
3244
3372
  ? { inputTransformations }
@@ -3407,8 +3535,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
3407
3535
 
3408
3536
  let result = await firstChunkReader.read();
3409
3537
 
3410
- // when raw chunks are enabled, the first chunk is a raw chunk, so we need to read the next chunk
3411
- if (result.value?.type === 'raw') {
3538
+ // Ignore transport-only parts while checking the first provider event.
3539
+ while (result.value?.type === 'raw' || result.value?.type === 'ping') {
3412
3540
  result = await firstChunkReader.read();
3413
3541
  }
3414
3542
 
@@ -51,6 +51,9 @@ export interface AnthropicMessageMetadata {
51
51
  usage: JSONObject;
52
52
  stopSequence: string | null;
53
53
 
54
+ /** The tier used by the provider, when returned in the response. */
55
+ serviceTier?: string | null;
56
+
54
57
  /**
55
58
  * Input blocks that Anthropic transformed before inference. This is
56
59
  * populated when thinking binding controls drop a mismatched thinking block.
@@ -15,7 +15,9 @@ type AnthropicLanguageProviderOption = keyof AnthropicLanguageModelOptions;
15
15
  */
16
16
  export const anthropicProviderOptions = {
17
17
  language: {
18
+ thread: { description: 'Create or continue a short-lived message thread.' },
18
19
  sendReasoning: { description: 'Whether to send reasoning to the model.' },
20
+ includePings: { description: 'Include transient ping events in streams.' },
19
21
  structuredOutputMode: {
20
22
  description: 'How structured outputs are generated.',
21
23
  },
@@ -336,6 +338,7 @@ function createAnthropicLanguageModelEntry(
336
338
  anthropicProviderOptions.language,
337
339
  declared ? true : 'unknown',
338
340
  {
341
+ includePings: true,
339
342
  thinking: reasoningSupport,
340
343
  effort: documented?.effort ?? 'unknown',
341
344
  // Fast mode is documented for claude-opus-4-6 only.
@@ -404,3 +407,6 @@ export function getAnthropicModelCapabilities(modelId: string) {
404
407
  isKnownModel: requestConfig.knownModel,
405
408
  };
406
409
  }
410
+
411
+ // Compatibility name also exported by the Anthropic runtime adapter.
412
+ export { getAnthropicModelCapabilities as getModelCapabilities };
@@ -27,6 +27,7 @@ export interface AnthropicToolOptions {
27
27
  export async function prepareTools({
28
28
  tools,
29
29
  toolChoice,
30
+ hasInlineTools = false,
30
31
  disableParallelToolUse,
31
32
  cacheControlValidator,
32
33
  supportsStructuredOutput,
@@ -36,6 +37,13 @@ export async function prepareTools({
36
37
  }: {
37
38
  tools: LanguageModelV4CallOptions['tools'];
38
39
  toolChoice: LanguageModelV4CallOptions['toolChoice'] | undefined;
40
+
41
+ /**
42
+ * Whether tools are added by value in the prompt (mid-conversation tool
43
+ * changes). The model has tools even when `tools` is empty, so the tool
44
+ * choice and parallel tool use settings still need to be sent.
45
+ */
46
+ hasInlineTools?: boolean;
39
47
  disableParallelToolUse?: boolean;
40
48
  cacheControlValidator?: CacheControlValidator;
41
49
 
@@ -74,13 +82,13 @@ export async function prepareTools({
74
82
  const betas = new Set<string>();
75
83
  const validator = cacheControlValidator || new CacheControlValidator();
76
84
 
77
- if (tools == null) {
85
+ if (tools == null && !hasInlineTools) {
78
86
  return { tools: undefined, toolChoice: undefined, toolWarnings, betas };
79
87
  }
80
88
 
81
89
  const anthropicTools: AnthropicTool[] = [];
82
90
 
83
- for (const tool of tools) {
91
+ for (const tool of tools ?? []) {
84
92
  switch (tool.type) {
85
93
  case 'function': {
86
94
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
@@ -129,7 +137,9 @@ export async function prepareTools({
129
137
  : {}),
130
138
  });
131
139
 
132
- if (supportsStructuredOutput === true) {
140
+ // Native final output does not require this beta. Only send it for
141
+ // providers that also support strict tools.
142
+ if (supportsStructuredOutput === true && supportsStrictTools === true) {
133
143
  betas.add('structured-outputs-2025-11-13');
134
144
  }
135
145
 
@@ -462,9 +472,13 @@ export async function prepareTools({
462
472
  }
463
473
  }
464
474
 
475
+ // when the user passed no tools (they exist only in tool changes inside the
476
+ // messages), omit `tools` instead of sending an empty array
477
+ const declaredTools = tools == null ? undefined : anthropicTools;
478
+
465
479
  if (toolChoice == null) {
466
480
  return {
467
- tools: anthropicTools,
481
+ tools: declaredTools,
468
482
  toolChoice: disableParallelToolUse
469
483
  ? { type: 'auto', disable_parallel_tool_use: disableParallelToolUse }
470
484
  : undefined,
@@ -478,7 +492,7 @@ export async function prepareTools({
478
492
  switch (type) {
479
493
  case 'auto':
480
494
  return {
481
- tools: anthropicTools,
495
+ tools: declaredTools,
482
496
  toolChoice: {
483
497
  type: 'auto',
484
498
  disable_parallel_tool_use: disableParallelToolUse,
@@ -496,7 +510,7 @@ export async function prepareTools({
496
510
  `Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made.`,
497
511
  });
498
512
  return {
499
- tools: anthropicTools,
513
+ tools: declaredTools,
500
514
  toolChoice: {
501
515
  type: 'auto',
502
516
  disable_parallel_tool_use: disableParallelToolUse,
@@ -506,7 +520,7 @@ export async function prepareTools({
506
520
  };
507
521
  }
508
522
  return {
509
- tools: anthropicTools,
523
+ tools: declaredTools,
510
524
  toolChoice: {
511
525
  type: 'any',
512
526
  disable_parallel_tool_use: disableParallelToolUse,
@@ -516,7 +530,7 @@ export async function prepareTools({
516
530
  };
517
531
  case 'none':
518
532
  return {
519
- tools: anthropicTools,
533
+ tools: declaredTools,
520
534
  toolChoice: { type: 'none' },
521
535
  toolWarnings,
522
536
  betas,
@@ -532,7 +546,7 @@ export async function prepareTools({
532
546
  `Instruct the model to use the tool in the prompt and verify that a tool call was made.`,
533
547
  });
534
548
  return {
535
- tools: anthropicTools.filter(
549
+ tools: declaredTools?.filter(
536
550
  tool => 'name' in tool && tool.name === toolChoice.toolName,
537
551
  ),
538
552
  toolChoice: {
@@ -544,7 +558,7 @@ export async function prepareTools({
544
558
  };
545
559
  }
546
560
  return {
547
- tools: anthropicTools,
561
+ tools: declaredTools,
548
562
  toolChoice: {
549
563
  type: 'tool',
550
564
  name: toolChoice.toolName,
@@ -20,7 +20,7 @@ import {
20
20
  type Resolvable,
21
21
  } from '@ai-sdk/provider-utils';
22
22
  import { Experimental_DecisionLanguageModel as DecisionLanguageModel } from '@ai-sdk/provider-utils/experimental-decision';
23
- import { AnthropicFiles } from './anthropic-files';
23
+ import { AnthropicFiles } from './files/anthropic-files';
24
24
  import { AnthropicLanguageModel } from './anthropic-language-model';
25
25
  import { AnthropicBatch } from './anthropic-batch';
26
26
  import type { AnthropicModelId } from './anthropic-language-model-options';
@@ -195,6 +195,7 @@ export function createAnthropic(
195
195
 
196
196
  const languageModelConfig = {
197
197
  provider: providerName,
198
+ supportsMessageThreads: true,
198
199
  baseURL,
199
200
  headers: getHeaders,
200
201
  fetch: options.fetch,