@ai-sdk/amazon-bedrock 4.0.23 → 4.0.25

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/anthropic/index.js +1 -1
  3. package/dist/anthropic/index.mjs +1 -1
  4. package/dist/index.js +33 -8
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +33 -8
  7. package/dist/index.mjs.map +1 -1
  8. package/package.json +4 -3
  9. package/src/__fixtures__/bedrock-json-only-text-first.1.chunks.txt +7 -0
  10. package/src/__fixtures__/bedrock-json-other-tool.1.chunks.txt +6 -0
  11. package/src/__fixtures__/bedrock-json-other-tool.1.json +24 -0
  12. package/src/__fixtures__/bedrock-json-tool-text-then-weather-then-json.1.chunks.txt +12 -0
  13. package/src/__fixtures__/bedrock-json-tool-with-answer.1.json +29 -0
  14. package/src/__fixtures__/bedrock-json-tool.1.chunks.txt +4 -0
  15. package/src/__fixtures__/bedrock-json-tool.1.json +35 -0
  16. package/src/__fixtures__/bedrock-json-tool.2.chunks.txt +6 -0
  17. package/src/__fixtures__/bedrock-json-tool.2.json +28 -0
  18. package/src/__fixtures__/bedrock-json-tool.3.chunks.txt +7 -0
  19. package/src/__fixtures__/bedrock-json-tool.3.json +36 -0
  20. package/src/__fixtures__/bedrock-json-with-tool.1.chunks.txt +9 -0
  21. package/src/__fixtures__/bedrock-json-with-tool.1.json +41 -0
  22. package/src/__fixtures__/bedrock-json-with-tools.1.chunks.txt +12 -0
  23. package/src/__fixtures__/bedrock-json-with-tools.1.json +50 -0
  24. package/src/__fixtures__/bedrock-tool-call.1.chunks.txt +6 -0
  25. package/src/__fixtures__/bedrock-tool-call.1.json +24 -0
  26. package/src/__fixtures__/bedrock-tool-no-args.chunks.txt +8 -0
  27. package/src/__fixtures__/bedrock-tool-no-args.json +25 -0
  28. package/src/anthropic/bedrock-anthropic-fetch.test.ts +344 -0
  29. package/src/anthropic/bedrock-anthropic-fetch.ts +62 -0
  30. package/src/anthropic/bedrock-anthropic-options.ts +28 -0
  31. package/src/anthropic/bedrock-anthropic-provider.test.ts +456 -0
  32. package/src/anthropic/bedrock-anthropic-provider.ts +357 -0
  33. package/src/anthropic/index.ts +9 -0
  34. package/src/bedrock-api-types.ts +195 -0
  35. package/src/bedrock-chat-language-model.test.ts +4569 -0
  36. package/src/bedrock-chat-language-model.ts +1019 -0
  37. package/src/bedrock-chat-options.ts +114 -0
  38. package/src/bedrock-embedding-model.test.ts +148 -0
  39. package/src/bedrock-embedding-model.ts +104 -0
  40. package/src/bedrock-embedding-options.ts +24 -0
  41. package/src/bedrock-error.ts +6 -0
  42. package/src/bedrock-event-stream-decoder.ts +59 -0
  43. package/src/bedrock-event-stream-response-handler.test.ts +233 -0
  44. package/src/bedrock-event-stream-response-handler.ts +57 -0
  45. package/src/bedrock-image-model.test.ts +866 -0
  46. package/src/bedrock-image-model.ts +297 -0
  47. package/src/bedrock-image-settings.ts +6 -0
  48. package/src/bedrock-prepare-tools.ts +190 -0
  49. package/src/bedrock-provider.test.ts +457 -0
  50. package/src/bedrock-provider.ts +351 -0
  51. package/src/bedrock-sigv4-fetch.test.ts +675 -0
  52. package/src/bedrock-sigv4-fetch.ts +138 -0
  53. package/src/convert-bedrock-usage.test.ts +207 -0
  54. package/src/convert-bedrock-usage.ts +50 -0
  55. package/src/convert-to-bedrock-chat-messages.test.ts +1175 -0
  56. package/src/convert-to-bedrock-chat-messages.ts +452 -0
  57. package/src/index.ts +10 -0
  58. package/src/inject-fetch-headers.test.ts +135 -0
  59. package/src/inject-fetch-headers.ts +32 -0
  60. package/src/map-bedrock-finish-reason.ts +22 -0
  61. package/src/normalize-tool-call-id.test.ts +72 -0
  62. package/src/normalize-tool-call-id.ts +36 -0
  63. package/src/reranking/__fixtures__/bedrock-reranking.1.json +12 -0
  64. package/src/reranking/bedrock-reranking-api.ts +44 -0
  65. package/src/reranking/bedrock-reranking-model.test.ts +299 -0
  66. package/src/reranking/bedrock-reranking-model.ts +115 -0
  67. package/src/reranking/bedrock-reranking-options.ts +36 -0
  68. package/src/version.ts +6 -0
