@ai-sdk/anthropic 4.0.97 → 4.0.99

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.
@@ -244,6 +244,150 @@ Initial usage may be incomplete; use `result.usage` for final token counts.
244
244
  Like other custom parts, this event is included in response content and forwarded
245
245
  to UI message streams. It is ignored when replaying conversation history to Anthropic.
246
246
 
247
+ ### Message Threads
248
+
249
+ [Anthropic message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads)
250
+ reduce request upload size and time to first token in long conversations. The first
251
+ request sends the full conversation; subsequent requests send only new messages.
252
+ Token usage, pricing, and rate limits remain unchanged. Prompt caching is separate.
253
+
254
+ ```ts
255
+ import { anthropic } from '@ai-sdk/anthropic';
256
+ import { generateText } from 'ai';
257
+
258
+ const model = anthropic('claude-sonnet-4-6');
259
+ const first = await generateText({
260
+ model,
261
+ system: 'Keep replies brief.',
262
+ prompt: 'Remember that my favorite color is cobalt blue.',
263
+ providerOptions: { anthropic: { thread: { type: 'create' } } },
264
+ });
265
+
266
+ if (first.response.id == null) throw new Error('Missing message ID.');
267
+
268
+ const second = await generateText({
269
+ model,
270
+ prompt: 'What is my favorite color?',
271
+ providerOptions: {
272
+ anthropic: {
273
+ thread: { type: 'continue', previousMessageId: first.response.id },
274
+ },
275
+ },
276
+ });
277
+ ```
278
+
279
+ The provider adds the `message-threads-2026-08-12` beta header. On continuation it
280
+ omits `system` and tool definitions from the request, even if supplied: Anthropic
281
+ retains them from the create request. If the create request used tools, you must
282
+ supply identical tool definitions to the SDK on continuation for tool name mapping,
283
+ execution, tool choice, and tool beta headers. They are not uploaded again.
284
+ Supplied system instructions are ignored on continuation; the provider emits a
285
+ compatibility warning when supplied system or tool definitions are omitted.
286
+ Start a new thread to change instructions rather than passing new leading system
287
+ messages to a continuation.
288
+
289
+ **Conversation management is explicit.** The provider does not retain history,
290
+ remove previously sent messages, or automatically replay requests. Keep a full
291
+ local copy of the conversation. Passing the entire history on continuation can
292
+ duplicate messages or cause an API error. For tool calls, continue with only the
293
+ new tool results. In a multi-step agent, use `prepareStep` to update the response
294
+ ID and select only new messages; simply setting `thread: { type: 'create' }` on an
295
+ agent does not automatically continue its thread.
296
+
297
+ For example, with an existing client-side `weather` tool:
298
+
299
+ ```ts
300
+ import { ToolLoopAgent, stepCountIs } from 'ai';
301
+
302
+ const agent = new ToolLoopAgent({
303
+ model,
304
+ tools: { weather },
305
+ stopWhen: stepCountIs(5),
306
+ prepareStep: ({ steps }) => {
307
+ const previous = steps.at(-1);
308
+ if (previous == null) {
309
+ return { providerOptions: { anthropic: { thread: { type: 'create' } } } };
310
+ }
311
+ const previousMessageId = previous.response.id;
312
+ if (previousMessageId == null) throw new Error('Missing message ID.');
313
+ return {
314
+ messages: previous.response.messages.filter(m => m.role === 'tool'),
315
+ providerOptions: {
316
+ anthropic: { thread: { type: 'continue', previousMessageId } },
317
+ },
318
+ };
319
+ },
320
+ });
321
+ ```
322
+
323
+ This pattern is for a loop with client-side tools that execute without approval.
324
+ Provider-executed tool continuations and tool-approval flows require their own
325
+ message selection. The compatibility warning about retained instructions and tool
326
+ definitions is expected in this example. Persist the original input and
327
+ each step's response messages for recovery; never rerun completed tools just to
328
+ rebuild history. Do not reuse a static continuation ID across multiple steps.
329
+
330
+ **Pin content-dependent beta headers.** The beta header set is fixed for a thread,
331
+ but features such as PDFs and Files API references enable headers based on the
332
+ messages in the current request. For example, when creating a thread with a PDF,
333
+ set `anthropicBeta: ['pdfs-2024-09-25']` on both the create request and every
334
+ continuation, including text-only continuations. The provider warns when message
335
+ content enables a beta that has not been pinned explicitly through `anthropicBeta`
336
+ or request headers. Plan for the features the conversation will use; start a new
337
+ thread with full history if a later turn needs additional beta headers.
338
+
339
+ Threads expire five minutes after their last request and can become unavailable
340
+ earlier. Inspect `APICallError.data.error.details.error_code` (after narrowing the
341
+ unknown `data` value). On `thread_not_found`, `thread_already_continued`, or
342
+ `thread_continue_in_flight`, replay the full conversation once with
343
+ `thread: { type: 'create' }`, including the original system prompt and tools.
344
+ Do not treat every 404 as an expired thread. Remove cache breakpoints from older
345
+ replayed messages to stay within Anthropic's four-breakpoint limit. If the
346
+ conversation cannot be stored, send the full history without `thread`.
347
+
348
+ Continue only from the latest response ID, which can be continued once. With
349
+ `streamText`, fully consume the stream before using `await result.response` to
350
+ continue. Check that `await result.finishReason` is not `'interrupted'` before continuing.
351
+ A partial or aborted stream must not be treated as a completed turn.
352
+ If a stream drops, recovery is the application's responsibility; don't blindly
353
+ append a replay to output already shown to the user.
354
+
355
+ To change the system prompt, tools, model, thinking, tool choice, output format,
356
+ context management, top-level cache control, or beta headers, start a new thread
357
+ with the full history. Fixed fields must otherwise have the same values on every
358
+ request. Send MCP configuration and container IDs on each request that needs them.
359
+ After a fallback model responds, start a new thread with the full history. Detect
360
+ this through a `fallback_message` entry in
361
+ `providerMetadata.anthropic.iterations`. After a refusal (`finishReason ===
362
+ 'content-filter'` or `rawFinishReason === 'refusal'`), start a new thread with the
363
+ refused turn removed or rephrased.
364
+
365
+ On models that bind preserved thinking to the prompt prefix, changing system
366
+ instructions or tools can invalidate earlier reasoning. Remove the earlier
367
+ reasoning parts, or set `sendReasoning: false`, when creating that new thread.
368
+
369
+ The provider-level interface accepts empty continuation prompts for `pause_turn`,
370
+ but `generateText` and `streamText` currently reject empty `messages`. Check
371
+ `rawFinishReason === 'pause_turn'` to detect this case. Resuming an empty turn
372
+ requires using the provider-level `doGenerate` or `doStream` interface with the
373
+ same fixed settings; the agent example above does not handle paused server turns.
374
+
375
+ The `@ai-sdk/anthropic` provider supports this beta on the native Claude API and
376
+ compatible Anthropic-managed endpoints. Anthropic's Claude Platform on AWS and
377
+ Anthropic-managed Google Cloud are distinct from Amazon Bedrock and Vertex AI.
378
+ The direct `@ai-sdk/anthropic-aws` provider supports message threads; with SigV4,
379
+ use the same IAM role or IAM user throughout the thread.
380
+
381
+ `@ai-sdk/amazon-bedrock/anthropic` and `@ai-sdk/google-vertex/anthropic` do not
382
+ support message threads.
383
+
384
+ Threads do not support Message Batches, compaction, or context editing other than
385
+ `clear_thinking_20251015` with `keep: 'all'`. They are not eligible for zero data
386
+ retention or HIPAA readiness. Contents are encrypted in memory, never written to
387
+ durable storage, and deleted within one hour of their last use. There is no API
388
+ to list, read, or delete threads. See Anthropic's documentation for platform
389
+ availability and all limitations.
390
+
247
391
  ### Streaming heartbeats
