@ai-sdk/amazon-bedrock 5.0.101 → 5.0.102

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.
@@ -1,555 +1,463 @@
1
- // src/anthropic/amazon-bedrock-anthropic-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- loadOptionalSetting as loadOptionalSetting2,
7
- loadSetting,
8
- resolve,
9
- withUserAgentSuffix as withUserAgentSuffix2
10
- } from "@ai-sdk/provider-utils";
11
- import {
12
- anthropicTools,
13
- AnthropicLanguageModel
14
- } from "@ai-sdk/anthropic/internal";
15
-
16
- // src/amazon-bedrock-sigv4-fetch.ts
17
- import {
18
- combineHeaders,
19
- normalizeHeaders,
20
- withUserAgentSuffix,
21
- getRuntimeEnvironmentUserAgent
22
- } from "@ai-sdk/provider-utils";
1
+ import { NoSuchModelError } from "@ai-sdk/provider";
2
+ import { combineHeaders, convertBase64ToUint8Array, getRuntimeEnvironmentUserAgent, loadOptionalSetting, loadSetting, normalizeHeaders, resolve, safeParseJSON, withUserAgentSuffix, withoutTrailingSlash } from "@ai-sdk/provider-utils";
3
+ import { AnthropicLanguageModel, anthropicTools } from "@ai-sdk/anthropic/internal";
23
4
  import { AwsV4Signer } from "aws4fetch";
24
-
25
- // src/version.ts
26
- var VERSION = true ? "5.0.101" : "0.0.0-test";
27
-
28
- // src/amazon-bedrock-sigv4-fetch.ts
5
+ import { z } from "zod/v4";
6
+ import { EventStreamCodec } from "@smithy/eventstream-codec";
7
+ import { fromUtf8, toUtf8 } from "@smithy/util-utf8";
8
+ //#region src/version.ts
9
+ const VERSION = "5.0.102";
10
+ //#endregion
11
+ //#region src/amazon-bedrock-sigv4-fetch.ts
12
+ /**
13
+ * Creates a fetch function that applies AWS Signature Version 4 signing.
14
+ *
15
+ * @param getCredentials - Function that returns the AWS credentials to use when signing.
16
+ * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.
17
+ * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.
18
+ * @returns A FetchFunction that signs requests before passing them to the underlying fetch.
19
+ */
29
20
  function createSigV4FetchFunction(getCredentials, fetch, service = "bedrock") {
30
- return async (input, init) => {
31
- const effectiveFetch = fetch ?? globalThis.fetch;
32
- const request = input instanceof Request ? input : void 0;
33
- const originalHeaders = combineHeaders(
34
- normalizeHeaders(request?.headers),
35
- normalizeHeaders(init?.headers)
36
- );
37
- const headersWithUserAgent = withUserAgentSuffix(
38
- originalHeaders,
39
- `ai-sdk-amazon-bedrock/${VERSION}`,
40
- getRuntimeEnvironmentUserAgent()
41
- );
42
- let effectiveBody = init?.body ?? void 0;
43
- if (effectiveBody === void 0 && request && request.body !== null) {
44
- try {
45
- effectiveBody = await request.clone().text();
46
- } catch {
47
- }
48
- }
49
- const effectiveMethod = init?.method ?? request?.method;
50
- if (effectiveMethod?.toUpperCase() !== "POST" || !effectiveBody) {
51
- return effectiveFetch(input, {
52
- ...init,
53
- headers: headersWithUserAgent
54
- });
55
- }
56
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
57
- const body = prepareBodyString(effectiveBody);
58
- const credentials = await getCredentials();
59
- const signer = new AwsV4Signer({
60
- url,
61
- method: "POST",
62
- headers: Object.entries(headersWithUserAgent),
63
- body,
64
- region: credentials.region,
65
- accessKeyId: credentials.accessKeyId,
66
- secretAccessKey: credentials.secretAccessKey,
67
- sessionToken: credentials.sessionToken,
68
- service
69
- });
70
- const signingResult = await signer.sign();
71
- const signedHeaders = normalizeHeaders(signingResult.headers);
72
- const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);
73
- return effectiveFetch(input, {
74
- ...init,
75
- body,
76
- headers: combinedHeaders
77
- });
78
- };
21
+ return async (input, init) => {
22
+ const effectiveFetch = fetch ?? globalThis.fetch;
23
+ const request = input instanceof Request ? input : void 0;
24
+ const originalHeaders = combineHeaders(normalizeHeaders(request?.headers), normalizeHeaders(init?.headers));
25
+ const headersWithUserAgent = withUserAgentSuffix(originalHeaders, `ai-sdk-amazon-bedrock/${VERSION}`, getRuntimeEnvironmentUserAgent());
26
+ let effectiveBody = init?.body ?? void 0;
27
+ if (effectiveBody === void 0 && request && request.body !== null) try {
28
+ effectiveBody = await request.clone().text();
29
+ } catch {}
30
+ if ((init?.method ?? request?.method)?.toUpperCase() !== "POST" || !effectiveBody) return effectiveFetch(input, {
31
+ ...init,
32
+ headers: headersWithUserAgent
33
+ });
34
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
35
+ const body = prepareBodyString(effectiveBody);
36
+ const credentials = await getCredentials();
37
+ const signingResult = await new AwsV4Signer({
38
+ url,
39
+ method: "POST",
40
+ headers: Object.entries(headersWithUserAgent),
41
+ body,
42
+ region: credentials.region,
43
+ accessKeyId: credentials.accessKeyId,
44
+ secretAccessKey: credentials.secretAccessKey,
45
+ sessionToken: credentials.sessionToken,
46
+ service
47
+ }).sign();
48
+ const signedHeaders = normalizeHeaders(signingResult.headers);
49
+ const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);
50
+ return effectiveFetch(input, {
51
+ ...init,
52
+ body,
53
+ headers: combinedHeaders
54
+ });
55
+ };
79
56
  }
