@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.
@@ -3,6 +3,8 @@ import {
3
3
  type JSONObject,
4
4
  type JSONValue,
5
5
  type LanguageModelV4FilePart,
6
+ type LanguageModelV4FunctionTool,
7
+ type LanguageModelV4ProviderTool,
6
8
  type SharedV4Warning,
7
9
  type LanguageModelV4Message,
8
10
  type LanguageModelV4Prompt,
@@ -30,6 +32,7 @@ import {
30
32
  type AnthropicPrompt,
31
33
  type AnthropicSystemMessage,
32
34
  type AnthropicTextContent,
35
+ type AnthropicTool,
33
36
  type AnthropicToolChangeContent,
34
37
  type AnthropicToolCallCaller,
35
38
  type AnthropicToolResultContent,
@@ -89,6 +92,66 @@ export type AnthropicMediaPartConverter = (
89
92
  | undefined
90
93
  >;
91
94
 
95
+ // The computer use tools cannot be defined in a message (the API rejects
96
+ // them), they must be declared in `tools` and added by reference.
97
+ function isComputerTool(
98
+ tool: LanguageModelV4FunctionTool | LanguageModelV4ProviderTool,
99
+ ): boolean {
100
+ return tool.type === 'provider' && tool.id.startsWith('anthropic.computer_');
101
+ }
102
+
103
+ /**
104
+ * Collects the tools that mid-conversation tool changes add by value, so they
105
+ * can take part in tool name mapping like the tools of the `tools` option.
106
+ * Tools that cannot be added by value are left out because they are ignored.
107
+ */
108
+ export async function getInlineToolsFromPrompt(
109
+ prompt: LanguageModelV4Prompt,
110
+ ): Promise<Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool>> {
111
+ const inlineTools: Array<
112
+ LanguageModelV4FunctionTool | LanguageModelV4ProviderTool
113
+ > = [];
114
+
115
+ for (const message of prompt) {
116
+ if (message.role !== 'system' || message.providerOptions == null) {
117
+ continue;
118
+ }
119
+
120
+ const options = await parseProviderOptions({
121
+ provider: 'anthropic',
122
+ providerOptions: message.providerOptions,
123
+ schema: anthropicSystemMessageProviderOptions,
124
+ });
125
+
126
+ for (const toolChange of options?.toolChanges ?? []) {
127
+ if ('tool' in toolChange) {
128
+ const tool = toolChange.tool as
129
+ | LanguageModelV4FunctionTool
130
+ | LanguageModelV4ProviderTool;
131
+
132
+ if (!isComputerTool(tool)) {
133
+ inlineTools.push(tool);
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ return inlineTools;
140
+ }
141
+
142
+ /**
143
+ * Converts a tool that is defined by value in a mid-conversation tool change
144
+ * into the Anthropic tool definition, the same way entries of the top-level
145
+ * `tools` option are converted.
146
+ */
147
+ export type AnthropicInlineToolConverter = (
148
+ tool: LanguageModelV4FunctionTool | LanguageModelV4ProviderTool,
149
+ ) => Promise<{
150
+ definition: AnthropicTool | undefined;
151
+ warnings: SharedV4Warning[];
152
+ betas: Set<string>;
153
+ }>;
154
+
92
155
  export async function convertToAnthropicPrompt({
93
156
  prompt,
94
157
  sendReasoning,
@@ -97,6 +160,7 @@ export async function convertToAnthropicPrompt({
97
160
  toolNameMapping,
98
161
  toolsetNames = {},
99
162
  convertMediaPart,
163
+ convertInlineTool,
100
164
  }: {
101
165
  prompt: LanguageModelV4Prompt;
102
166
  sendReasoning: boolean;
@@ -111,6 +175,12 @@ export async function convertToAnthropicPrompt({
111
175
  * serialized as toolset member calls.
112
176
  */
113
177
  toolsetNames?: Record<string, string>;
178
+
179
+ /**
180
+ * Converts tools that are added by value in mid-conversation tool changes.
181
+ * Required when the prompt contains such additions.
182
+ */
183
+ convertInlineTool?: AnthropicInlineToolConverter;
114
184
  }): Promise<{
115
185
  prompt: AnthropicPrompt;
116
186
  betas: Set<string>;
@@ -174,6 +244,7 @@ export async function convertToAnthropicPrompt({
174
244
  clearAt?: 'next_user_message';
175
245
  effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
176
246
  toolChangeCount: number;
247
+ hasInlineToolDefinition: boolean;
177
248
  }> = [];
178
249
 
179
250
  for (const { content: text, providerOptions } of block.messages) {
@@ -203,7 +274,56 @@ export async function convertToAnthropicPrompt({
203
274
  });
204
275
  }
205
276
 
277
+ let toolChangeCount = 0;
278
+ let hasInlineToolDefinition = false;
279
+
206
280
  for (const toolChange of toolChanges) {
281
+ if ('tool' in toolChange) {
282
+ if (convertInlineTool == null) {
283
+ throw new UnsupportedFunctionalityError({
284
+ functionality:
285
+ 'tool additions by value in mid-conversation tool changes',
286
+ });
287
+ }
288
+
289
+ const tool = toolChange.tool as
290
+ | LanguageModelV4FunctionTool
291
+ | LanguageModelV4ProviderTool;
292
+
293
+ if (isComputerTool(tool)) {
294
+ warnings.push({
295
+ type: 'other',
296
+ message:
297
+ `The tool '${tool.name}' cannot be added by value in a tool change. ` +
298
+ 'Declare it in the tools option and add it by reference with toolName. ' +
299
+ 'The tool change has been ignored.',
300
+ });
301
+ continue;
302
+ }
303
+
304
+ const {
305
+ definition,
306
+ warnings: toolWarnings,
307
+ betas: toolBetas,
308
+ } = await convertInlineTool(tool);
309
+ warnings.push(...toolWarnings);
310
+ for (const beta of toolBetas) {
311
+ betas.add(beta);
312
+ }
313
+
314
+ if (definition == null) {
315
+ continue;
316
+ }
317
+
318
+ content.push({
319
+ type: 'tool_addition',
320
+ tool: { type: 'tool_definition', definition },
321
+ } satisfies AnthropicToolChangeContent);
322
+ toolChangeCount++;
323
+ hasInlineToolDefinition = true;
324
+ continue;
325
+ }
326
+
207
327
  content.push({
208
328
  type: toolChange.type,
209
329
  tool: {
@@ -211,13 +331,24 @@ export async function convertToAnthropicPrompt({
211
331
  name: toolNameMapping.toProviderToolName(toolChange.toolName),
212
332
  },
213
333
  } satisfies AnthropicToolChangeContent);
334
+ toolChangeCount++;
335
+ }
336
+
337
+ // Every change was ignored and nothing else is left to send.
338
+ if (
339
+ content.length === 0 &&
340
+ systemMessageOptions?.clearAt == null &&
341
+ systemMessageOptions?.effort == null
342
+ ) {
343
+ continue;
214
344
  }
215
345
 
216
346
  convertedMessages.push({
217
347
  content,
218
348
  clearAt: systemMessageOptions?.clearAt,
219
349
  effort: systemMessageOptions?.effort,
220
- toolChangeCount: toolChanges.length,
350
+ toolChangeCount,
351
+ hasInlineToolDefinition,
221
352
  });
222
353
  }
223
354
 
@@ -285,7 +416,10 @@ export async function convertToAnthropicPrompt({
285
416
  }),
286
417
  });
287
418
 
288
- if (message.toolChangeCount > 0) {
419
+ // The inline tools beta also covers changes by reference.
420
+ if (message.hasInlineToolDefinition) {
421
+ betas.add('inline-tools-2026-09-15');
422
+ } else if (message.toolChangeCount > 0) {
289
423
  betas.add('mid-conversation-tool-changes-2026-07-01');
290
424
  }
291
425
  if (message.clearAt != null) {
@@ -750,7 +884,11 @@ export async function convertToAnthropicPrompt({
750
884
  for (let j = 0; j < block.messages.length; j++) {
751
885
  const message = block.messages[j];
752
886
  const isLastMessage = j === block.messages.length - 1;
753
- const { content } = message;
887
+ // Filter before calculating the last part so message cache control
888
+ // and assistant prefill trimming apply to content actually sent.
889
+ const content = message.content.filter(
890
+ part => part.type !== 'text' || part.text.length > 0,
891
+ );
754
892
 
755
893
  for (let k = 0; k < content.length; k++) {
756
894
  const part = content[k];
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod/v4';
2
+ import { lazySchema, zodSchema } from '@ai-sdk/provider-utils';
3
+
4
+ export const anthropicUploadFileResponseSchema = lazySchema(() =>
5
+ zodSchema(
6
+ z.object({
7
+ id: z.string(),
8
+ type: z.literal('file').nullish(),
9
+ filename: z.string().nullish(),
10
+ mime_type: z.string().nullish(),
11
+ size_bytes: z.number().nullish(),
12
+ created_at: z.string().nullish(),
13
+ downloadable: z.boolean().nullish(),
14
+ expires_at: z.string().nullish(),
15
+ }),
16
+ ),
17
+ );
18
+
19
+ export const anthropicDeleteFileResponseSchema = lazySchema(() =>
20
+ zodSchema(
21
+ z.object({
22
+ type: z.literal('file_deleted').nullish(),
23
+ id: z.string(),
24
+ }),
25
+ ),
26
+ );
@@ -0,0 +1,217 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ type FilesV4,
4
+ type FilesV4DeleteFileCallOptions,
5
+ type FilesV4DeleteFileResult,
6
+ type FilesV4UploadFileCallOptions,
7
+ type FilesV4UploadFileResult,
8
+ type SharedV4ProviderReference,
9
+ type FilesV4DownloadFileCallOptions,
10
+ type FilesV4DownloadFileResult,
11
+ type FilesV4GetFileMetadataCallOptions,
12
+ type FilesV4GetFileMetadataResult,
13
+ } from '@ai-sdk/provider';
14
+ import {
15
+ combineHeaders,
16
+ convertInlineFileDataToUint8Array,
17
+ createBinaryStreamResponseHandler,
18
+ createJsonResponseHandler,
19
+ deleteFromApi,
20
+ getFromApi,
21
+ encodePathSegment,
22
+ postFormDataToApi,
23
+ resolve,
24
+ type Resolvable,
25
+ type FetchFunction,
26
+ type InferSchema,
27
+ } from '@ai-sdk/provider-utils';
28
+ import { anthropicFailedResponseHandler } from '../anthropic-error';
29
+ import {
30
+ anthropicDeleteFileResponseSchema,
31
+ anthropicUploadFileResponseSchema,
32
+ } from './anthropic-files-api';
33
+
34
+ interface AnthropicFilesConfig {
35
+ provider: string;
36
+ baseURL: string;
37
+ headers: Resolvable<Record<string, string | undefined>>;
38
+ fetch?: FetchFunction;
39
+ }
40
+
41
+ export class AnthropicFiles implements FilesV4 {
42
+ readonly specificationVersion = 'v4';
43
+
44
+ get provider(): string {
45
+ return this.config.provider;
46
+ }
47
+
48
+ constructor(private readonly config: AnthropicFilesConfig) {}
49
+
50
+ private getFileId(file: SharedV4ProviderReference): string {
51
+ const fileId = file.anthropic;
52
+ if (fileId == null || fileId.trim() === '') {
53
+ throw new InvalidArgumentError({
54
+ argument: 'file',
55
+ message: "file reference is missing an 'anthropic' file id.",
56
+ });
57
+ }
58
+ return fileId;
59
+ }
60
+
61
+ private async getHeaders(
62
+ headers: Record<string, string | undefined> | undefined,
63
+ ): Promise<Record<string, string | undefined>> {
64
+ return combineHeaders(
65
+ await resolve(this.config.headers),
66
+ { 'anthropic-beta': 'files-api-2025-04-14' },
67
+ headers,
68
+ );
69
+ }
70
+
71
+ async uploadFile({
72
+ data,
73
+ mediaType,
74
+ filename,
75
+ abortSignal,
76
+ headers,
77
+ }: FilesV4UploadFileCallOptions): Promise<FilesV4UploadFileResult> {
78
+ const fileBytes = convertInlineFileDataToUint8Array(data);
79
+
80
+ const blob = new Blob([fileBytes as Uint8Array<ArrayBuffer>], {
81
+ type: mediaType,
82
+ });
83
+
84
+ const formData = new FormData();
85
+ if (filename != null) {
86
+ formData.append('file', blob, filename);
87
+ } else {
88
+ formData.append('file', blob);
89
+ }
90
+
91
+ const { value: response } = await postFormDataToApi({
92
+ url: `${this.config.baseURL}/files`,
93
+ headers: await this.getHeaders(headers),
94
+ formData,
95
+ failedResponseHandler: anthropicFailedResponseHandler,
96
+ successfulResponseHandler: createJsonResponseHandler(
97
+ anthropicUploadFileResponseSchema,
98
+ ),
99
+ abortSignal,
100
+ fetch: this.config.fetch,
101
+ });
102
+
103
+ return {
104
+ warnings: [],
105
+ providerReference: { anthropic: response.id },
106
+ mediaType: response.mime_type ?? mediaType,
107
+ filename: response.filename ?? filename,
108
+ byteSize: response.size_bytes ?? undefined,
109
+ createdAt:
110
+ response.created_at != null ? new Date(response.created_at) : undefined,
111
+ expiresAt:
112
+ response.expires_at != null ? new Date(response.expires_at) : undefined,
113
+ providerMetadata: { anthropic: this.toFileMetadata(response) },
114
+ };
115
+ }
116
+
117
+ async deleteFile({
118
+ file,
119
+ abortSignal,
120
+ headers,
121
+ }: FilesV4DeleteFileCallOptions): Promise<FilesV4DeleteFileResult> {
122
+ const fileId = this.getFileId(file);
123
+ const { value: response } = await deleteFromApi({
124
+ url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}`,
125
+ headers: await this.getHeaders(headers),
126
+ abortSignal,
127
+ fetch: this.config.fetch,
128
+ failedResponseHandler: anthropicFailedResponseHandler,
129
+ successfulResponseHandler: createJsonResponseHandler(
130
+ anthropicDeleteFileResponseSchema,
131
+ ),
132
+ });
133
+ return {
134
+ warnings: [],
135
+ providerReference: { anthropic: response.id },
136
+ deleted: true,
137
+ };
138
+ }
139
+
140
+ async getFileMetadata({
141
+ file,
142
+ abortSignal,
143
+ headers,
144
+ }: FilesV4GetFileMetadataCallOptions): Promise<FilesV4GetFileMetadataResult> {
145
+ const fileId = this.getFileId(file);
146
+ const { value: response } = await getFromApi({
147
+ url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}`,
148
+ headers: await this.getHeaders(headers),
149
+ abortSignal,
150
+ fetch: this.config.fetch,
151
+ failedResponseHandler: anthropicFailedResponseHandler,
152
+ successfulResponseHandler: createJsonResponseHandler(
153
+ anthropicUploadFileResponseSchema,
154
+ ),
155
+ validateUrl: false,
156
+ });
157
+
158
+ return {
159
+ warnings: [],
160
+ providerReference: { anthropic: response.id },
161
+ filename: response.filename ?? undefined,
162
+ mediaType: response.mime_type ?? undefined,
163
+ byteSize: response.size_bytes ?? undefined,
164
+ createdAt:
165
+ response.created_at != null ? new Date(response.created_at) : undefined,
166
+ expiresAt:
167
+ response.expires_at != null ? new Date(response.expires_at) : undefined,
168
+ providerMetadata: { anthropic: this.toFileMetadata(response) },
169
+ };
170
+ }
171
+
172
+ private toFileMetadata(
173
+ response: InferSchema<typeof anthropicUploadFileResponseSchema>,
174
+ ) {
175
+ return {
176
+ ...(response.filename != null ? { filename: response.filename } : {}),
177
+ ...(response.mime_type != null ? { mimeType: response.mime_type } : {}),
178
+ ...(response.size_bytes != null
179
+ ? { sizeBytes: response.size_bytes }
180
+ : {}),
181
+ ...(response.created_at != null
182
+ ? { createdAt: response.created_at }
183
+ : {}),
184
+ ...(response.downloadable != null
185
+ ? { downloadable: response.downloadable }
186
+ : {}),
187
+ ...(response.expires_at != null
188
+ ? { expiresAt: response.expires_at }
189
+ : {}),
190
+ };
191
+ }
192
+
193
+ async downloadFile({
194
+ file,
195
+ abortSignal,
196
+ headers,
197
+ }: FilesV4DownloadFileCallOptions): Promise<FilesV4DownloadFileResult> {
198
+ const fileId = this.getFileId(file);
199
+ const { value: content, responseHeaders } = await getFromApi({
200
+ url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}/content`,
201
+ headers: await this.getHeaders(headers),
202
+ abortSignal,
203
+ fetch: this.config.fetch,
204
+ failedResponseHandler: anthropicFailedResponseHandler,
205
+ successfulResponseHandler: createBinaryStreamResponseHandler(),
206
+ validateUrl: false,
207
+ });
208
+
209
+ const mediaType = responseHeaders?.['content-type']?.split(';')[0].trim();
210
+
211
+ return {
212
+ warnings: [],
213
+ content,
214
+ ...(mediaType ? { mediaType } : {}),
215
+ };
216
+ }
217
+ }
@@ -33,7 +33,12 @@ export class CacheControlValidator {
33
33
  private breakpointCount = 0;
34
34
  private warnings: SharedV4Warning[] = [];
35
35
 
36
- constructor(private readonly providerOptionsName = 'anthropic') {}
36
+ constructor(
37
+ private readonly providerOptionsName = 'anthropic',
38
+ initialBreakpointCount = 0,
39
+ ) {
40
+ this.breakpointCount = initialBreakpointCount;
41
+ }
37
42
 
38
43
  getCacheControl(
39
44
  providerMetadata: SharedV4ProviderMetadata | undefined,
@@ -1,4 +1,4 @@
1
- export { AnthropicFiles } from '../anthropic-files';
1
+ export { AnthropicFiles } from '../files/anthropic-files';
2
2
  export {
3
3
  AnthropicLanguageModel,
4
4
  /** @deprecated Use `AnthropicLanguageModel` instead. */
@@ -15,3 +15,9 @@ export { prepareTools } from '../anthropic-prepare-tools';
15
15
  export { sanitizeJsonSchema } from '../sanitize-json-schema';
16
16
  export { supportsNativeStructuredOutputSchema } from '../supports-native-structured-output-schema';
17
17
  export { AnthropicSkills } from '../skills/anthropic-skills';
18
+
19
+ export {
20
+ anthropicModelCatalog,
21
+ anthropicProviderOptions,
22
+ getAnthropicLanguageModelEntry,
23
+ } from '../anthropic-model-catalog';
@@ -1,104 +0,0 @@
1
- import type {
2
- FilesV4,
3
- FilesV4UploadFileCallOptions,
4
- FilesV4UploadFileResult,
5
- } from '@ai-sdk/provider';
6
- import {
7
- combineHeaders,
8
- convertInlineFileDataToUint8Array,
9
- createJsonResponseHandler,
10
- lazySchema,
11
- postFormDataToApi,
12
- resolve,
13
- zodSchema,
14
- type FetchFunction,
15
- type Resolvable,
16
- } from '@ai-sdk/provider-utils';
17
- import { z } from 'zod/v4';
18
- import { anthropicFailedResponseHandler } from './anthropic-error';
19
-
20
- const anthropicUploadFileResponseSchema = lazySchema(() =>
21
- zodSchema(
22
- z.object({
23
- id: z.string(),
24
- type: z.literal('file'),
25
- filename: z.string(),
26
- mime_type: z.string(),
27
- size_bytes: z.number(),
28
- created_at: z.string(),
29
- downloadable: z.boolean().nullish(),
30
- }),
31
- ),
32
- );
33
-
34
- interface AnthropicFilesConfig {
35
- provider: string;
36
- baseURL: string;
37
- headers: Resolvable<Record<string, string | undefined>>;
38
- fetch?: FetchFunction;
39
- }
40
-
41
- export class AnthropicFiles implements FilesV4 {
42
- readonly specificationVersion = 'v4';
43
-
44
- get provider(): string {
45
- return this.config.provider;
46
- }
47
-
48
- constructor(private readonly config: AnthropicFilesConfig) {}
49
-
50
- async uploadFile({
51
- data,
52
- mediaType,
53
- filename,
54
- abortSignal,
55
- headers,
56
- }: FilesV4UploadFileCallOptions): Promise<FilesV4UploadFileResult> {
57
- const fileBytes = convertInlineFileDataToUint8Array(data);
58
-
59
- const blob = new Blob([fileBytes as Uint8Array<ArrayBuffer>], {
60
- type: mediaType,
61
- });
62
-
63
- const formData = new FormData();
64
- if (filename != null) {
65
- formData.append('file', blob, filename);
66
- } else {
67
- formData.append('file', blob);
68
- }
69
-
70
- const { value: response } = await postFormDataToApi({
71
- url: `${this.config.baseURL}/files`,
72
- headers: combineHeaders(
73
- await resolve(this.config.headers),
74
- { 'anthropic-beta': 'files-api-2025-04-14' },
75
- headers,
76
- ),
77
- formData,
78
- failedResponseHandler: anthropicFailedResponseHandler,
79
- successfulResponseHandler: createJsonResponseHandler(
80
- anthropicUploadFileResponseSchema,
81
- ),
82
- abortSignal,
83
- fetch: this.config.fetch,
84
- });
85
-
86
- return {
87
- warnings: [],
88
- providerReference: { anthropic: response.id },
89
- mediaType: response.mime_type ?? mediaType,
90
- filename: response.filename ?? filename,
91
- providerMetadata: {
92
- anthropic: {
93
- filename: response.filename,
94
- mimeType: response.mime_type,
95
- sizeBytes: response.size_bytes,
96
- createdAt: response.created_at,
97
- ...(response.downloadable != null
98
- ? { downloadable: response.downloadable }
99
- : {}),
100
- },
101
- },
102
- };
103
- }
104
- }