@ai-sdk/anthropic 4.0.97 → 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.
- package/CHANGELOG.md +9 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +189 -43
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +276 -9
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +184 -43
- package/dist/internal/index.js.map +1 -1
- package/docs/05-anthropic.mdx +205 -1
- package/package.json +1 -1
- package/src/anthropic-api.ts +19 -6
- package/src/anthropic-batch.ts +6 -0
- package/src/anthropic-error.ts +7 -0
- package/src/anthropic-language-model-options.ts +46 -5
- package/src/anthropic-language-model.ts +106 -12
- package/src/anthropic-model-catalog.ts +4 -0
- package/src/anthropic-prepare-tools.ts +21 -9
- package/src/anthropic-provider.ts +1 -0
- package/src/convert-to-anthropic-prompt.ts +136 -2
- package/src/get-cache-control.ts +6 -1
- package/src/internal/index.ts +6 -0
package/docs/05-anthropic.mdx
CHANGED
|
@@ -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
|
|
@@ -2020,7 +2170,61 @@ const result = await generateText({
|
|
|
2020
2170
|
});
|
|
2021
2171
|
```
|
|
2022
2172
|
|
|
2023
|
-
|
|
2173
|
+
#### Defining Tools by Value
|
|
2174
|
+
|
|
2175
|
+
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.
|
|
2176
|
+
|
|
2177
|
+
```ts
|
|
2178
|
+
import { anthropic } from '@ai-sdk/anthropic';
|
|
2179
|
+
import { generateText } from 'ai';
|
|
2180
|
+
|
|
2181
|
+
const result = await generateText({
|
|
2182
|
+
model: anthropic('claude-opus-4-8'),
|
|
2183
|
+
// required for system messages inside `messages`:
|
|
2184
|
+
allowSystemInMessages: true,
|
|
2185
|
+
messages: [
|
|
2186
|
+
{ role: 'user', content: 'What is the weather forecast for Paris?' },
|
|
2187
|
+
{
|
|
2188
|
+
role: 'system',
|
|
2189
|
+
content: '',
|
|
2190
|
+
providerOptions: {
|
|
2191
|
+
anthropic: {
|
|
2192
|
+
toolChanges: [
|
|
2193
|
+
{
|
|
2194
|
+
type: 'tool_addition',
|
|
2195
|
+
tool: {
|
|
2196
|
+
type: 'function',
|
|
2197
|
+
name: 'get_forecast',
|
|
2198
|
+
description: 'Get 5-day forecast',
|
|
2199
|
+
inputSchema: {
|
|
2200
|
+
type: 'object',
|
|
2201
|
+
properties: { city: { type: 'string' } },
|
|
2202
|
+
required: ['city'],
|
|
2203
|
+
},
|
|
2204
|
+
},
|
|
2205
|
+
},
|
|
2206
|
+
],
|
|
2207
|
+
},
|
|
2208
|
+
},
|
|
2209
|
+
},
|
|
2210
|
+
],
|
|
2211
|
+
});
|
|
2212
|
+
```
|
|
2213
|
+
|
|
2214
|
+
<Note>
|
|
2215
|
+
A tool defined by value is only known to the model. It is not part of the
|
|
2216
|
+
`tools` option, so functions like `generateText` cannot execute its calls. Use
|
|
2217
|
+
it when you handle the tool calls yourself, or declare the tool in `tools` and
|
|
2218
|
+
add it by reference with `toolName` to have the AI SDK execute it.
|
|
2219
|
+
`inputSchema` is a plain JSON Schema object.
|
|
2220
|
+
</Note>
|
|
2221
|
+
|
|
2222
|
+
<Note>
|
|
2223
|
+
The computer use tools cannot be defined in a message. Declare them in `tools`
|
|
2224
|
+
and add them by reference with `toolName`. The AI SDK ignores such an addition
|
|
2225
|
+
and emits a warning. A `tool_removal` always references the tool by
|
|
2226
|
+
`toolName`.
|
|
2227
|
+
</Note>
|
|
2024
2228
|
|
|
2025
2229
|
<Note>
|
|
2026
2230
|
Tool changes are not supported on the initial system message. The AI SDK
|
package/package.json
CHANGED
package/src/anthropic-api.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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';
|
package/src/anthropic-batch.ts
CHANGED
|
@@ -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',
|
package/src/anthropic-error.ts
CHANGED
|
@@ -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
|
-
*
|
|
115
|
-
*
|
|
116
|
-
* the
|
|
117
|
-
* `
|
|
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.
|
|
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
|
*
|
|
@@ -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. */
|
|
@@ -618,13 +622,44 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
618
622
|
});
|
|
619
623
|
}
|
|
620
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
|
+
|
|
621
647
|
// Create a shared cache control validator to track breakpoints across tools and messages
|
|
622
648
|
const cacheControlValidator = new CacheControlValidator(
|
|
623
649
|
config.cacheControlProviderOptionsName,
|
|
650
|
+
thread != null && anthropicOptions?.cacheControl != null ? 1 : 0,
|
|
624
651
|
);
|
|
625
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
|
+
|
|
626
659
|
const toolNameMapping = createToolNameMapping({
|
|
627
|
-
|
|
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 ?? [])],
|
|
628
663
|
providerToolNames: {
|
|
629
664
|
'anthropic.code_execution_20250522': 'code_execution',
|
|
630
665
|
'anthropic.code_execution_20250825': 'code_execution',
|
|
@@ -662,8 +697,59 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
662
697
|
toolNameMapping,
|
|
663
698
|
toolsetNames,
|
|
664
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
|
+
},
|
|
665
722
|
});
|
|
666
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
|
+
|
|
667
753
|
/*
|
|
668
754
|
* Map top-level `reasoning` to Anthropic thinking/effort when provider
|
|
669
755
|
* options don't already specify them. Provider options always take precedence.
|
|
@@ -917,7 +1003,16 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
917
1003
|
}),
|
|
918
1004
|
|
|
919
1005
|
// prompt:
|
|
920
|
-
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
|
+
}),
|
|
921
1016
|
messages: messagesPrompt.messages,
|
|
922
1017
|
|
|
923
1018
|
...(anthropicOptions?.safeguards &&
|
|
@@ -1150,9 +1245,6 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1150
1245
|
betas.add('server-side-fallback-2026-06-01');
|
|
1151
1246
|
}
|
|
1152
1247
|
|
|
1153
|
-
const defaultEagerInputStreaming =
|
|
1154
|
-
stream && (anthropicOptions?.toolStreaming ?? true);
|
|
1155
|
-
|
|
1156
1248
|
const {
|
|
1157
1249
|
tools: anthropicTools,
|
|
1158
1250
|
toolChoice: anthropicToolChoice,
|
|
@@ -1182,6 +1274,9 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1182
1274
|
: {
|
|
1183
1275
|
tools: tools ?? [],
|
|
1184
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,
|
|
1185
1280
|
disableParallelToolUse: anthropicOptions?.disableParallelToolUse,
|
|
1186
1281
|
cacheControlValidator,
|
|
1187
1282
|
supportsStructuredOutput,
|
|
@@ -1198,17 +1293,20 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1198
1293
|
return {
|
|
1199
1294
|
args: {
|
|
1200
1295
|
...baseArgs,
|
|
1201
|
-
tools: anthropicTools,
|
|
1296
|
+
tools: thread?.type === 'continue' ? undefined : anthropicTools,
|
|
1202
1297
|
tool_choice: anthropicToolChoice,
|
|
1203
1298
|
stream: stream === true ? true : undefined, // do not send when not streaming
|
|
1204
1299
|
},
|
|
1205
1300
|
warnings: [...warnings, ...toolWarnings, ...cacheWarnings],
|
|
1206
1301
|
betas: new Set([
|
|
1302
|
+
...(thread != null ? ['message-threads-2026-08-12'] : []),
|
|
1207
1303
|
...betas,
|
|
1208
1304
|
...toolsBetas,
|
|
1209
1305
|
...userSuppliedBetas,
|
|
1210
1306
|
...(anthropicOptions?.anthropicBeta ?? []),
|
|
1211
1307
|
]),
|
|
1308
|
+
markCodeExecutionDynamic:
|
|
1309
|
+
hasDynamicFilteringWebToolWithoutCodeExecution(anthropicTools),
|
|
1212
1310
|
usesJsonResponseTool: jsonResponseTool != null,
|
|
1213
1311
|
includePings: stream === true && anthropicOptions?.includePings === true,
|
|
1214
1312
|
toolNameMapping,
|
|
@@ -1338,6 +1436,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1338
1436
|
warnings,
|
|
1339
1437
|
betas,
|
|
1340
1438
|
usesJsonResponseTool,
|
|
1439
|
+
markCodeExecutionDynamic,
|
|
1341
1440
|
toolNameMapping,
|
|
1342
1441
|
providerOptionsName,
|
|
1343
1442
|
usedCustomProviderKey,
|
|
@@ -1355,9 +1454,6 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1355
1454
|
...this.extractCitationDocuments(options.prompt),
|
|
1356
1455
|
];
|
|
1357
1456
|
|
|
1358
|
-
const markCodeExecutionDynamic =
|
|
1359
|
-
hasDynamicFilteringWebToolWithoutCodeExecution(args.tools);
|
|
1360
|
-
|
|
1361
1457
|
const {
|
|
1362
1458
|
responseHeaders,
|
|
1363
1459
|
value: response,
|
|
@@ -2005,6 +2101,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
2005
2101
|
warnings,
|
|
2006
2102
|
betas,
|
|
2007
2103
|
usesJsonResponseTool,
|
|
2104
|
+
markCodeExecutionDynamic,
|
|
2008
2105
|
includePings,
|
|
2009
2106
|
toolNameMapping,
|
|
2010
2107
|
providerOptionsName,
|
|
@@ -2023,9 +2120,6 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
2023
2120
|
...this.extractCitationDocuments(options.prompt),
|
|
2024
2121
|
];
|
|
2025
2122
|
|
|
2026
|
-
const markCodeExecutionDynamic =
|
|
2027
|
-
hasDynamicFilteringWebToolWithoutCodeExecution(body.tools);
|
|
2028
|
-
|
|
2029
2123
|
const url = this.buildRequestUrl(true);
|
|
2030
2124
|
const { responseHeaders, value: response } = await postJsonToApi({
|
|
2031
2125
|
url,
|
|
@@ -15,6 +15,7 @@ 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.' },
|
|
19
20
|
includePings: { description: 'Include transient ping events in streams.' },
|
|
20
21
|
structuredOutputMode: {
|
|
@@ -406,3 +407,6 @@ export function getAnthropicModelCapabilities(modelId: string) {
|
|
|
406
407
|
isKnownModel: requestConfig.knownModel,
|
|
407
408
|
};
|
|
408
409
|
}
|
|
410
|
+
|
|
411
|
+
// Compatibility name also exported by the Anthropic runtime adapter.
|
|
412
|
+
export { getAnthropicModelCapabilities as getModelCapabilities };
|