80
57
  function prepareBodyString(body) {
81
- if (typeof body === "string") {
82
- return body;
83
- } else if (body instanceof Uint8Array) {
84
- return new TextDecoder().decode(body);
85
- } else if (body instanceof ArrayBuffer) {
86
- return new TextDecoder().decode(new Uint8Array(body));
87
- } else {
88
- return JSON.stringify(body);
89
- }
58
+ if (typeof body === "string") return body;
59
+ else if (body instanceof Uint8Array) return new TextDecoder().decode(body);
60
+ else if (body instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(body));
61
+ else return JSON.stringify(body);
90
62
  }
63
+ /**
64
+ * Creates a fetch function that applies Bearer token authentication.
65
+ *
66
+ * @param apiKey - The API key to use for Bearer token authentication.
67
+ * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.
68
+ * @returns A FetchFunction that adds Authorization header with Bearer token to requests.
69
+ */
91
70
  function createApiKeyFetchFunction(apiKey, fetch) {
92
- return async (input, init) => {
93
- const effectiveFetch = fetch ?? globalThis.fetch;
94
- const originalHeaders = normalizeHeaders(init?.headers);
95
- const headersWithUserAgent = withUserAgentSuffix(
96
- originalHeaders,
97
- `ai-sdk-amazon-bedrock/${VERSION}`,
98
- getRuntimeEnvironmentUserAgent()
99
- );
100
- const finalHeaders = combineHeaders(headersWithUserAgent, {
101
- Authorization: `Bearer ${apiKey}`
102
- });
103
- return effectiveFetch(input, {
104
- ...init,
105
- headers: finalHeaders
106
- });
107
- };
71
+ return async (input, init) => {
72
+ const effectiveFetch = fetch ?? globalThis.fetch;
73
+ const originalHeaders = normalizeHeaders(init?.headers);
74
+ const headersWithUserAgent = withUserAgentSuffix(originalHeaders, `ai-sdk-amazon-bedrock/${VERSION}`, getRuntimeEnvironmentUserAgent());
75
+ const finalHeaders = combineHeaders(headersWithUserAgent, { Authorization: `Bearer ${apiKey}` });
76
+ return effectiveFetch(input, {
77
+ ...init,
78
+ headers: finalHeaders
79
+ });
80
+ };
108
81
  }
109
-
110
- // src/amazon-bedrock-anthropic-model-support.ts
82
+ //#endregion
83
+ //#region src/amazon-bedrock-anthropic-model-support.ts
111
84
  function supportsStrictTools(modelId) {
112
- return !matchesModel(modelId, MODELS_WITHOUT_STRICT_TOOL_SUPPORT);
85
+ return !matchesModel(modelId, MODELS_WITHOUT_STRICT_TOOL_SUPPORT);
113
86
  }
114
87
  function supportsNativeStructuredOutput(modelId) {
115
- return !matchesModel(
116
- modelId,
117
- MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT
118
- );
88
+ return !matchesModel(modelId, MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT);
119
89
  }