@@ -0,0 +1,351 @@
1
+ import { anthropicTools } from '@ai-sdk/anthropic/internal';
2
+ import {
3
+ EmbeddingModelV3,
4
+ ImageModelV3,
5
+ LanguageModelV3,
6
+ ProviderV3,
7
+ RerankingModelV3,
8
+ } from '@ai-sdk/provider';
9
+ import {
10
+ FetchFunction,
11
+ generateId,
12
+ loadOptionalSetting,
13
+ loadSetting,
14
+ withoutTrailingSlash,
15
+ withUserAgentSuffix,
16
+ } from '@ai-sdk/provider-utils';
17
+ import { BedrockChatLanguageModel } from './bedrock-chat-language-model';
18
+ import { BedrockChatModelId } from './bedrock-chat-options';
19
+ import { BedrockEmbeddingModel } from './bedrock-embedding-model';
20
+ import { BedrockEmbeddingModelId } from './bedrock-embedding-options';
21
+ import { BedrockImageModel } from './bedrock-image-model';
22
+ import { BedrockImageModelId } from './bedrock-image-settings';
23
+ import {
24
+ BedrockCredentials,
25
+ createApiKeyFetchFunction,
26
+ createSigV4FetchFunction,
27
+ } from './bedrock-sigv4-fetch';
28
+ import { BedrockRerankingModel } from './reranking/bedrock-reranking-model';
29
+ import { BedrockRerankingModelId } from './reranking/bedrock-reranking-options';
30
+ import { VERSION } from './version';
31
+
32
+ export interface AmazonBedrockProviderSettings {
33
+ /**
34
+ The AWS region to use for the Bedrock provider. Defaults to the value of the
35
+ `AWS_REGION` environment variable.
36
+ */
37
+ region?: string;
38
+
39
+ /**
40
+ API key for authenticating requests using Bearer token authentication.
41
+ When provided, this will be used instead of AWS SigV4 authentication.
42
+ Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
43
+
44
+ @example
45
+ ```typescript
46
+ // Using API key directly
47
+ const bedrock = createAmazonBedrock({
48
+ apiKey: 'your-api-key-here',
49
+ region: 'us-east-1'
50
+ });
51
+
52
+ // Using environment variable AWS_BEARER_TOKEN_BEDROCK
53
+ const bedrock = createAmazonBedrock({
54
+ region: 'us-east-1'
55
+ });
56
+ ```
57
+
58
+ Note: When `apiKey` is provided, it takes precedence over AWS SigV4 authentication.
59
+ If neither `apiKey` nor `AWS_BEARER_TOKEN_BEDROCK` environment variable is set,
60
+ the provider will fall back to AWS SigV4 authentication using AWS credentials.
61
+ */
62
+ apiKey?: string;
63
+
64
+ /**
65
+ The AWS access key ID to use for the Bedrock provider. Defaults to the value of the
66
+ `AWS_ACCESS_KEY_ID` environment variable.
67
+ */
68
+ accessKeyId?: string;
69
+
70
+ /**
71
+ The AWS secret access key to use for the Bedrock provider. Defaults to the value of the
72
+ `AWS_SECRET_ACCESS_KEY` environment variable.
73
+ */
74
+ secretAccessKey?: string;
75
+
76
+ /**
77
+ The AWS session token to use for the Bedrock provider. Defaults to the value of the
78
+ `AWS_SESSION_TOKEN` environment variable.
79
+ */
80
+ sessionToken?: string;
81
+
82
+ /**
83
+ Base URL for the Bedrock API calls.
84
+ */
85
+ baseURL?: string;
86
+
87
+ /**
88
+ Custom headers to include in the requests.
89
+ */
90
+ headers?: Record<string, string>;
91
+
92
+ /**
93
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
94
+ or to provide a custom fetch implementation for e.g. testing.
95
+ */
96
+ fetch?: FetchFunction;
97
+
98
+ /**
99
+ The AWS credential provider to use for the Bedrock provider to get dynamic
100
+ credentials similar to the AWS SDK. Setting a provider here will cause its
101
+ credential values to be used instead of the `accessKeyId`, `secretAccessKey`,
102
+ and `sessionToken` settings.
103
+ */
104
+ credentialProvider?: () => PromiseLike<Omit<BedrockCredentials, 'region'>>;
105
+
106
+ // for testing
107
+ generateId?: () => string;
108
+ }
109
+
110
+ export interface AmazonBedrockProvider extends ProviderV3 {
111
+ (modelId: BedrockChatModelId): LanguageModelV3;
112
+
113
+ languageModel(modelId: BedrockChatModelId): LanguageModelV3;
114
+
115
+ /**
116
+ * Creates a model for text embeddings.
117
+ */
118
+ embedding(modelId: BedrockEmbeddingModelId): EmbeddingModelV3;
119
+
120
+ /**
121
+ * Creates a model for text embeddings.
122
+ */
123
+ embeddingModel(modelId: BedrockEmbeddingModelId): EmbeddingModelV3;
124
+
125
+ /**
126
+ * @deprecated Use `embedding` instead.
127
+ */
128
+ textEmbedding(modelId: BedrockEmbeddingModelId): EmbeddingModelV3;
129
+
130
+ /**
131
+ * @deprecated Use `embeddingModel` instead.
132
+ */
133
+ textEmbeddingModel(modelId: BedrockEmbeddingModelId): EmbeddingModelV3;
134
+
135
+ /**
136
+ Creates a model for image generation.
137
+ */
138
+ image(modelId: BedrockImageModelId): ImageModelV3;
139
+
140
+ /**
141
+ Creates a model for image generation.
142
+ */
143
+ imageModel(modelId: BedrockImageModelId): ImageModelV3;
144
+
145
+ /**
146
+ * Creates a model for reranking documents.
147
+ */
148
+ reranking(modelId: BedrockRerankingModelId): RerankingModelV3;
149
+
150
+ /**
151
+ * Creates a model for reranking documents.
152
+ */
153
+ rerankingModel(modelId: BedrockRerankingModelId): RerankingModelV3;
154
+
155
+ /**
156
+ Anthropic-specific tools that can be used with Anthropic models on Bedrock.
157
+ */
158
+ tools: typeof anthropicTools;
159
+ }
160
+
161
+ /**
162
+ Create an Amazon Bedrock provider instance.
163
+ */
164
+ export function createAmazonBedrock(
165
+ options: AmazonBedrockProviderSettings = {},
166
+ ): AmazonBedrockProvider {
167
+ // Check for API key authentication first
168
+ const rawApiKey = loadOptionalSetting({
169
+ settingValue: options.apiKey,
170
+ environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',
171
+ });
172
+
173
+ // FIX 1: Validate API key to ensure proper fallback to SigV4
174
+ // Only use API key if it's a non-empty, non-whitespace string
175
+ const apiKey =
176
+ rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : undefined;
177
+
178
+ // Use API key authentication if available, otherwise fall back to SigV4
179
+ const fetchFunction = apiKey
180
+ ? createApiKeyFetchFunction(apiKey, options.fetch)
181
+ : createSigV4FetchFunction(async () => {
182
+ const region = loadSetting({
183
+ settingValue: options.region,
184
+ settingName: 'region',
185
+ environmentVariableName: 'AWS_REGION',
186
+ description: 'AWS region',
187
+ });
188
+
189
+ // If a credential provider is provided, use it to get the credentials.
190
+ if (options.credentialProvider) {
191
+ try {
192
+ return {
193
+ ...(await options.credentialProvider()),
194
+ region,
195
+ };
196
+ } catch (error) {
197
+ // Error handling for credential provider failures
198
+ const errorMessage =
199
+ error instanceof Error ? error.message : String(error);
200
+ throw new Error(
201
+ `AWS credential provider failed: ${errorMessage}. ` +
202
+ 'Please ensure your credential provider returns valid AWS credentials ' +
203
+ 'with accessKeyId and secretAccessKey properties.',
204
+ );
205
+ }
206
+ }
207
+
208
+ // Enhanced error handling for SigV4 credential loading
209
+ try {
210
+ return {
211
+ region,
212
+ accessKeyId: loadSetting({
213
+ settingValue: options.accessKeyId,
214
+ settingName: 'accessKeyId',
215
+ environmentVariableName: 'AWS_ACCESS_KEY_ID',
216
+ description: 'AWS access key ID',
217
+ }),
218
+ secretAccessKey: loadSetting({
219
+ settingValue: options.secretAccessKey,
220
+ settingName: 'secretAccessKey',
221
+ environmentVariableName: 'AWS_SECRET_ACCESS_KEY',
222
+ description: 'AWS secret access key',
223
+ }),
224
+ sessionToken: loadOptionalSetting({
225
+ settingValue: options.sessionToken,
226
+ environmentVariableName: 'AWS_SESSION_TOKEN',
227
+ }),
228
+ };
229
+ } catch (error) {
230
+ // Provide helpful error message for missing AWS credentials
231
+ const errorMessage =
232
+ error instanceof Error ? error.message : String(error);
233
+ if (
234
+ errorMessage.includes('AWS_ACCESS_KEY_ID') ||
235
+ errorMessage.includes('accessKeyId')
236
+ ) {
237
+ throw new Error(
238
+ 'AWS SigV4 authentication requires AWS credentials. Please provide either:\n' +
239
+ '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\n' +
240
+ '2. Provide accessKeyId and secretAccessKey in options\n' +
241
+ '3. Use a credentialProvider function\n' +
242
+ '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\n' +
243
+ `Original error: ${errorMessage}`,
244
+ );
245
+ }
246
+ if (
247
+ errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||
248
+ errorMessage.includes('secretAccessKey')
249
+ ) {
250
+ throw new Error(
251
+ 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +
252
+ 'Please ensure both credentials are provided.\n' +
253
+ `Original error: ${errorMessage}`,
254
+ );
255
+ }
256
+ // Re-throw other errors as-is
257
+ throw error;
258
+ }
259
+ }, options.fetch);
260
+
261
+ const getHeaders = () => {
262
+ const baseHeaders = options.headers ?? {};
263
+ return withUserAgentSuffix(baseHeaders, `ai-sdk/amazon-bedrock/${VERSION}`);
264
+ };
265
+
266
+ const getBedrockRuntimeBaseUrl = (): string =>
267
+ withoutTrailingSlash(
268
+ options.baseURL ??
269
+ `https://bedrock-runtime.${loadSetting({
270
+ settingValue: options.region,
271
+ settingName: 'region',
272
+ environmentVariableName: 'AWS_REGION',
273
+ description: 'AWS region',
274
+ })}.amazonaws.com`,
275
+ ) ?? `https://bedrock-runtime.us-east-1.amazonaws.com`;
276
+
277
+ const getBedrockAgentRuntimeBaseUrl = (): string =>
278
+ withoutTrailingSlash(
279
+ options.baseURL ??
280
+ `https://bedrock-agent-runtime.${loadSetting({
281
+ settingValue: options.region,
282
+ settingName: 'region',
283
+ environmentVariableName: 'AWS_REGION',
284
+ description: 'AWS region',
285
+ })}.amazonaws.com`,
286
+ ) ?? `https://bedrock-agent-runtime.us-west-2.amazonaws.com`;
287
+
288
+ const createChatModel = (modelId: BedrockChatModelId) =>
289
+ new BedrockChatLanguageModel(modelId, {
290
+ baseUrl: getBedrockRuntimeBaseUrl,
291
+ headers: getHeaders,
292
+ fetch: fetchFunction,
293
+ generateId,
294
+ });
295
+
296
+ const provider = function (modelId: BedrockChatModelId) {
297
+ if (new.target) {
298
+ throw new Error(
299
+ 'The Amazon Bedrock model function cannot be called with the new keyword.',
300
+ );
301
+ }
302
+
303
+ return createChatModel(modelId);
304
+ };
305
+
306
+ const createEmbeddingModel = (modelId: BedrockEmbeddingModelId) =>
307
+ new BedrockEmbeddingModel(modelId, {
308
+ baseUrl: getBedrockRuntimeBaseUrl,
309
+ headers: getHeaders,
310
+ fetch: fetchFunction,
311
+ });
312
+
313
+ const createImageModel = (modelId: BedrockImageModelId) =>
314
+ new BedrockImageModel(modelId, {
315
+ baseUrl: getBedrockRuntimeBaseUrl,
316
+ headers: getHeaders,
317
+ fetch: fetchFunction,
318
+ });
319
+
320
+ const createRerankingModel = (modelId: BedrockRerankingModelId) =>
321
+ new BedrockRerankingModel(modelId, {
322
+ baseUrl: getBedrockAgentRuntimeBaseUrl,
323
+ region: loadSetting({
324
+ settingValue: options.region,
325
+ settingName: 'region',
326
+ environmentVariableName: 'AWS_REGION',
327
+ description: 'AWS region',
328
+ }),
329
+ headers: getHeaders,
330
+ fetch: fetchFunction,
331
+ });
332
+
333
+ provider.specificationVersion = 'v3' as const;
334
+ provider.languageModel = createChatModel;
335
+ provider.embedding = createEmbeddingModel;
336
+ provider.embeddingModel = createEmbeddingModel;
337
+ provider.textEmbedding = createEmbeddingModel;
338
+ provider.textEmbeddingModel = createEmbeddingModel;
339
+ provider.image = createImageModel;
340
+ provider.imageModel = createImageModel;
341
+ provider.reranking = createRerankingModel;
342
+ provider.rerankingModel = createRerankingModel;
343
+ provider.tools = anthropicTools;
344
+
345
+ return provider;
346
+ }
347
+
348
+ /**
349
+ Default Bedrock provider instance.
350
+ */
351
+ export const bedrock = createAmazonBedrock();