@ai-sdk/anthropic 4.0.96 → 4.0.97
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 +26 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +145 -24
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +12 -3
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +143 -24
- package/dist/internal/index.js.map +1 -1
- package/docs/05-anthropic.mdx +87 -0
- package/package.json +3 -3
- package/src/anthropic-api.ts +5 -0
- package/src/anthropic-batch.ts +2 -0
- package/src/anthropic-language-model-options.ts +11 -2
- package/src/anthropic-language-model.ts +37 -3
- package/src/anthropic-message-metadata.ts +3 -0
- package/src/anthropic-model-catalog.ts +2 -0
- package/src/anthropic-prepare-tools.ts +3 -1
- package/src/anthropic-provider.ts +1 -1
- package/src/convert-to-anthropic-prompt.ts +5 -1
- package/src/files/anthropic-files-api.ts +26 -0
- package/src/files/anthropic-files.ts +217 -0
- package/src/internal/index.ts +1 -1
- package/src/anthropic-files.ts +0 -104
package/docs/05-anthropic.mdx
CHANGED
|
@@ -244,10 +244,46 @@ 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
|
+
### Streaming heartbeats
|
|
248
|
+
|
|
249
|
+
To receive typed Anthropic heartbeat events, set
|
|
250
|
+
`providerOptions.anthropic.includePings: true`. This option defaults to `false`
|
|
251
|
+
and is handled locally; it is not sent in the Anthropic request body.
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
const result = streamText({
|
|
255
|
+
model: anthropic('claude-haiku-4-5'),
|
|
256
|
+
prompt: 'Explain how rainbows form.',
|
|
257
|
+
providerOptions: { anthropic: { includePings: true } },
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
for await (const part of result.stream) {
|
|
261
|
+
if (part.type === 'ping') console.log('Provider is still connected.');
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Pings are transient stream events. They do not contain generated output, change
|
|
266
|
+
usage, reset model-output timeouts, or become response content. They are omitted
|
|
267
|
+
from text projections and UI message streams. Raw pings remain available through
|
|
268
|
+
`include.rawChunks` independently of this option. Workflow durable streams record stream parts, including
|
|
269
|
+
pings, even though pings are excluded from generated content and UI messages.
|
|
270
|
+
This option applies to the Anthropic Messages implementation (including wrappers
|
|
271
|
+
that use it); Amazon Bedrock Converse does not emit typed Anthropic pings.
|
|
272
|
+
|
|
273
|
+
Enable this option only when all normalized stream consumers support the `ping`
|
|
274
|
+
part. In particular, a Gateway server must negotiate support before forwarding
|
|
275
|
+
these parts to older SDK clients. This option does not add transport keepalives to
|
|
276
|
+
UI responses; applications can send SSE comments at their transport boundary.
|
|
277
|
+
|
|
247
278
|
### Provider options
|
|
248
279
|
|
|
249
280
|
The following optional provider options are available for Anthropic models:
|
|
250
281
|
|
|
282
|
+
- `includePings` _boolean_
|
|
283
|
+
|
|
284
|
+
Optional. Defaults to `false`. Emit typed `ping` parts during streaming without
|
|
285
|
+
enabling raw chunks. See [Streaming heartbeats](#streaming-heartbeats).
|
|
286
|
+
|
|
251
287
|
- `disableParallelToolUse` _boolean_
|
|
252
288
|
|
|
253
289
|
Optional. Disables the use of parallel tool calls. Defaults to `false`.
|
|
@@ -273,6 +309,18 @@ The following optional provider options are available for Anthropic models:
|
|
|
273
309
|
|
|
274
310
|
Optional. See [Fast Mode section](#fast-mode) for more details.
|
|
275
311
|
|
|
312
|
+
- `serviceTier` _"auto" | "standard_only"_
|
|
313
|
+
|
|
314
|
+
Optional. Selects whether to use priority capacity when available (`"auto"`)
|
|
315
|
+
or standard capacity only (`"standard_only"`), sent as `service_tier`.
|
|
316
|
+
MiniMax uses its own `"standard"` and `"priority"` values. A tier belonging
|
|
317
|
+
to another known provider is omitted with an unsupported-setting warning.
|
|
318
|
+
See [Anthropic service tiers](https://platform.claude.com/docs/en/api/service-tiers).
|
|
319
|
+
|
|
320
|
+
The applied tier, when returned by the API, is available as
|
|
321
|
+
`providerMetadata.anthropic.serviceTier` for generation, streaming and batch
|
|
322
|
+
results. The original `usage.service_tier` remains in the raw usage metadata.
|
|
323
|
+
|
|
276
324
|
- `inferenceGeo` _"us" | "global"_
|
|
277
325
|
|
|
278
326
|
Optional. See [Data Residency section](#data-residency) for more details.
|
|
@@ -2168,6 +2216,45 @@ const result = await generateText({
|
|
|
2168
2216
|
|
|
2169
2217
|
Supported file types include CSV, Excel, JSON, XML, images (JPEG, PNG, GIF, WebP), and text files.
|
|
2170
2218
|
|
|
2219
|
+
#### Managing Files
|
|
2220
|
+
|
|
2221
|
+
`anthropic.files()` also supports metadata reads, generated-file downloads, and deletion directly through its optional FilesV4 methods:
|
|
2222
|
+
|
|
2223
|
+
```ts
|
|
2224
|
+
import { anthropic } from '@ai-sdk/anthropic';
|
|
2225
|
+
import { uploadFile } from 'ai';
|
|
2226
|
+
|
|
2227
|
+
const files = anthropic.files();
|
|
2228
|
+
const { providerReference } = await uploadFile({
|
|
2229
|
+
api: files,
|
|
2230
|
+
data: { type: 'text', text: 'Notes for Claude.' },
|
|
2231
|
+
filename: 'notes.txt',
|
|
2232
|
+
});
|
|
2233
|
+
|
|
2234
|
+
try {
|
|
2235
|
+
// These optional FilesV4 operations are supported by Anthropic.
|
|
2236
|
+
const metadata = await files.getFileMetadata!({ file: providerReference });
|
|
2237
|
+
console.log(metadata.filename, metadata.mediaType, metadata.byteSize);
|
|
2238
|
+
} finally {
|
|
2239
|
+
await files.deleteFile!({ file: providerReference });
|
|
2240
|
+
}
|
|
2241
|
+
```
|
|
2242
|
+
|
|
2243
|
+
For a file generated by code execution or a skill, pass its file ID as the Anthropic provider reference:
|
|
2244
|
+
|
|
2245
|
+
```ts
|
|
2246
|
+
const generatedFile = { anthropic: 'file_generated_by_code_execution' };
|
|
2247
|
+
const metadata = await files.getFileMetadata!({ file: generatedFile });
|
|
2248
|
+
if (metadata.providerMetadata?.anthropic?.downloadable === true) {
|
|
2249
|
+
const download = await files.downloadFile!({ file: generatedFile });
|
|
2250
|
+
const bytes = await new Response(download.content).arrayBuffer();
|
|
2251
|
+
}
|
|
2252
|
+
```
|
|
2253
|
+
|
|
2254
|
+
Downloads return a `ReadableStream<Uint8Array>` and the response media type when available. Anthropic only allows downloads when `downloadable` is `true`; downloading a file you uploaded returns an API error. Metadata and deletion work for both uploaded and generated files. Returned standard metadata includes `filename`, `mediaType`, `byteSize`, `createdAt`, and `expiresAt` when available; `providerMetadata.anthropic` uses the same camelCase fields for uploads and metadata reads, including `downloadable`.
|
|
2255
|
+
|
|
2256
|
+
All operations accept `abortSignal` and per-call `headers`. The provider retains its existing Files beta header by default; per-call headers can override it. Anthropic's current Files API also supports requests without that beta, which may return additional metadata such as expiration.
|
|
2257
|
+
|
|
2171
2258
|
#### Error Handling
|
|
2172
2259
|
|
|
2173
2260
|
Code execution errors are handled differently depending on whether you're using streaming or non-streaming:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/anthropic",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.97",
|
|
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.
|
|
39
|
-
"@ai-sdk/provider-utils": "5.0.
|
|
38
|
+
"@ai-sdk/provider": "4.0.36",
|
|
39
|
+
"@ai-sdk/provider-utils": "5.0.75"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@ai-sdk/test-server": "2.0.4",
|
package/src/anthropic-api.ts
CHANGED
|
@@ -1072,12 +1072,14 @@ export const anthropicResponseSchema = lazySchema(() =>
|
|
|
1072
1072
|
),
|
|
1073
1073
|
stop_reason: z.string().nullish(),
|
|
1074
1074
|
stop_sequence: z.string().nullish(),
|
|
1075
|
+
service_tier: z.string().nullish(),
|
|
1075
1076
|
stop_details: anthropicStopDetailsSchema().nullish(),
|
|
1076
1077
|
input_transformations: z
|
|
1077
1078
|
.array(anthropicInputTransformationSchema())
|
|
1078
1079
|
.nullish(),
|
|
1079
1080
|
safeguard_results: z.array(anthropicSafeguardResultSchema()).nullish(),
|
|
1080
1081
|
usage: z.looseObject({
|
|
1082
|
+
service_tier: z.string().nullish(),
|
|
1081
1083
|
input_tokens: z.number(),
|
|
1082
1084
|
output_tokens: z.number(),
|
|
1083
1085
|
output_tokens_details: z
|
|
@@ -1156,7 +1158,9 @@ export const anthropicChunkSchema = lazySchema(() =>
|
|
|
1156
1158
|
id: z.string().nullish(),
|
|
1157
1159
|
model: z.string().nullish(),
|
|
1158
1160
|
role: z.string().nullish(),
|
|
1161
|
+
service_tier: z.string().nullish(),
|
|
1159
1162
|
usage: z.looseObject({
|
|
1163
|
+
service_tier: z.string().nullish(),
|
|
1160
1164
|
input_tokens: z.number(),
|
|
1161
1165
|
cache_creation_input_tokens: z.number().nullish(),
|
|
1162
1166
|
cache_read_input_tokens: z.number().nullish(),
|
|
@@ -1508,6 +1512,7 @@ export const anthropicChunkSchema = lazySchema(() =>
|
|
|
1508
1512
|
.nullish(),
|
|
1509
1513
|
}),
|
|
1510
1514
|
usage: z.looseObject({
|
|
1515
|
+
service_tier: z.string().nullish(),
|
|
1511
1516
|
input_tokens: z.number().nullish(),
|
|
1512
1517
|
output_tokens: z.number(),
|
|
1513
1518
|
output_tokens_details: z
|
package/src/anthropic-batch.ts
CHANGED
|
@@ -1126,10 +1126,12 @@ function anthropicCallerMetadata(
|
|
|
1126
1126
|
|
|
1127
1127
|
function convertAnthropicMessageMetadata(response: AnthropicResponse) {
|
|
1128
1128
|
const stopDetails = mapAnthropicStopDetails(response.stop_details);
|
|
1129
|
+
const serviceTier = response.usage.service_tier ?? response.service_tier;
|
|
1129
1130
|
|
|
1130
1131
|
return {
|
|
1131
1132
|
usage: response.usage as JSONObject,
|
|
1132
1133
|
stopSequence: response.stop_sequence ?? null,
|
|
1134
|
+
...(serviceTier != null ? { serviceTier } : {}),
|
|
1133
1135
|
...(stopDetails != null ? { stopDetails } : {}),
|
|
1134
1136
|
...(response.input_transformations != null
|
|
1135
1137
|
? { inputTransformations: response.input_transformations }
|
|
@@ -159,6 +159,9 @@ export const anthropicLanguageModelOptions = lazySchema(() =>
|
|
|
159
159
|
.enum(['outputFormat', 'jsonTool', 'auto'])
|
|
160
160
|
.optional(),
|
|
161
161
|
|
|
162
|
+
/** Emit typed streaming heartbeat parts. Disabled by default. */
|
|
163
|
+
includePings: z.boolean().optional(),
|
|
164
|
+
|
|
162
165
|
/**
|
|
163
166
|
* Configuration for enabling Claude's extended thinking.
|
|
164
167
|
*
|
|
@@ -344,8 +347,14 @@ export const anthropicLanguageModelOptions = lazySchema(() =>
|
|
|
344
347
|
*/
|
|
345
348
|
speed: z.enum(['fast', 'standard']).optional(),
|
|
346
349
|
|
|
347
|
-
/**
|
|
348
|
-
|
|
350
|
+
/**
|
|
351
|
+
* Request admission tier. Anthropic accepts `auto` and `standard_only`;
|
|
352
|
+
* MiniMax accepts `standard` and `priority`. Values for another known
|
|
353
|
+
* provider are omitted with an unsupported-setting warning.
|
|
354
|
+
*/
|
|
355
|
+
serviceTier: z
|
|
356
|
+
.enum(['auto', 'standard_only', 'standard', 'priority'])
|
|
357
|
+
.optional(),
|
|
349
358
|
|
|
350
359
|
/**
|
|
351
360
|
* Controls where model inference runs for this request.
|
|
@@ -466,6 +466,26 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
466
466
|
customProviderOptions ?? {},
|
|
467
467
|
);
|
|
468
468
|
|
|
469
|
+
if (anthropicOptions.serviceTier != null) {
|
|
470
|
+
const supportedTiers =
|
|
471
|
+
providerOptionsName === 'anthropic'
|
|
472
|
+
? ['auto', 'standard_only']
|
|
473
|
+
: providerOptionsName === 'minimax'
|
|
474
|
+
? ['standard', 'priority']
|
|
475
|
+
: undefined;
|
|
476
|
+
if (
|
|
477
|
+
supportedTiers != null &&
|
|
478
|
+
!supportedTiers.includes(anthropicOptions.serviceTier)
|
|
479
|
+
) {
|
|
480
|
+
warnings.push({
|
|
481
|
+
type: 'unsupported',
|
|
482
|
+
feature: 'serviceTier',
|
|
483
|
+
details: `serviceTier "${anthropicOptions.serviceTier}" is not supported by ${providerOptionsName}. Use ${supportedTiers.map(tier => `"${tier}"`).join(' or ')}.`,
|
|
484
|
+
});
|
|
485
|
+
anthropicOptions.serviceTier = undefined;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
469
489
|
const {
|
|
470
490
|
maxOutputTokens: maxOutputTokensForModel,
|
|
471
491
|
supportsStructuredOutput: modelSupportsStructuredOutput,
|
|
@@ -1190,6 +1210,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1190
1210
|
...(anthropicOptions?.anthropicBeta ?? []),
|
|
1191
1211
|
]),
|
|
1192
1212
|
usesJsonResponseTool: jsonResponseTool != null,
|
|
1213
|
+
includePings: stream === true && anthropicOptions?.includePings === true,
|
|
1193
1214
|
toolNameMapping,
|
|
1194
1215
|
providerOptionsName,
|
|
1195
1216
|
usedCustomProviderKey,
|
|
@@ -1902,10 +1923,13 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1902
1923
|
warnings,
|
|
1903
1924
|
providerMetadata: (() => {
|
|
1904
1925
|
const stopDetails = mapAnthropicStopDetails(response.stop_details);
|
|
1926
|
+
const serviceTier =
|
|
1927
|
+
response.usage.service_tier ?? response.service_tier;
|
|
1905
1928
|
|
|
1906
1929
|
const anthropicMetadata = {
|
|
1907
1930
|
usage: response.usage as JSONObject,
|
|
1908
1931
|
stopSequence: response.stop_sequence ?? null,
|
|
1932
|
+
...(serviceTier != null ? { serviceTier } : {}),
|
|
1909
1933
|
...(stopDetails != null ? { stopDetails } : {}),
|
|
1910
1934
|
...(response.input_transformations != null
|
|
1911
1935
|
? { inputTransformations: response.input_transformations }
|
|
@@ -1981,6 +2005,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
1981
2005
|
warnings,
|
|
1982
2006
|
betas,
|
|
1983
2007
|
usesJsonResponseTool,
|
|
2008
|
+
includePings,
|
|
1984
2009
|
toolNameMapping,
|
|
1985
2010
|
providerOptionsName,
|
|
1986
2011
|
usedCustomProviderKey,
|
|
@@ -2066,6 +2091,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
2066
2091
|
| null = null;
|
|
2067
2092
|
let rawUsage: JSONObject | undefined = undefined;
|
|
2068
2093
|
let stopSequence: string | null = null;
|
|
2094
|
+
let serviceTier: string | null = null;
|
|
2069
2095
|
let stopDetails: AnthropicMessageMetadata['stopDetails'] = undefined;
|
|
2070
2096
|
let inputTransformations: AnthropicMessageMetadata['inputTransformations'];
|
|
2071
2097
|
let safeguardResults: AnthropicMessageMetadata['safeguardResults'];
|
|
@@ -2144,7 +2170,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
2144
2170
|
|
|
2145
2171
|
switch (value.type) {
|
|
2146
2172
|
case 'ping': {
|
|
2147
|
-
|
|
2173
|
+
if (includePings) controller.enqueue({ type: 'ping' });
|
|
2174
|
+
return;
|
|
2148
2175
|
}
|
|
2149
2176
|
|
|
2150
2177
|
case 'content_block_start': {
|
|
@@ -3056,6 +3083,10 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
3056
3083
|
return;
|
|
3057
3084
|
}
|
|
3058
3085
|
|
|
3086
|
+
serviceTier =
|
|
3087
|
+
value.message.usage.service_tier ??
|
|
3088
|
+
value.message.service_tier ??
|
|
3089
|
+
null;
|
|
3059
3090
|
isMessageOpen = true;
|
|
3060
3091
|
activeMessageId = value.message.id;
|
|
3061
3092
|
heldBackTextByIndex.clear();
|
|
@@ -3224,6 +3255,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
3224
3255
|
safeguardResults = value.delta.safeguard_results;
|
|
3225
3256
|
}
|
|
3226
3257
|
|
|
3258
|
+
serviceTier = value.usage.service_tier ?? serviceTier;
|
|
3259
|
+
|
|
3227
3260
|
rawUsage = {
|
|
3228
3261
|
...rawUsage,
|
|
3229
3262
|
...(value.usage as JSONObject),
|
|
@@ -3239,6 +3272,7 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
3239
3272
|
const anthropicMetadata = {
|
|
3240
3273
|
usage: (rawUsage as JSONObject) ?? null,
|
|
3241
3274
|
stopSequence,
|
|
3275
|
+
...(serviceTier != null ? { serviceTier } : {}),
|
|
3242
3276
|
...(stopDetails != null ? { stopDetails } : {}),
|
|
3243
3277
|
...(inputTransformations != null
|
|
3244
3278
|
? { inputTransformations }
|
|
@@ -3407,8 +3441,8 @@ export class AnthropicLanguageModel implements LanguageModelV4 {
|
|
|
3407
3441
|
|
|
3408
3442
|
let result = await firstChunkReader.read();
|
|
3409
3443
|
|
|
3410
|
-
//
|
|
3411
|
-
|
|
3444
|
+
// Ignore transport-only parts while checking the first provider event.
|
|
3445
|
+
while (result.value?.type === 'raw' || result.value?.type === 'ping') {
|
|
3412
3446
|
result = await firstChunkReader.read();
|
|
3413
3447
|
}
|
|
3414
3448
|
|
|
@@ -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.
|
|
@@ -16,6 +16,7 @@ type AnthropicLanguageProviderOption = keyof AnthropicLanguageModelOptions;
|
|
|
16
16
|
export const anthropicProviderOptions = {
|
|
17
17
|
language: {
|
|
18
18
|
sendReasoning: { description: 'Whether to send reasoning to the model.' },
|
|
19
|
+
includePings: { description: 'Include transient ping events in streams.' },
|
|
19
20
|
structuredOutputMode: {
|
|
20
21
|
description: 'How structured outputs are generated.',
|
|
21
22
|
},
|
|
@@ -336,6 +337,7 @@ function createAnthropicLanguageModelEntry(
|
|
|
336
337
|
anthropicProviderOptions.language,
|
|
337
338
|
declared ? true : 'unknown',
|
|
338
339
|
{
|
|
340
|
+
includePings: true,
|
|
339
341
|
thinking: reasoningSupport,
|
|
340
342
|
effort: documented?.effort ?? 'unknown',
|
|
341
343
|
// Fast mode is documented for claude-opus-4-6 only.
|
|
@@ -129,7 +129,9 @@ export async function prepareTools({
|
|
|
129
129
|
: {}),
|
|
130
130
|
});
|
|
131
131
|
|
|
132
|
-
|
|
132
|
+
// Native final output does not require this beta. Only send it for
|
|
133
|
+
// providers that also support strict tools.
|
|
134
|
+
if (supportsStructuredOutput === true && supportsStrictTools === true) {
|
|
133
135
|
betas.add('structured-outputs-2025-11-13');
|
|
134
136
|
}
|
|
135
137
|
|
|
@@ -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';
|
|
@@ -750,7 +750,11 @@ export async function convertToAnthropicPrompt({
|
|
|
750
750
|
for (let j = 0; j < block.messages.length; j++) {
|
|
751
751
|
const message = block.messages[j];
|
|
752
752
|
const isLastMessage = j === block.messages.length - 1;
|
|
753
|
-
|
|
753
|
+
// Filter before calculating the last part so message cache control
|
|
754
|
+
// and assistant prefill trimming apply to content actually sent.
|
|
755
|
+
const content = message.content.filter(
|
|
756
|
+
part => part.type !== 'text' || part.text.length > 0,
|
|
757
|
+
);
|
|
754
758
|
|
|
755
759
|
for (let k = 0; k < content.length; k++) {
|
|
756
760
|
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
|
+
}
|
package/src/internal/index.ts
CHANGED