120
- var MODELS_WITHOUT_STRICT_TOOL_SUPPORT = [
121
- "claude-opus-4-7",
122
- "claude-opus-4-8",
123
- "claude-opus-5",
124
- "claude-fable-5",
125
- "claude-sonnet-5"
90
+ const MODELS_WITHOUT_STRICT_TOOL_SUPPORT = [
91
+ "claude-opus-4-7",
92
+ "claude-opus-4-8",
93
+ "claude-opus-5",
94
+ "claude-fable-5",
95
+ "claude-sonnet-5"
126
96
  ];
127
- var MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT = [
128
- ...MODELS_WITHOUT_STRICT_TOOL_SUPPORT,
129
- "claude-sonnet-4-6",
130
- "claude-haiku-4-5"
97
+ const MODELS_WITHOUT_RELIABLE_NATIVE_STRUCTURED_OUTPUT = [
98
+ ...MODELS_WITHOUT_STRICT_TOOL_SUPPORT,
99
+ "claude-sonnet-4-6",
100
+ "claude-haiku-4-5"
131
101
  ];
132
102
  function matchesModel(modelId, models) {
133
- return models.some((model) => modelId.includes(model));
103
+ return models.some((model) => modelId.includes(model));
134
104
  }
135
-
136
- // src/resolve-amazon-bedrock-base-url.ts
137
- import {
138
- loadOptionalSetting,
139
- withoutTrailingSlash
140
- } from "@ai-sdk/provider-utils";
141
- var AWS_PARTITION_DNS_SUFFIXES = [
142
- { regionPrefix: "cn-", dnsSuffix: "amazonaws.com.cn" },
143
- { regionPrefix: "us-iso-", dnsSuffix: "c2s.ic.gov" },
144
- { regionPrefix: "us-isob-", dnsSuffix: "sc2s.sgov.gov" },
145
- { regionPrefix: "eu-isoe-", dnsSuffix: "cloud.adc-e.uk" },
146
- { regionPrefix: "us-isof-", dnsSuffix: "csp.hci.ic.gov" },
147
- { regionPrefix: "eusc-", dnsSuffix: "amazonaws.eu" }
105
+ //#endregion
106
+ //#region src/resolve-amazon-bedrock-base-url.ts
107
+ const AWS_PARTITION_DNS_SUFFIXES = [
108
+ {
109
+ regionPrefix: "cn-",
110
+ dnsSuffix: "amazonaws.com.cn"
111
+ },
112
+ {
113
+ regionPrefix: "us-iso-",
114
+ dnsSuffix: "c2s.ic.gov"
115
+ },
116
+ {
117
+ regionPrefix: "us-isob-",
118
+ dnsSuffix: "sc2s.sgov.gov"
119
+ },
120
+ {
121
+ regionPrefix: "eu-isoe-",
122
+ dnsSuffix: "cloud.adc-e.uk"
123
+ },
124
+ {
125
+ regionPrefix: "us-isof-",
126
+ dnsSuffix: "csp.hci.ic.gov"
127
+ },
128
+ {
129
+ regionPrefix: "eusc-",
130
+ dnsSuffix: "amazonaws.eu"
131
+ }
148
132
  ];
149
- function resolveAmazonBedrockBaseURL({
150
- baseURL,
151
- getRegion,
152
- service,
153
- serviceEndpointUrlEnvironmentVariableName
154
- }) {
155
- const resolvedBaseURL = baseURL ?? loadOptionalSetting({
156
- settingValue: void 0,
157
- environmentVariableName: serviceEndpointUrlEnvironmentVariableName
158
- }) ?? loadOptionalSetting({
159
- settingValue: void 0,
160
- environmentVariableName: "AWS_ENDPOINT_URL"
161
- });
162
- if (resolvedBaseURL != null) {
163
- return withoutTrailingSlash(resolvedBaseURL) ?? resolvedBaseURL;
164
- }
165
- const region = getRegion();
166
- const dnsSuffix = AWS_PARTITION_DNS_SUFFIXES.find(
167
- ({ regionPrefix }) => region.startsWith(regionPrefix)
168
- )?.dnsSuffix ?? "amazonaws.com";
169
- const generatedBaseURL = `https://${service}.${region}.${dnsSuffix}`;
170
- return withoutTrailingSlash(generatedBaseURL) ?? generatedBaseURL;
133
+ function resolveAmazonBedrockBaseURL({ baseURL, getRegion, service, serviceEndpointUrlEnvironmentVariableName }) {
134
+ const resolvedBaseURL = baseURL ?? loadOptionalSetting({
135
+ settingValue: void 0,
136
+ environmentVariableName: serviceEndpointUrlEnvironmentVariableName
137
+ }) ?? loadOptionalSetting({
138
+ settingValue: void 0,
139
+ environmentVariableName: "AWS_ENDPOINT_URL"
140
+ });
141
+ if (resolvedBaseURL != null) return withoutTrailingSlash(resolvedBaseURL) ?? resolvedBaseURL;
142
+ const region = getRegion();
143
+ const generatedBaseURL = `https://${service}.${region}.${AWS_PARTITION_DNS_SUFFIXES.find(({ regionPrefix }) => region.startsWith(regionPrefix))?.dnsSuffix ?? "amazonaws.com"}`;
144
+ return withoutTrailingSlash(generatedBaseURL) ?? generatedBaseURL;
171
145
  }
172
-
173
- // src/anthropic/amazon-bedrock-anthropic-fetch.ts
174
- import {
175
- convertBase64ToUint8Array,
176
- safeParseJSON
177
- } from "@ai-sdk/provider-utils";
178
- import { z } from "zod/v4";
179
-
180
- // src/amazon-bedrock-event-stream-decoder.ts
181
- import { EventStreamCodec } from "@smithy/eventstream-codec";
182
- import { toUtf8, fromUtf8 } from "@smithy/util-utf8";
146
+ //#endregion
147
+ //#region src/amazon-bedrock-event-stream-decoder.ts
183
148
  function createAmazonBedrockEventStreamDecoder(body, processEvent) {
184
- const codec = new EventStreamCodec(toUtf8, fromUtf8);
185
- let buffer = new Uint8Array(0);
186
- const textDecoder = new TextDecoder();
187
- return body.pipeThrough(
188
- new TransformStream({
189
- async transform(chunk, controller) {
190
- const newBuffer = new Uint8Array(buffer.length + chunk.length);
191
- newBuffer.set(buffer);
192
- newBuffer.set(chunk, buffer.length);
193
- buffer = newBuffer;
194
- while (buffer.length >= 4) {
195
- const totalLength = new DataView(
196
- buffer.buffer,
197
- buffer.byteOffset,
198
- buffer.byteLength
199
- ).getUint32(0, false);
200
- if (buffer.length < totalLength) {
201
- break;
202
- }
203
- const subView = buffer.subarray(0, totalLength);
204
- const decoded = codec.decode(subView);
205
- buffer = buffer.slice(totalLength);
206
- const messageType = decoded.headers[":message-type"]?.value;
207
- const eventType = decoded.headers[":event-type"]?.value;
208
- const exceptionType = decoded.headers[":exception-type"]?.value;
209
- const data = textDecoder.decode(decoded.body);
210
- await processEvent(
211
- { messageType, eventType, exceptionType, data },
212
- controller
213
- );
214
- }
215
- },
216
- flush() {
217
- if (buffer.length > 0) {
218
- throw new Error(
219
- `Incomplete Amazon Bedrock event-stream frame: ${buffer.length} buffered bytes remain at end of stream.`
220
- );
221
- }
222
- }
223
- })
224
- );
149
+ const codec = new EventStreamCodec(toUtf8, fromUtf8);
150
+ let buffer = /* @__PURE__ */ new Uint8Array(0);
151
+ const textDecoder = new TextDecoder();
152
+ return body.pipeThrough(new TransformStream({
153
+ async transform(chunk, controller) {
154
+ const newBuffer = new Uint8Array(buffer.length + chunk.length);
155
+ newBuffer.set(buffer);
156
+ newBuffer.set(chunk, buffer.length);
157
+ buffer = newBuffer;
158
+ while (buffer.length >= 4) {
159
+ const totalLength = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getUint32(0, false);
160
+ if (buffer.length < totalLength) break;
161
+ const subView = buffer.subarray(0, totalLength);
162
+ const decoded = codec.decode(subView);
163
+ buffer = buffer.slice(totalLength);
164
+ const messageType = decoded.headers[":message-type"]?.value;
165
+ const eventType = decoded.headers[":event-type"]?.value;
166
+ const exceptionType = decoded.headers[":exception-type"]?.value;
167
+ await processEvent({
168
+ messageType,
169
+ eventType,
170
+ exceptionType,
171
+ data: textDecoder.decode(decoded.body)
172
+ }, controller);
173
+ }
174
+ },
175
+ flush() {
176
+ if (buffer.length > 0) throw new Error(`Incomplete Amazon Bedrock event-stream frame: ${buffer.length} buffered bytes remain at end of stream.`);
177
+ }
178
+ }));
225
179
  }
226
-
227
- // src/amazon-bedrock-stream-error.ts
180
+ //#endregion
181
+ //#region src/amazon-bedrock-stream-error.ts
228
182
  function getAmazonBedrockStreamErrorMetadata(type) {
229
- switch (type) {
230
- case "internalServerException":
231
- case "InternalServerException":
232
- return { statusCode: 500, isRetryable: true };
233
- case "modelStreamErrorException":
234
- case "ModelStreamErrorException":
235
- return { statusCode: 424, isRetryable: true };
236
- case "serviceUnavailableException":
237
- case "ServiceUnavailableException":
238
- return { statusCode: 503, isRetryable: true };
239
- case "throttlingException":
240
- case "ThrottlingException":
241
- return { statusCode: 429, isRetryable: true };
242
- case "validationException":
243
- case "ValidationException":
244
- return { statusCode: 400, isRetryable: false };
245
- default:
246
- return {};
247
- }
183
+ switch (type) {
184
+ case "internalServerException":
185
+ case "InternalServerException": return {
186
+ statusCode: 500,
187
+ isRetryable: true
188
+ };
189
+ case "modelStreamErrorException":
190
+ case "ModelStreamErrorException": return {
191
+ statusCode: 424,
192
+ isRetryable: true
193
+ };
194
+ case "serviceUnavailableException":
195
+ case "ServiceUnavailableException": return {
196
+ statusCode: 503,
197
+ isRetryable: true
198
+ };
199
+ case "throttlingException":
200
+ case "ThrottlingException": return {
201
+ statusCode: 429,
202
+ isRetryable: true
203
+ };
204
+ case "validationException":
205
+ case "ValidationException": return {
206
+ statusCode: 400,
207
+ isRetryable: false
208
+ };
209
+ default: return {};
210
+ }
248
211
  }
249
-
250
- // src/anthropic/amazon-bedrock-anthropic-fetch.ts
251
- var amazonBedrockErrorSchema = z.looseObject({
252
- message: z.string().optional()
253
- });
212
+ //#endregion
213
+ //#region src/anthropic/amazon-bedrock-anthropic-fetch.ts
214
+ const amazonBedrockErrorSchema = z.looseObject({ message: z.string().optional() });
254
215
  function createAmazonBedrockAnthropicFetch(baseFetch) {
255
- return async (url, options) => {
256
- const response = await baseFetch(url, options);
257
- if (!response.ok) {
258
- const text = await response.text();
259
- const parsed = await safeParseJSON({
260
- text,
261
- schema: amazonBedrockErrorSchema
262
- });
263
- const message = parsed.success && parsed.value.message ? parsed.value.message : text;
264
- const anthropicError = JSON.stringify({
265
- type: "error",
266
- error: { type: "error", message }
267
- });
268
- return new Response(anthropicError, {
269
- status: response.status,
270
- statusText: response.statusText,
271
- headers: response.headers
272
- });
273
- }
274
- const contentType = response.headers.get("content-type");
275
- if (contentType?.includes("application/vnd.amazon.eventstream") && response.body != null) {
276
- const transformedBody = transformAmazonBedrockEventStreamToSSE(
277
- response.body
278
- );
279
- return new Response(transformedBody, {
280
- status: response.status,
281
- statusText: response.statusText,
282
- headers: new Headers({
283
- ...Object.fromEntries(response.headers.entries()),
284
- "content-type": "text/event-stream"
285
- })
286
- });
287
- }
288
- return response;
289
- };
216
+ return async (url, options) => {
217
+ const response = await baseFetch(url, options);
218
+ if (!response.ok) {
219
+ const text = await response.text();
220
+ const parsed = await safeParseJSON({
221
+ text,
222
+ schema: amazonBedrockErrorSchema
223
+ });
224
+ const message = parsed.success && parsed.value.message ? parsed.value.message : text;
225
+ const anthropicError = JSON.stringify({
226
+ type: "error",
227
+ error: {
228
+ type: "error",
229
+ message
230
+ }
231
+ });
232
+ return new Response(anthropicError, {
233
+ status: response.status,
234
+ statusText: response.statusText,
235
+ headers: response.headers
236
+ });
237
+ }
238
+ if (response.headers.get("content-type")?.includes("application/vnd.amazon.eventstream") && response.body != null) {
239
+ const transformedBody = transformAmazonBedrockEventStreamToSSE(response.body);
240
+ return new Response(transformedBody, {
241
+ status: response.status,
242
+ statusText: response.statusText,
243
+ headers: new Headers({
244
+ ...Object.fromEntries(response.headers.entries()),
245
+ "content-type": "text/event-stream"
246
+ })
247
+ });
248
+ }
249
+ return response;
250
+ };
290
251
  }
291
252
  function transformAmazonBedrockEventStreamToSSE(body) {
292
- const textEncoder = new TextEncoder();
293
- return createAmazonBedrockEventStreamDecoder(
294
- body,
295
- async (event, controller) => {
296
- if (event.messageType === "event") {
297
- if (event.eventType === "chunk") {
298
- const parsed = await safeParseJSON({ text: event.data });
299
- if (!parsed.success) {
300
- controller.enqueue(textEncoder.encode(`data: ${event.data}
301
-
302
- `));
303
- return;
304
- }
305
- const bytes = parsed.value.bytes;
306
- if (bytes) {
307
- const anthropicEvent = new TextDecoder().decode(
308
- convertBase64ToUint8Array(bytes)
309
- );
310
- controller.enqueue(
311
- textEncoder.encode(`data: ${anthropicEvent}
312
-
313
- `)
314
- );
315
- } else {
316
- controller.enqueue(textEncoder.encode(`data: ${event.data}
317
-
318
- `));
319
- }
320
- } else if (event.eventType === "messageStop") {
321
- controller.enqueue(textEncoder.encode("data: [DONE]\n\n"));
322
- }
323
- } else if (event.messageType === "exception") {
324
- const parsed = await safeParseJSON({ text: event.data });
325
- const data = parsed.success ? parsed.value : event.data;
326
- const message = typeof data === "object" && data != null && typeof data.message === "string" ? data.message : event.data;
327
- const type = event.eventType ?? event.exceptionType ?? "error";
328
- const metadata = getAmazonBedrockStreamErrorMetadata(type);
329
- controller.enqueue(
330
- textEncoder.encode(
331
- `data: ${JSON.stringify({
332
- type: "error",
333
- error: {
334
- type,
335
- message,
336
- ...metadata,
337
- data
338
- }
339
- })}
340
-
341
- `
342
- )
343
- );
344
- }
345
- }
346
- );
253
+ const textEncoder = new TextEncoder();
254
+ return createAmazonBedrockEventStreamDecoder(body, async (event, controller) => {
255
+ if (event.messageType === "event") {
256
+ if (event.eventType === "chunk") {
257
+ const parsed = await safeParseJSON({ text: event.data });
258
+ if (!parsed.success) {
259
+ controller.enqueue(textEncoder.encode(`data: ${event.data}\n\n`));
260
+ return;
261
+ }
262
+ const bytes = parsed.value.bytes;
263
+ if (bytes) {
264
+ const anthropicEvent = new TextDecoder().decode(convertBase64ToUint8Array(bytes));
265
+ controller.enqueue(textEncoder.encode(`data: ${anthropicEvent}\n\n`));
266
+ } else controller.enqueue(textEncoder.encode(`data: ${event.data}\n\n`));
267
+ } else if (event.eventType === "messageStop") controller.enqueue(textEncoder.encode("data: [DONE]\n\n"));
268
+ } else if (event.messageType === "exception") {
269
+ const parsed = await safeParseJSON({ text: event.data });
270
+ const data = parsed.success ? parsed.value : event.data;
271
+ const message = typeof data === "object" && data != null && typeof data.message === "string" ? data.message : event.data;
272
+ const type = event.eventType ?? event.exceptionType ?? "error";
273
+ const metadata = getAmazonBedrockStreamErrorMetadata(type);
274
+ controller.enqueue(textEncoder.encode(`data: ${JSON.stringify({
275
+ type: "error",
276
+ error: {
277
+ type,
278
+ message,
279
+ ...metadata,
280
+ data
281
+ }
282
+ })}\n\n`));
283
+ }
284
+ });
347
285
  }
348
-
349
- // src/anthropic/amazon-bedrock-anthropic-provider.ts
350
- var BEDROCK_TOOL_VERSION_MAP = {
351
- bash_20241022: "bash_20250124",
352
- text_editor_20241022: "text_editor_20250728",
353
- computer_20241022: "computer_20250124"
354
- };
355
- var BEDROCK_TOOL_NAME_MAP = {
356
- text_editor_20250728: "str_replace_based_edit_tool"
286
+ //#endregion
287
+ //#region src/anthropic/amazon-bedrock-anthropic-provider.ts
288
+ const BEDROCK_TOOL_VERSION_MAP = {
289
+ bash_20241022: "bash_20250124",
290
+ text_editor_20241022: "text_editor_20250728",
291
+ computer_20241022: "computer_20250124"
357
292
  };
358
- var BEDROCK_TOOL_BETA_MAP = {
359
- bash_20250124: "computer-use-2025-01-24",
360
- bash_20241022: "computer-use-2024-10-22",
361
- text_editor_20250124: "computer-use-2025-01-24",
362
- text_editor_20241022: "computer-use-2024-10-22",
363
- text_editor_20250429: "computer-use-2025-01-24",
364
- text_editor_20250728: "computer-use-2025-01-24",
365
- computer_20250124: "computer-use-2025-01-24",
366
- computer_20241022: "computer-use-2024-10-22",
367
- tool_search_tool_regex_20251119: "tool-search-tool-2025-10-19",
368
- // BM25 is not currently supported on Bedrock, but including the beta flag
369
- // so that Bedrock returns a more useful error message if it's used.
370
- tool_search_tool_bm25_20251119: "tool-search-tool-2025-10-19"
293
+ const BEDROCK_TOOL_NAME_MAP = { text_editor_20250728: "str_replace_based_edit_tool" };
294
+ const BEDROCK_TOOL_BETA_MAP = {
295
+ bash_20250124: "computer-use-2025-01-24",
296
+ bash_20241022: "computer-use-2024-10-22",
297
+ text_editor_20250124: "computer-use-2025-01-24",
298
+ text_editor_20241022: "computer-use-2024-10-22",
299
+ text_editor_20250429: "computer-use-2025-01-24",
300
+ text_editor_20250728: "computer-use-2025-01-24",
301
+ computer_20250124: "computer-use-2025-01-24",
302
+ computer_20241022: "computer-use-2024-10-22",
303
+ tool_search_tool_regex_20251119: "tool-search-tool-2025-10-19",
304
+ tool_search_tool_bm25_20251119: "tool-search-tool-2025-10-19"
371
305
  };
306
+ /**
307
+ * Create an Amazon Bedrock Anthropic provider instance.
308
+ * This provider uses the native Anthropic API through Bedrock's InvokeModel endpoint,
309
+ * bypassing the Converse API for better feature compatibility.
310
+ */
372
311
  function createAmazonBedrockAnthropic(options = {}) {
373
- const rawApiKey = loadOptionalSetting2({
374
- settingValue: options.apiKey,
375
- environmentVariableName: "AWS_BEARER_TOKEN_BEDROCK"
376
- });
377
- const apiKey = rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : void 0;
378
- const baseFetchFunction = apiKey ? createApiKeyFetchFunction(apiKey, options.fetch) : createSigV4FetchFunction(async () => {
379
- const region = loadSetting({
380
- settingValue: options.region,
381
- settingName: "region",
382
- environmentVariableName: "AWS_REGION",
383
- description: "AWS region"
384
- });
385
- if (options.credentialProvider) {
386
- try {
387
- return {
388
- ...await options.credentialProvider(),
389
- region
390
- };
391
- } catch (error) {
392
- const errorMessage = error instanceof Error ? error.message : String(error);
393
- throw new Error(
394
- `AWS credential provider failed: ${errorMessage}. Please ensure your credential provider returns valid AWS credentials with accessKeyId and secretAccessKey properties.`
395
- );
396
- }
397
- }
398
- try {
399
- return {
400
- region,
401
- accessKeyId: loadSetting({
402
- settingValue: options.accessKeyId,
403
- settingName: "accessKeyId",
404
- environmentVariableName: "AWS_ACCESS_KEY_ID",
405
- description: "AWS access key ID"
406
- }),
407
- secretAccessKey: loadSetting({
408
- settingValue: options.secretAccessKey,
409
- settingName: "secretAccessKey",
410
- environmentVariableName: "AWS_SECRET_ACCESS_KEY",
411
- description: "AWS secret access key"
412
- }),
413
- sessionToken: loadOptionalSetting2({
414
- settingValue: options.sessionToken,
415
- environmentVariableName: "AWS_SESSION_TOKEN"
416
- })
417
- };
418
- } catch (error) {
419
- const errorMessage = error instanceof Error ? error.message : String(error);
420
- if (errorMessage.includes("AWS_ACCESS_KEY_ID") || errorMessage.includes("accessKeyId")) {
421
- throw new Error(
422
- `AWS SigV4 authentication requires AWS credentials. Please provide either:
312
+ const rawApiKey = loadOptionalSetting({
313
+ settingValue: options.apiKey,
314
+ environmentVariableName: "AWS_BEARER_TOKEN_BEDROCK"
315
+ });
316
+ const apiKey = rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : void 0;
317
+ const fetchFunction = createAmazonBedrockAnthropicFetch(apiKey ? createApiKeyFetchFunction(apiKey, options.fetch) : createSigV4FetchFunction(async () => {
318
+ const region = loadSetting({
319
+ settingValue: options.region,
320
+ settingName: "region",
321
+ environmentVariableName: "AWS_REGION",
322
+ description: "AWS region"
323
+ });
324
+ if (options.credentialProvider) try {
325
+ return {
326
+ ...await options.credentialProvider(),
327
+ region
328
+ };
329
+ } catch (error) {
330
+ const errorMessage = error instanceof Error ? error.message : String(error);
331
+ throw new Error(`AWS credential provider failed: ${errorMessage}. Please ensure your credential provider returns valid AWS credentials with accessKeyId and secretAccessKey properties.`);
332
+ }
333
+ try {
334
+ return {
335
+ region,
336
+ accessKeyId: loadSetting({
337
+ settingValue: options.accessKeyId,
338
+ settingName: "accessKeyId",
339
+ environmentVariableName: "AWS_ACCESS_KEY_ID",
340
+ description: "AWS access key ID"
341
+ }),
342
+ secretAccessKey: loadSetting({
343
+ settingValue: options.secretAccessKey,
344
+ settingName: "secretAccessKey",
345
+ environmentVariableName: "AWS_SECRET_ACCESS_KEY",
346
+ description: "AWS secret access key"
347
+ }),
348
+ sessionToken: loadOptionalSetting({
349
+ settingValue: options.sessionToken,
350
+ environmentVariableName: "AWS_SESSION_TOKEN"
351
+ })
352
+ };
353
+ } catch (error) {
354
+ const errorMessage = error instanceof Error ? error.message : String(error);
355
+ if (errorMessage.includes("AWS_ACCESS_KEY_ID") || errorMessage.includes("accessKeyId")) throw new Error(`AWS SigV4 authentication requires AWS credentials. Please provide either:
423
356
  1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables
424
357
  2. Provide accessKeyId and secretAccessKey in options
425
358
  3. Use a credentialProvider function
426
359
  4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option
427
- Original error: ${errorMessage}`
428
- );
429
- }
430
- if (errorMessage.includes("AWS_SECRET_ACCESS_KEY") || errorMessage.includes("secretAccessKey")) {
431
- throw new Error(
432
- `AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Please ensure both credentials are provided.
433
- Original error: ${errorMessage}`
434
- );
435
- }
436
- throw error;
437
- }
438
- }, options.fetch);
439
- const fetchFunction = createAmazonBedrockAnthropicFetch(baseFetchFunction);
440
- const getBaseURL = () => resolveAmazonBedrockBaseURL({
441
- baseURL: options.baseURL,
442
- getRegion: () => loadSetting({
443
- settingValue: options.region,
444
- settingName: "region",
445
- environmentVariableName: "AWS_REGION",
446
- description: "AWS region"
447
- }),
448
- service: "bedrock-runtime",
449
- serviceEndpointUrlEnvironmentVariableName: "AWS_ENDPOINT_URL_BEDROCK_RUNTIME"
450
- });
451
- const getHeaders = async () => {
452
- const baseHeaders = await resolve(options.headers) ?? {};
453
- return withUserAgentSuffix2(baseHeaders, `ai-sdk-amazon-bedrock/${VERSION}`);
454
- };
455
- const createChatModel = (modelId) => new AnthropicLanguageModel(modelId, {
456
- provider: "bedrock.anthropic.messages",
457
- baseURL: getBaseURL(),
458
- headers: getHeaders,
459
- fetch: fetchFunction,
460
- buildRequestUrl: (baseURL, isStreaming) => `${baseURL}/model/${encodeURIComponent(modelId)}/${isStreaming ? "invoke-with-response-stream" : "invoke"}`,
461
- transformRequestBody: (args, betas) => {
462
- const {
463
- model: _model,
464
- stream: _stream,
465
- tool_choice,
466
- thinking,
467
- tools,
468
- ...rest
469
- } = args;
470
- const transformedToolChoice = tool_choice != null ? {
471
- type: tool_choice.type,
472
- ...tool_choice.name != null ? { name: tool_choice.name } : {}
473
- } : void 0;
474
- const transformedThinking = thinking?.block_binding != null ? {
475
- ...thinking,
476
- block_binding: {
477
- mismatch_behavior: thinking.block_binding.prefix_mismatch_behavior
478
- }
479
- } : thinking;
480
- const requiredBetas = new Set(betas);
481
- const transformedTools = tools?.map(
482
- (rawTool) => {
483
- const { eager_input_streaming: eagerInputStreaming, ...tool } = rawTool;
484
- if (eagerInputStreaming === true) {
485
- requiredBetas.add("fine-grained-tool-streaming-2025-05-14");
486
- }
487
- const toolType = tool.type;
488
- if (toolType && toolType in BEDROCK_TOOL_VERSION_MAP) {
489
- const newType = BEDROCK_TOOL_VERSION_MAP[toolType];
490
- if (newType in BEDROCK_TOOL_BETA_MAP) {
491
- requiredBetas.add(BEDROCK_TOOL_BETA_MAP[newType]);
492
- }
493
- const newName = newType in BEDROCK_TOOL_NAME_MAP ? BEDROCK_TOOL_NAME_MAP[newType] : tool.name;
494
- return {
495
- ...tool,
496
- type: newType,
497
- name: newName
498
- };
499
- }
500
- if (toolType && toolType in BEDROCK_TOOL_BETA_MAP) {
501
- requiredBetas.add(BEDROCK_TOOL_BETA_MAP[toolType]);
502
- }
503
- if (toolType && toolType in BEDROCK_TOOL_NAME_MAP) {
504
- return {
505
- ...tool,
506
- name: BEDROCK_TOOL_NAME_MAP[toolType]
507
- };
508
- }
509
- return tool;
510
- }
511
- );
512
- return {
513
- ...rest,
514
- ...thinking != null ? { thinking: transformedThinking } : {},
515
- ...transformedTools != null ? { tools: transformedTools } : {},
516
- ...transformedToolChoice != null ? { tool_choice: transformedToolChoice } : {},
517
- ...requiredBetas.size > 0 ? { anthropic_beta: Array.from(requiredBetas) } : {},
518
- anthropic_version: "bedrock-2023-05-31"
519
- };
520
- },
521
- // Bedrock Anthropic doesn't support URL sources, force download and base64 conversion
522
- supportedUrls: () => ({}),
523
- supportsNativeStructuredOutput: supportsNativeStructuredOutput(modelId),
524
- supportsStrictTools: supportsStrictTools(modelId)
525
- });
526
- const provider = function(modelId) {
527
- if (new.target) {
528
- throw new Error(
529
- "The Bedrock Anthropic model function cannot be called with the new keyword."
530
- );
531
- }
532
- return createChatModel(modelId);
533
- };
534
- provider.specificationVersion = "v4";
535
- provider.languageModel = createChatModel;
536
- provider.chat = createChatModel;
537
- provider.messages = createChatModel;
538
- provider.embeddingModel = (modelId) => {
539
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
540
- };
541
- provider.textEmbeddingModel = provider.embeddingModel;
542
- provider.imageModel = (modelId) => {
543
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
544
- };
545
- provider.tools = anthropicTools;
546
- return provider;
360
+ Original error: ${errorMessage}`);
361
+ if (errorMessage.includes("AWS_SECRET_ACCESS_KEY") || errorMessage.includes("secretAccessKey")) throw new Error(`AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. Please ensure both credentials are provided.
362
+ Original error: ${errorMessage}`);
363
+ throw error;
364
+ }
365
+ }, options.fetch));
366
+ const getBaseURL = () => resolveAmazonBedrockBaseURL({
367
+ baseURL: options.baseURL,
368
+ getRegion: () => loadSetting({
369
+ settingValue: options.region,
370
+ settingName: "region",
371
+ environmentVariableName: "AWS_REGION",
372
+ description: "AWS region"
373
+ }),
374
+ service: "bedrock-runtime",
375
+ serviceEndpointUrlEnvironmentVariableName: "AWS_ENDPOINT_URL_BEDROCK_RUNTIME"
376
+ });
377
+ const getHeaders = async () => {
378
+ const baseHeaders = await resolve(options.headers) ?? {};
379
+ return withUserAgentSuffix(baseHeaders, `ai-sdk-amazon-bedrock/${VERSION}`);
380
+ };
381
+ const createChatModel = (modelId) => new AnthropicLanguageModel(modelId, {
382
+ provider: "bedrock.anthropic.messages",
383
+ baseURL: getBaseURL(),
384
+ headers: getHeaders,
385
+ fetch: fetchFunction,
386
+ buildRequestUrl: (baseURL, isStreaming) => `${baseURL}/model/${encodeURIComponent(modelId)}/${isStreaming ? "invoke-with-response-stream" : "invoke"}`,
387
+ transformRequestBody: (args, betas) => {
388
+ const { model: _model, stream: _stream, tool_choice, thinking, tools, ...rest } = args;
389
+ const transformedToolChoice = tool_choice != null ? {
390
+ type: tool_choice.type,
391
+ ...tool_choice.name != null ? { name: tool_choice.name } : {}
392
+ } : void 0;
393
+ const transformedThinking = thinking?.block_binding != null ? {
394
+ ...thinking,
395
+ block_binding: { mismatch_behavior: thinking.block_binding.prefix_mismatch_behavior }
396
+ } : thinking;
397
+ const requiredBetas = new Set(betas);
398
+ const transformedTools = tools?.map((rawTool) => {
399
+ const { eager_input_streaming: eagerInputStreaming, ...tool } = rawTool;
400
+ if (eagerInputStreaming === true) requiredBetas.add("fine-grained-tool-streaming-2025-05-14");
401
+ const toolType = tool.type;
402
+ if (toolType && toolType in BEDROCK_TOOL_VERSION_MAP) {
403
+ const newType = BEDROCK_TOOL_VERSION_MAP[toolType];
404
+ if (newType in BEDROCK_TOOL_BETA_MAP) requiredBetas.add(BEDROCK_TOOL_BETA_MAP[newType]);
405
+ const newName = newType in BEDROCK_TOOL_NAME_MAP ? BEDROCK_TOOL_NAME_MAP[newType] : tool.name;
406
+ return {
407
+ ...tool,
408
+ type: newType,
409
+ name: newName
410
+ };
411
+ }
412
+ if (toolType && toolType in BEDROCK_TOOL_BETA_MAP) requiredBetas.add(BEDROCK_TOOL_BETA_MAP[toolType]);
413
+ if (toolType && toolType in BEDROCK_TOOL_NAME_MAP) return {
414
+ ...tool,
415
+ name: BEDROCK_TOOL_NAME_MAP[toolType]
416
+ };
417
+ return tool;
418
+ });
419
+ return {
420
+ ...rest,
421
+ ...thinking != null ? { thinking: transformedThinking } : {},
422
+ ...transformedTools != null ? { tools: transformedTools } : {},
423
+ ...transformedToolChoice != null ? { tool_choice: transformedToolChoice } : {},
424
+ ...requiredBetas.size > 0 ? { anthropic_beta: Array.from(requiredBetas) } : {},
425
+ anthropic_version: "bedrock-2023-05-31"
426
+ };
427
+ },
428
+ supportedUrls: () => ({}),
429
+ supportsNativeStructuredOutput: supportsNativeStructuredOutput(modelId),
430
+ supportsStrictTools: supportsStrictTools(modelId)
431
+ });
432
+ const provider = function(modelId) {
433
+ if (new.target) throw new Error("The Bedrock Anthropic model function cannot be called with the new keyword.");
434
+ return createChatModel(modelId);
435
+ };
436
+ provider.specificationVersion = "v4";
437
+ provider.languageModel = createChatModel;
438
+ provider.chat = createChatModel;
439
+ provider.messages = createChatModel;
440
+ provider.embeddingModel = (modelId) => {
441
+ throw new NoSuchModelError({
442
+ modelId,
443
+ modelType: "embeddingModel"
444
+ });
445
+ };
446
+ provider.textEmbeddingModel = provider.embeddingModel;
447
+ provider.imageModel = (modelId) => {
448
+ throw new NoSuchModelError({
449
+ modelId,
450
+ modelType: "imageModel"
451
+ });
452
+ };
453
+ provider.tools = anthropicTools;
454
+ return provider;
547
455
  }
548
- var amazonBedrockAnthropic = createAmazonBedrockAnthropic();
549
- export {
550
- amazonBedrockAnthropic,
551
- amazonBedrockAnthropic as bedrockAnthropic,
552
- createAmazonBedrockAnthropic,
553
- createAmazonBedrockAnthropic as createBedrockAnthropic
554
- };
456
+ /**
457
+ * Default Bedrock Anthropic provider instance.
458
+ */
459
+ const amazonBedrockAnthropic = createAmazonBedrockAnthropic();
460
+ //#endregion
461
+ export { amazonBedrockAnthropic, amazonBedrockAnthropic as bedrockAnthropic, createAmazonBedrockAnthropic, createAmazonBedrockAnthropic as createBedrockAnthropic };
462
+
555
463
  //# sourceMappingURL=index.js.map