248
392
 
249
393
  To receive typed Anthropic heartbeat events, set
@@ -279,6 +423,12 @@ UI responses; applications can send SSE comments at their transport boundary.
279
423
 
280
424
  The following optional provider options are available for Anthropic models:
281
425
 
426
+ - `thread` _object_
427
+
428
+ Optional. Use `{ type: 'create' }` to create a short-lived server-side message
429
+ thread, or `{ type: 'continue', previousMessageId: string }` to continue one.
430
+ The required beta header is added automatically. See [Message Threads](#message-threads).
431
+
282
432
  - `includePings` _boolean_
283
433
 
284
434
  Optional. Defaults to `false`. Emit typed `ping` parts during streaming without
@@ -412,13 +562,21 @@ schemas with open objects such as maps (`additionalProperties` set to a schema
412
562
  or `true`), which native structured outputs would return as `{}`.
413
563
  Likewise, a `required` or named `toolChoice` is downgraded to
414
564
  `auto` with a warning; instruct the model to use the tool in your prompt and
415
- verify that a tool call was made.
565
+ verify that a tool call was made. When a named choice falls back to `auto`,
566
+ inline tool additions must use the selected tool's name. Conflicting additions,
567
+ including definitions replayed from conversation history, cause an
568
+ `InvalidArgumentError` before the request is sent.
416
569
 
417
570
  The JSON-tool fallback limits which application tools are available:
418
571
  `toolChoice: 'none'` sends only the internal JSON response tool, and a named tool
419
572
  choice sends only that application tool alongside the JSON response tool. The
420
573
  fallback can produce a JSON response without calling the named application tool;
421
574
  verify the selected call if your application requires it.
575
+ These restrictions also apply to inline tool definitions: a named choice allows
576
+ only additions with the selected tool's name, and `toolChoice: 'none'` rejects
577
+ all inline additions. Conflicting definitions cause an `InvalidArgumentError`
578
+ before the request is sent. Tool changes on the initial system message remain
579
+ ignored with a warning.
422
580
 
423
581
  When the JSON tool cannot be forced (for example with manual thinking) and the
424
582
  model answers in text without calling it, the text of its final answer is
@@ -929,6 +1087,9 @@ the selected tool is sent. This also applies when the top-level `reasoning`
929
1087
  option enables manual thinking, including when structured output uses the
930
1088
  internal JSON response tool. Tool use is no longer guaranteed: instruct the
931
1089
  model to use the tool in your prompt and verify that a tool call was made.
1090
+ Inline tool additions must use the selected tool's name when a named choice
1091
+ falls back to `auto`. Conflicting additions, including definitions replayed from
1092
+ conversation history, cause an `InvalidArgumentError` before the request is sent.
932
1093
 
933
1094
  See [AI SDK UI: Chatbot](/docs/ai-sdk-ui/chatbot#reasoning) for more details
934
1095
  on how to integrate reasoning into your chatbot.
@@ -1518,7 +1679,13 @@ return several actions in one turn, each as its own tool call.
1518
1679
  The API returns each action as a separate `tool_use` block with
1519
1680
  `toolset_name: 'computer'`. The AI SDK maps every action to the toolset tool and
1520
1681
  passes the action name as `action`, so `execute` receives the same input shape
1521
- as the older computer tools:
1682
+ as the older computer tools.
1683
+
1684
+ The SDK preserves the returned member name as `action` and rejects disabled or
1685
+ unavailable members before emitting tool calls, including during streaming.
1686
+ Disabled members are also rejected by the tool's local input schema.
1687
+
1688
+ For example:
1522
1689
 
1523
1690
  ```ts
1524
1691
  const computerTool = anthropic.tools.computerToolset_20260801({
@@ -2020,7 +2187,61 @@ const result = await generateText({
2020
2187
  });
2021
2188
  ```
2022
2189
 
2023
- To change a tool's definition, remove the old definition at the end of one request, then carry the conversation forward with the updated definition in `tools` on the next request.
2190
+ #### Defining Tools by Value
2191
+
2192
+ A `tool_addition` can also define the tool by value with `tool`, in the same shape as an entry of the `tools` option. The tool does not need to be declared in `tools` up front, which lets you introduce tools that did not exist when the conversation started, for example after an MCP server connects. Defining a tool under an existing name replaces the earlier definition from that point on, so this also changes a tool's schema mid-conversation. The required `inline-tools-2026-09-15` beta header is added automatically.
2193
+
2194
+ ```ts
2195
+ import { anthropic } from '@ai-sdk/anthropic';
2196
+ import { generateText } from 'ai';
2197
+
2198
+ const result = await generateText({
2199
+ model: anthropic('claude-opus-4-8'),
2200
+ // required for system messages inside `messages`:
2201
+ allowSystemInMessages: true,
2202
+ messages: [
2203
+ { role: 'user', content: 'What is the weather forecast for Paris?' },
2204
+ {
2205
+ role: 'system',
2206
+ content: '',
2207
+ providerOptions: {
2208
+ anthropic: {
2209
+ toolChanges: [
2210
+ {
2211
+ type: 'tool_addition',
2212
+ tool: {
2213
+ type: 'function',
2214
+ name: 'get_forecast',
2215
+ description: 'Get 5-day forecast',
2216
+ inputSchema: {
2217
+ type: 'object',
2218
+ properties: { city: { type: 'string' } },
2219
+ required: ['city'],
2220
+ },
2221
+ },
2222
+ },
2223
+ ],
2224
+ },
2225
+ },
2226
+ },
2227
+ ],
2228
+ });
2229
+ ```
2230
+
2231
+ <Note>
2232
+ A tool defined by value is only known to the model. It is not part of the
2233
+ `tools` option, so functions like `generateText` cannot execute its calls. Use
2234
+ it when you handle the tool calls yourself, or declare the tool in `tools` and
2235
+ add it by reference with `toolName` to have the AI SDK execute it.
2236
+ `inputSchema` is a plain JSON Schema object.
2237
+ </Note>
2238
+
2239
+ <Note>
2240
+ The computer use tools cannot be defined in a message. Declare them in `tools`
2241
+ and add them by reference with `toolName`. The AI SDK ignores such an addition
2242
+ and emits a warning. A `tool_removal` always references the tool by
2243
+ `toolName`.
2244
+ </Note>
2024
2245
 
2025
2246
  <Note>
2026
2247
  Tool changes are not supported on the initial system message. The AI SDK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/anthropic",
3
- "version": "4.0.97",
3
+ "version": "4.0.99",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -35,8 +35,8 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@ai-sdk/provider": "4.0.36",
39
- "@ai-sdk/provider-utils": "5.0.75"
38
+ "@ai-sdk/provider": "4.0.37",
39
+ "@ai-sdk/provider-utils": "5.0.76"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@ai-sdk/test-server": "2.0.4",
@@ -35,13 +35,26 @@ export interface AnthropicSystemMessage {
35
35
  * conversation's tool set without invalidating the prompt cache.
36
36
  *
37
37
  * Only valid inside system messages that appear in the `messages` array.
38
- * Requires the `mid-conversation-tool-changes-2026-07-01` beta.
38
+ * Changes by reference require the `mid-conversation-tool-changes-2026-07-01`
39
+ * beta. Additions by value (`tool_definition`) require the
40
+ * `inline-tools-2026-09-15` beta, which also covers changes by reference.
39
41
  */
40
- export interface AnthropicToolChangeContent {
41
- type: 'tool_addition' | 'tool_removal';
42
- tool: { type: 'tool_reference'; name: string };
43
- cache_control?: never;
44
- }
42
+ export type AnthropicToolChangeContent =
43
+ | {
44
+ type: 'tool_addition' | 'tool_removal';
45
+ tool: { type: 'tool_reference'; name: string };
46
+ cache_control?: never;
47
+ }
48
+ | {
49
+ type: 'tool_addition';
50
+ /**
51
+ * The tool definition, in the same shape as an entry of the top-level
52
+ * `tools` array. It replaces any earlier definition with the same name
53
+ * from this point on.
54
+ */
55
+ tool: { type: 'tool_definition'; definition: AnthropicTool };
56
+ cache_control?: never;
57
+ };
45
58
 
46
59
  export interface AnthropicUserMessage {
47
60
  role: 'user';
@@ -260,6 +260,12 @@ export class AnthropicBatch implements BatchV4<{
260
260
  userSuppliedBetas: new Set(explicitBatchBetas),
261
261
  },
262
262
  });
263
+ if (prepared.args.thread != null) {
264
+ throw new UnsupportedFunctionalityError({
265
+ functionality: 'message threads in batches',
266
+ message: `Anthropic Message Batches do not support message threads (request "${request.id}").`,
267
+ });
268
+ }
263
269
  if (prepared.usesJsonResponseTool) {
264
270
  throw new UnsupportedFunctionalityError({
265
271
  functionality: 'batch responseFormat JSON-tool fallback',
@@ -13,6 +13,13 @@ export const anthropicErrorDataSchema = lazySchema(() =>
13
13
  error: z.object({
14
14
  type: z.string(),
15
15
  message: z.string(),
16
+ details: z
17
+ .object({
18
+ error_code: z.string().nullish().catch(undefined),
19
+ unsupported: z.array(z.string()).nullish().catch(undefined),
20
+ })
21
+ .nullish()
22
+ .catch(undefined),
16
23
  }),
17
24
  }),
18
25
  ),
@@ -111,18 +111,44 @@ export const anthropicSystemMessageProviderOptions = lazySchema(() =>
111
111
  * initial system prompt). A system message carrying tool changes must come
112
112
  * right before an assistant message or at the end of the messages.
113
113
  *
114
- * Tools referenced by a `tool_addition` must be declared in the `tools`
115
- * option (typically with `deferLoading: true` so they are not loaded until
116
- * the addition surfaces them). The required
117
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
114
+ * A `tool_addition` either references a tool by `toolName` or defines it
115
+ * by value with `tool`:
116
+ * - By reference: the tool must be declared in the `tools` option
117
+ * (typically with `deferLoading: true` so it is not loaded until the
118
+ * addition surfaces it). The required
119
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
120
+ * automatically.
121
+ * - By value: `tool` is a function or provider tool, in the same shape as
122
+ * an entry of the `tools` option. The tool does not need to be declared
123
+ * in `tools`, and defining a tool under an existing name replaces it
124
+ * from that point on. The required `inline-tools-2026-09-15` beta is
125
+ * added automatically.
126
+ *
127
+ * A `tool_removal` always references the tool by `toolName`.
118
128
  */
119
129
  toolChanges: z
120
130
  .array(
121
- z.discriminatedUnion('type', [
131
+ z.union([
122
132
  z.object({
123
133
  type: z.literal('tool_addition'),
124
134
  toolName: z.string(),
125
135
  }),
136
+ z.object({
137
+ type: z.literal('tool_addition'),
138
+ tool: z.union([
139
+ z.looseObject({
140
+ type: z.literal('function'),
141
+ name: z.string(),
142
+ inputSchema: z.record(z.string(), z.unknown()),
143
+ }),
144
+ z.looseObject({
145
+ type: z.literal('provider'),
146
+ id: z.string(),
147
+ name: z.string(),
148
+ args: z.record(z.string(), z.unknown()),
149
+ }),
150
+ ]),
151
+ }),
126
152
  z.object({
127
153
  type: z.literal('tool_removal'),
128
154
  toolName: z.string(),
@@ -141,6 +167,21 @@ export type AnthropicSystemMessageProviderOptions = InferSchema<
141
167
  export const anthropicLanguageModelOptions = lazySchema(() =>
142
168
  zodSchema(
143
169
  z.object({
170
+ /**
171
+ * Create or continue a short-lived server-side message thread.
172
+ * On continuation, messages must contain only new messages. Keep the full
173
+ * conversation locally so it can be replayed when the thread expires.
174
+ */
175
+ thread: z
176
+ .discriminatedUnion('type', [
177
+ z.object({ type: z.literal('create') }),
178
+ z.object({
179
+ type: z.literal('continue'),
180
+ previousMessageId: z.string().min(1),
181
+ }),
182
+ ])
183
+ .optional(),
184
+
144
185
  /**
145
186
  * Whether to send reasoning to the model.
146
187
  *