@ai-sdk/amazon-bedrock 1.1.5 → 2.0.0
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 +19 -0
- package/dist/index.d.mts +27 -5
- package/dist/index.d.ts +27 -5
- package/dist/index.js +421 -123
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +433 -119
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/dist/index.mjs
CHANGED
|
@@ -2,20 +2,117 @@
|
|
|
2
2
|
import {
|
|
3
3
|
generateId,
|
|
4
4
|
loadOptionalSetting,
|
|
5
|
-
loadSetting
|
|
5
|
+
loadSetting,
|
|
6
|
+
withoutTrailingSlash
|
|
6
7
|
} from "@ai-sdk/provider-utils";
|
|
7
|
-
import {
|
|
8
|
-
BedrockRuntimeClient as BedrockRuntimeClient3
|
|
9
|
-
} from "@aws-sdk/client-bedrock-runtime";
|
|
10
8
|
|
|
11
9
|
// src/bedrock-chat-language-model.ts
|
|
12
10
|
import {
|
|
13
11
|
UnsupportedFunctionalityError as UnsupportedFunctionalityError3
|
|
14
12
|
} from "@ai-sdk/provider";
|
|
15
13
|
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
combineHeaders,
|
|
15
|
+
createJsonErrorResponseHandler,
|
|
16
|
+
createJsonResponseHandler,
|
|
17
|
+
postJsonToApi,
|
|
18
|
+
resolve
|
|
19
|
+
} from "@ai-sdk/provider-utils";
|
|
20
|
+
|
|
21
|
+
// src/bedrock-api-types.ts
|
|
22
|
+
var BEDROCK_STOP_REASONS = [
|
|
23
|
+
"stop",
|
|
24
|
+
"stop_sequence",
|
|
25
|
+
"end_turn",
|
|
26
|
+
"length",
|
|
27
|
+
"max_tokens",
|
|
28
|
+
"content-filter",
|
|
29
|
+
"content_filtered",
|
|
30
|
+
"guardrail_intervened",
|
|
31
|
+
"tool-calls",
|
|
32
|
+
"tool_use"
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
// src/bedrock-error.ts
|
|
36
|
+
import { z } from "zod";
|
|
37
|
+
var BedrockErrorSchema = z.object({
|
|
38
|
+
message: z.string(),
|
|
39
|
+
type: z.string().nullish()
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// src/bedrock-event-stream-response-handler.ts
|
|
43
|
+
import { EmptyResponseBodyError } from "@ai-sdk/provider";
|
|
44
|
+
import {
|
|
45
|
+
safeParseJSON,
|
|
46
|
+
extractResponseHeaders,
|
|
47
|
+
safeValidateTypes
|
|
48
|
+
} from "@ai-sdk/provider-utils";
|
|
49
|
+
import { EventStreamCodec } from "@smithy/eventstream-codec";
|
|
50
|
+
import { toUtf8, fromUtf8 } from "@smithy/util-utf8";
|
|
51
|
+
var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
52
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
53
|
+
if (response.body == null) {
|
|
54
|
+
throw new EmptyResponseBodyError({});
|
|
55
|
+
}
|
|
56
|
+
const codec = new EventStreamCodec(toUtf8, fromUtf8);
|
|
57
|
+
let buffer = new Uint8Array(0);
|
|
58
|
+
const textDecoder = new TextDecoder();
|
|
59
|
+
return {
|
|
60
|
+
responseHeaders,
|
|
61
|
+
value: response.body.pipeThrough(
|
|
62
|
+
new TransformStream({
|
|
63
|
+
transform(chunk, controller) {
|
|
64
|
+
var _a, _b;
|
|
65
|
+
const newBuffer = new Uint8Array(buffer.length + chunk.length);
|
|
66
|
+
newBuffer.set(buffer);
|
|
67
|
+
newBuffer.set(chunk, buffer.length);
|
|
68
|
+
buffer = newBuffer;
|
|
69
|
+
while (buffer.length >= 4) {
|
|
70
|
+
const totalLength = new DataView(
|
|
71
|
+
buffer.buffer,
|
|
72
|
+
buffer.byteOffset,
|
|
73
|
+
buffer.byteLength
|
|
74
|
+
).getUint32(0, false);
|
|
75
|
+
if (buffer.length < totalLength) {
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const subView = buffer.subarray(0, totalLength);
|
|
80
|
+
const decoded = codec.decode(subView);
|
|
81
|
+
buffer = buffer.slice(totalLength);
|
|
82
|
+
if (((_a = decoded.headers[":message-type"]) == null ? void 0 : _a.value) === "event") {
|
|
83
|
+
const data = textDecoder.decode(decoded.body);
|
|
84
|
+
const parsedDataResult = safeParseJSON({ text: data });
|
|
85
|
+
if (!parsedDataResult.success) {
|
|
86
|
+
controller.enqueue(parsedDataResult);
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
delete parsedDataResult.value.p;
|
|
90
|
+
let wrappedData = {
|
|
91
|
+
[(_b = decoded.headers[":event-type"]) == null ? void 0 : _b.value]: parsedDataResult.value
|
|
92
|
+
};
|
|
93
|
+
const validatedWrappedData = safeValidateTypes({
|
|
94
|
+
value: wrappedData,
|
|
95
|
+
schema: chunkSchema
|
|
96
|
+
});
|
|
97
|
+
if (!validatedWrappedData.success) {
|
|
98
|
+
controller.enqueue(validatedWrappedData);
|
|
99
|
+
} else {
|
|
100
|
+
controller.enqueue({
|
|
101
|
+
success: true,
|
|
102
|
+
value: validatedWrappedData.value,
|
|
103
|
+
rawValue: wrappedData
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
} catch (e) {
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
})
|
|
113
|
+
)
|
|
114
|
+
};
|
|
115
|
+
};
|
|
19
116
|
|
|
20
117
|
// src/bedrock-prepare-tools.ts
|
|
21
118
|
import {
|
|
@@ -92,7 +189,10 @@ function prepareTools(mode) {
|
|
|
92
189
|
import {
|
|
93
190
|
UnsupportedFunctionalityError as UnsupportedFunctionalityError2
|
|
94
191
|
} from "@ai-sdk/provider";
|
|
95
|
-
import {
|
|
192
|
+
import {
|
|
193
|
+
createIdGenerator,
|
|
194
|
+
convertUint8ArrayToBase64
|
|
195
|
+
} from "@ai-sdk/provider-utils";
|
|
96
196
|
var generateFileId = createIdGenerator({ prefix: "file", size: 16 });
|
|
97
197
|
function convertToBedrockChatMessages(prompt) {
|
|
98
198
|
var _a, _b, _c, _d, _e;
|
|
@@ -136,9 +236,13 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
136
236
|
}
|
|
137
237
|
bedrockContent.push({
|
|
138
238
|
image: {
|
|
139
|
-
format: (_b = (_a = part.mimeType) == null ? void 0 : _a.split(
|
|
239
|
+
format: (_b = (_a = part.mimeType) == null ? void 0 : _a.split(
|
|
240
|
+
"/"
|
|
241
|
+
)) == null ? void 0 : _b[1],
|
|
140
242
|
source: {
|
|
141
|
-
bytes: (
|
|
243
|
+
bytes: convertUint8ArrayToBase64(
|
|
244
|
+
(_c = part.image) != null ? _c : part.image
|
|
245
|
+
)
|
|
142
246
|
}
|
|
143
247
|
}
|
|
144
248
|
});
|
|
@@ -157,7 +261,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
157
261
|
)) == null ? void 0 : _e[1],
|
|
158
262
|
name: generateFileId(),
|
|
159
263
|
source: {
|
|
160
|
-
bytes:
|
|
264
|
+
bytes: part.data
|
|
161
265
|
}
|
|
162
266
|
}
|
|
163
267
|
});
|
|
@@ -302,15 +406,16 @@ function mapBedrockFinishReason(finishReason) {
|
|
|
302
406
|
}
|
|
303
407
|
|
|
304
408
|
// src/bedrock-chat-language-model.ts
|
|
409
|
+
import { z as z2 } from "zod";
|
|
305
410
|
var BedrockChatLanguageModel = class {
|
|
306
411
|
constructor(modelId, settings, config) {
|
|
412
|
+
this.modelId = modelId;
|
|
413
|
+
this.settings = settings;
|
|
414
|
+
this.config = config;
|
|
307
415
|
this.specificationVersion = "v1";
|
|
308
416
|
this.provider = "amazon-bedrock";
|
|
309
417
|
this.defaultObjectGenerationMode = "tool";
|
|
310
418
|
this.supportsImageUrls = false;
|
|
311
|
-
this.modelId = modelId;
|
|
312
|
-
this.settings = settings;
|
|
313
|
-
this.config = config;
|
|
314
419
|
}
|
|
315
420
|
getArgs({
|
|
316
421
|
mode,
|
|
@@ -327,7 +432,7 @@ var BedrockChatLanguageModel = class {
|
|
|
327
432
|
providerMetadata,
|
|
328
433
|
headers
|
|
329
434
|
}) {
|
|
330
|
-
var _a
|
|
435
|
+
var _a;
|
|
331
436
|
const type = mode.type;
|
|
332
437
|
const warnings = [];
|
|
333
438
|
if (frequencyPenalty != null) {
|
|
@@ -348,12 +453,6 @@ var BedrockChatLanguageModel = class {
|
|
|
348
453
|
setting: "seed"
|
|
349
454
|
});
|
|
350
455
|
}
|
|
351
|
-
if (headers != null) {
|
|
352
|
-
warnings.push({
|
|
353
|
-
type: "unsupported-setting",
|
|
354
|
-
setting: "headers"
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
456
|
if (topK != null) {
|
|
358
457
|
warnings.push({
|
|
359
458
|
type: "unsupported-setting",
|
|
@@ -368,18 +467,20 @@ var BedrockChatLanguageModel = class {
|
|
|
368
467
|
});
|
|
369
468
|
}
|
|
370
469
|
const { system, messages } = convertToBedrockChatMessages(prompt);
|
|
470
|
+
const inferenceConfig = {
|
|
471
|
+
...maxTokens != null && { maxTokens },
|
|
472
|
+
...temperature != null && { temperature },
|
|
473
|
+
...topP != null && { topP },
|
|
474
|
+
...stopSequences != null && { stopSequences }
|
|
475
|
+
};
|
|
371
476
|
const baseArgs = {
|
|
372
|
-
modelId: this.modelId,
|
|
373
477
|
system: system ? [{ text: system }] : void 0,
|
|
374
478
|
additionalModelRequestFields: this.settings.additionalModelRequestFields,
|
|
375
|
-
inferenceConfig
|
|
376
|
-
|
|
377
|
-
temperature,
|
|
378
|
-
topP,
|
|
379
|
-
stopSequences
|
|
479
|
+
...Object.keys(inferenceConfig).length > 0 && {
|
|
480
|
+
inferenceConfig
|
|
380
481
|
},
|
|
381
482
|
messages,
|
|
382
|
-
|
|
483
|
+
...providerMetadata == null ? void 0 : providerMetadata.bedrock
|
|
383
484
|
};
|
|
384
485
|
switch (type) {
|
|
385
486
|
case "regular": {
|
|
@@ -387,7 +488,7 @@ var BedrockChatLanguageModel = class {
|
|
|
387
488
|
return {
|
|
388
489
|
command: {
|
|
389
490
|
...baseArgs,
|
|
390
|
-
...((
|
|
491
|
+
...((_a = toolConfig.tools) == null ? void 0 : _a.length) ? { toolConfig } : {}
|
|
391
492
|
},
|
|
392
493
|
warnings: [...warnings, ...toolWarnings]
|
|
393
494
|
};
|
|
@@ -427,11 +528,29 @@ var BedrockChatLanguageModel = class {
|
|
|
427
528
|
}
|
|
428
529
|
async doGenerate(options) {
|
|
429
530
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
|
|
430
|
-
const { command, warnings } = this.getArgs(options);
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
531
|
+
const { command: args, warnings } = this.getArgs(options);
|
|
532
|
+
const url = `${this.getUrl(this.modelId)}/converse`;
|
|
533
|
+
const { value: response, responseHeaders } = await postJsonToApi({
|
|
534
|
+
url,
|
|
535
|
+
headers: combineHeaders(
|
|
536
|
+
await resolve(this.config.headers),
|
|
537
|
+
options.headers
|
|
538
|
+
),
|
|
539
|
+
body: args,
|
|
540
|
+
failedResponseHandler: createJsonErrorResponseHandler({
|
|
541
|
+
errorSchema: BedrockErrorSchema,
|
|
542
|
+
errorToMessage: (error) => {
|
|
543
|
+
var _a2;
|
|
544
|
+
return `${(_a2 = error.message) != null ? _a2 : "Unknown error"}`;
|
|
545
|
+
}
|
|
546
|
+
}),
|
|
547
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
548
|
+
BedrockResponseSchema
|
|
549
|
+
),
|
|
550
|
+
abortSignal: options.abortSignal,
|
|
551
|
+
fetch: this.config.fetch
|
|
552
|
+
});
|
|
553
|
+
const { messages: rawPrompt, ...rawSettings } = args;
|
|
435
554
|
const providerMetadata = response.trace ? { bedrock: { trace: response.trace } } : void 0;
|
|
436
555
|
return {
|
|
437
556
|
text: (_d = (_c = (_b = (_a = response.output) == null ? void 0 : _a.message) == null ? void 0 : _b.content) == null ? void 0 : _c.map((part) => {
|
|
@@ -447,48 +566,53 @@ var BedrockChatLanguageModel = class {
|
|
|
447
566
|
args: JSON.stringify((_f2 = (_e2 = part.toolUse) == null ? void 0 : _e2.input) != null ? _f2 : "")
|
|
448
567
|
};
|
|
449
568
|
}),
|
|
450
|
-
finishReason: mapBedrockFinishReason(
|
|
569
|
+
finishReason: mapBedrockFinishReason(
|
|
570
|
+
response.stopReason
|
|
571
|
+
),
|
|
451
572
|
usage: {
|
|
452
573
|
promptTokens: (_j = (_i = response.usage) == null ? void 0 : _i.inputTokens) != null ? _j : Number.NaN,
|
|
453
574
|
completionTokens: (_l = (_k = response.usage) == null ? void 0 : _k.outputTokens) != null ? _l : Number.NaN
|
|
454
575
|
},
|
|
455
576
|
rawCall: { rawPrompt, rawSettings },
|
|
577
|
+
rawResponse: { headers: responseHeaders },
|
|
456
578
|
warnings,
|
|
457
|
-
providerMetadata
|
|
579
|
+
...providerMetadata && { providerMetadata }
|
|
458
580
|
};
|
|
459
581
|
}
|
|
460
582
|
async doStream(options) {
|
|
461
|
-
const { command, warnings } = this.getArgs(options);
|
|
462
|
-
const
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
583
|
+
const { command: args, warnings } = this.getArgs(options);
|
|
584
|
+
const url = `${this.getUrl(this.modelId)}/converse-stream`;
|
|
585
|
+
const { value: response, responseHeaders } = await postJsonToApi({
|
|
586
|
+
url,
|
|
587
|
+
headers: combineHeaders(
|
|
588
|
+
await resolve(this.config.headers),
|
|
589
|
+
options.headers
|
|
590
|
+
),
|
|
591
|
+
body: args,
|
|
592
|
+
failedResponseHandler: createJsonErrorResponseHandler({
|
|
593
|
+
errorSchema: BedrockErrorSchema,
|
|
594
|
+
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
595
|
+
}),
|
|
596
|
+
successfulResponseHandler: createBedrockEventStreamResponseHandler(BedrockStreamSchema),
|
|
597
|
+
abortSignal: options.abortSignal,
|
|
598
|
+
fetch: this.config.fetch
|
|
599
|
+
});
|
|
600
|
+
const { messages: rawPrompt, ...rawSettings } = args;
|
|
466
601
|
let finishReason = "unknown";
|
|
467
602
|
let usage = {
|
|
468
603
|
promptTokens: Number.NaN,
|
|
469
604
|
completionTokens: Number.NaN
|
|
470
605
|
};
|
|
471
606
|
let providerMetadata = void 0;
|
|
472
|
-
if (!response.stream) {
|
|
473
|
-
throw new Error("No stream found");
|
|
474
|
-
}
|
|
475
|
-
const stream = new ReadableStream({
|
|
476
|
-
async start(controller) {
|
|
477
|
-
for await (const chunk of response.stream) {
|
|
478
|
-
controller.enqueue({ success: true, value: chunk });
|
|
479
|
-
}
|
|
480
|
-
controller.close();
|
|
481
|
-
}
|
|
482
|
-
});
|
|
483
607
|
const toolCallContentBlocks = {};
|
|
484
608
|
return {
|
|
485
|
-
stream:
|
|
609
|
+
stream: response.pipeThrough(
|
|
486
610
|
new TransformStream({
|
|
487
611
|
transform(chunk, controller) {
|
|
488
|
-
var _a, _b, _c, _d, _e, _f, _g
|
|
489
|
-
function enqueueError(
|
|
612
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
613
|
+
function enqueueError(bedrockError) {
|
|
490
614
|
finishReason = "error";
|
|
491
|
-
controller.enqueue({ type: "error", error });
|
|
615
|
+
controller.enqueue({ type: "error", error: bedrockError });
|
|
492
616
|
}
|
|
493
617
|
if (!chunk.success) {
|
|
494
618
|
enqueueError(chunk.error);
|
|
@@ -529,14 +653,14 @@ var BedrockChatLanguageModel = class {
|
|
|
529
653
|
};
|
|
530
654
|
}
|
|
531
655
|
}
|
|
532
|
-
if ((
|
|
656
|
+
if (((_e = value.contentBlockDelta) == null ? void 0 : _e.delta) && "text" in value.contentBlockDelta.delta && value.contentBlockDelta.delta.text) {
|
|
533
657
|
controller.enqueue({
|
|
534
658
|
type: "text-delta",
|
|
535
659
|
textDelta: value.contentBlockDelta.delta.text
|
|
536
660
|
});
|
|
537
661
|
}
|
|
538
662
|
const contentBlockStart = value.contentBlockStart;
|
|
539
|
-
if (((
|
|
663
|
+
if (((_f = contentBlockStart == null ? void 0 : contentBlockStart.start) == null ? void 0 : _f.toolUse) != null) {
|
|
540
664
|
const toolUse = contentBlockStart.start.toolUse;
|
|
541
665
|
toolCallContentBlocks[contentBlockStart.contentBlockIndex] = {
|
|
542
666
|
toolCallId: toolUse.toolUseId,
|
|
@@ -545,9 +669,9 @@ var BedrockChatLanguageModel = class {
|
|
|
545
669
|
};
|
|
546
670
|
}
|
|
547
671
|
const contentBlockDelta = value.contentBlockDelta;
|
|
548
|
-
if ((
|
|
672
|
+
if ((contentBlockDelta == null ? void 0 : contentBlockDelta.delta) && "toolUse" in contentBlockDelta.delta && contentBlockDelta.delta.toolUse) {
|
|
549
673
|
const contentBlock = toolCallContentBlocks[contentBlockDelta.contentBlockIndex];
|
|
550
|
-
const delta = (
|
|
674
|
+
const delta = (_g = contentBlockDelta.delta.toolUse.input) != null ? _g : "";
|
|
551
675
|
controller.enqueue({
|
|
552
676
|
type: "tool-call-delta",
|
|
553
677
|
toolCallType: "function",
|
|
@@ -578,99 +702,284 @@ var BedrockChatLanguageModel = class {
|
|
|
578
702
|
type: "finish",
|
|
579
703
|
finishReason,
|
|
580
704
|
usage,
|
|
581
|
-
providerMetadata
|
|
705
|
+
...providerMetadata && { providerMetadata }
|
|
582
706
|
});
|
|
583
707
|
}
|
|
584
708
|
})
|
|
585
709
|
),
|
|
586
710
|
rawCall: { rawPrompt, rawSettings },
|
|
711
|
+
rawResponse: { headers: responseHeaders },
|
|
587
712
|
warnings
|
|
588
713
|
};
|
|
589
714
|
}
|
|
715
|
+
getUrl(modelId) {
|
|
716
|
+
const encodedModelId = encodeURIComponent(modelId);
|
|
717
|
+
return `${this.config.baseUrl()}/model/${encodedModelId}`;
|
|
718
|
+
}
|
|
590
719
|
};
|
|
720
|
+
var BedrockStopReasonSchema = z2.union([
|
|
721
|
+
z2.enum(BEDROCK_STOP_REASONS),
|
|
722
|
+
z2.string()
|
|
723
|
+
]);
|
|
724
|
+
var BedrockToolUseSchema = z2.object({
|
|
725
|
+
toolUseId: z2.string(),
|
|
726
|
+
name: z2.string(),
|
|
727
|
+
input: z2.unknown()
|
|
728
|
+
});
|
|
729
|
+
var BedrockResponseSchema = z2.object({
|
|
730
|
+
metrics: z2.object({
|
|
731
|
+
latencyMs: z2.number()
|
|
732
|
+
}).nullish(),
|
|
733
|
+
output: z2.object({
|
|
734
|
+
message: z2.object({
|
|
735
|
+
content: z2.array(
|
|
736
|
+
z2.object({
|
|
737
|
+
text: z2.string().nullish(),
|
|
738
|
+
toolUse: BedrockToolUseSchema.nullish()
|
|
739
|
+
})
|
|
740
|
+
),
|
|
741
|
+
role: z2.string()
|
|
742
|
+
})
|
|
743
|
+
}),
|
|
744
|
+
stopReason: BedrockStopReasonSchema,
|
|
745
|
+
trace: z2.unknown().nullish(),
|
|
746
|
+
usage: z2.object({
|
|
747
|
+
inputTokens: z2.number(),
|
|
748
|
+
outputTokens: z2.number(),
|
|
749
|
+
totalTokens: z2.number()
|
|
750
|
+
})
|
|
751
|
+
});
|
|
752
|
+
var BedrockStreamSchema = z2.object({
|
|
753
|
+
contentBlockDelta: z2.object({
|
|
754
|
+
contentBlockIndex: z2.number(),
|
|
755
|
+
delta: z2.union([
|
|
756
|
+
z2.object({ text: z2.string() }),
|
|
757
|
+
z2.object({ toolUse: z2.object({ input: z2.string() }) })
|
|
758
|
+
]).nullish()
|
|
759
|
+
}).nullish(),
|
|
760
|
+
contentBlockStart: z2.object({
|
|
761
|
+
contentBlockIndex: z2.number(),
|
|
762
|
+
start: z2.object({
|
|
763
|
+
toolUse: BedrockToolUseSchema.nullish()
|
|
764
|
+
}).nullish()
|
|
765
|
+
}).nullish(),
|
|
766
|
+
contentBlockStop: z2.object({
|
|
767
|
+
contentBlockIndex: z2.number()
|
|
768
|
+
}).nullish(),
|
|
769
|
+
internalServerException: z2.record(z2.unknown()).nullish(),
|
|
770
|
+
messageStop: z2.object({
|
|
771
|
+
additionalModelResponseFields: z2.record(z2.unknown()).nullish(),
|
|
772
|
+
stopReason: BedrockStopReasonSchema
|
|
773
|
+
}).nullish(),
|
|
774
|
+
metadata: z2.object({
|
|
775
|
+
trace: z2.unknown().nullish(),
|
|
776
|
+
usage: z2.object({
|
|
777
|
+
inputTokens: z2.number(),
|
|
778
|
+
outputTokens: z2.number()
|
|
779
|
+
}).nullish()
|
|
780
|
+
}).nullish(),
|
|
781
|
+
modelStreamErrorException: z2.record(z2.unknown()).nullish(),
|
|
782
|
+
throttlingException: z2.record(z2.unknown()).nullish(),
|
|
783
|
+
validationException: z2.record(z2.unknown()).nullish()
|
|
784
|
+
});
|
|
591
785
|
|
|
592
786
|
// src/bedrock-embedding-model.ts
|
|
593
787
|
import {
|
|
594
|
-
|
|
595
|
-
|
|
788
|
+
combineHeaders as combineHeaders2,
|
|
789
|
+
createJsonErrorResponseHandler as createJsonErrorResponseHandler2,
|
|
790
|
+
createJsonResponseHandler as createJsonResponseHandler2,
|
|
791
|
+
postJsonToApi as postJsonToApi2,
|
|
792
|
+
resolve as resolve2
|
|
793
|
+
} from "@ai-sdk/provider-utils";
|
|
794
|
+
import { z as z3 } from "zod";
|
|
596
795
|
var BedrockEmbeddingModel = class {
|
|
597
796
|
constructor(modelId, settings, config) {
|
|
797
|
+
this.modelId = modelId;
|
|
798
|
+
this.settings = settings;
|
|
799
|
+
this.config = config;
|
|
598
800
|
this.specificationVersion = "v1";
|
|
599
801
|
this.provider = "amazon-bedrock";
|
|
600
802
|
this.maxEmbeddingsPerCall = void 0;
|
|
601
803
|
this.supportsParallelCalls = true;
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
804
|
+
}
|
|
805
|
+
getUrl(modelId) {
|
|
806
|
+
const encodedModelId = encodeURIComponent(modelId);
|
|
807
|
+
return `${this.config.baseUrl()}/model/${encodedModelId}/invoke`;
|
|
605
808
|
}
|
|
606
809
|
async doEmbed({
|
|
607
|
-
values
|
|
810
|
+
values,
|
|
811
|
+
headers,
|
|
812
|
+
abortSignal
|
|
608
813
|
}) {
|
|
609
|
-
const
|
|
610
|
-
const
|
|
814
|
+
const embedSingleText = async (inputText) => {
|
|
815
|
+
const args = {
|
|
611
816
|
inputText,
|
|
612
817
|
dimensions: this.settings.dimensions,
|
|
613
818
|
normalize: this.settings.normalize
|
|
614
819
|
};
|
|
615
|
-
const
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
820
|
+
const url = this.getUrl(this.modelId);
|
|
821
|
+
const { value: response } = await postJsonToApi2({
|
|
822
|
+
url,
|
|
823
|
+
headers: await resolve2(
|
|
824
|
+
combineHeaders2(await resolve2(this.config.headers), headers)
|
|
825
|
+
),
|
|
826
|
+
body: args,
|
|
827
|
+
failedResponseHandler: createJsonErrorResponseHandler2({
|
|
828
|
+
errorSchema: BedrockErrorSchema,
|
|
829
|
+
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
830
|
+
}),
|
|
831
|
+
successfulResponseHandler: createJsonResponseHandler2(
|
|
832
|
+
BedrockEmbeddingResponseSchema
|
|
833
|
+
),
|
|
834
|
+
fetch: this.config.fetch,
|
|
835
|
+
abortSignal
|
|
619
836
|
});
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
837
|
+
return {
|
|
838
|
+
embedding: response.embedding,
|
|
839
|
+
inputTextTokenCount: response.inputTextTokenCount
|
|
840
|
+
};
|
|
623
841
|
};
|
|
624
|
-
const responses = await Promise.all(values.map(
|
|
625
|
-
|
|
626
|
-
(
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
return
|
|
842
|
+
const responses = await Promise.all(values.map(embedSingleText));
|
|
843
|
+
return responses.reduce(
|
|
844
|
+
(accumulated, response) => {
|
|
845
|
+
accumulated.embeddings.push(response.embedding);
|
|
846
|
+
accumulated.usage.tokens += response.inputTextTokenCount;
|
|
847
|
+
return accumulated;
|
|
630
848
|
},
|
|
631
849
|
{ embeddings: [], usage: { tokens: 0 } }
|
|
632
850
|
);
|
|
633
|
-
return response;
|
|
634
851
|
}
|
|
635
852
|
};
|
|
853
|
+
var BedrockEmbeddingResponseSchema = z3.object({
|
|
854
|
+
embedding: z3.array(z3.number()),
|
|
855
|
+
inputTextTokenCount: z3.number()
|
|
856
|
+
});
|
|
857
|
+
|
|
858
|
+
// src/headers-utils.ts
|
|
859
|
+
function extractHeaders(headers) {
|
|
860
|
+
let originalHeaders = {};
|
|
861
|
+
if (headers) {
|
|
862
|
+
if (headers instanceof Headers) {
|
|
863
|
+
originalHeaders = convertHeadersToRecord(headers);
|
|
864
|
+
} else if (Array.isArray(headers)) {
|
|
865
|
+
for (const [k, v] of headers) {
|
|
866
|
+
originalHeaders[k.toLowerCase()] = v;
|
|
867
|
+
}
|
|
868
|
+
} else {
|
|
869
|
+
originalHeaders = Object.fromEntries(
|
|
870
|
+
Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])
|
|
871
|
+
);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return originalHeaders;
|
|
875
|
+
}
|
|
876
|
+
function convertHeadersToRecord(headers) {
|
|
877
|
+
const record = {};
|
|
878
|
+
headers.forEach((value, key) => {
|
|
879
|
+
record[key.toLowerCase()] = value;
|
|
880
|
+
});
|
|
881
|
+
return record;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// src/bedrock-sigv4-fetch.ts
|
|
885
|
+
import {
|
|
886
|
+
combineHeaders as combineHeaders3,
|
|
887
|
+
removeUndefinedEntries
|
|
888
|
+
} from "@ai-sdk/provider-utils";
|
|
889
|
+
import { AwsV4Signer } from "aws4fetch";
|
|
890
|
+
function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
|
|
891
|
+
return async (input, init) => {
|
|
892
|
+
var _a;
|
|
893
|
+
if (((_a = init == null ? void 0 : init.method) == null ? void 0 : _a.toUpperCase()) !== "POST" || !(init == null ? void 0 : init.body)) {
|
|
894
|
+
return fetch(input, init);
|
|
895
|
+
}
|
|
896
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
897
|
+
const originalHeaders = extractHeaders(init.headers);
|
|
898
|
+
const body = prepareBodyString(init.body);
|
|
899
|
+
const credentials = getCredentials();
|
|
900
|
+
const signer = new AwsV4Signer({
|
|
901
|
+
url,
|
|
902
|
+
method: "POST",
|
|
903
|
+
headers: Object.entries(removeUndefinedEntries(originalHeaders)),
|
|
904
|
+
body,
|
|
905
|
+
region: credentials.region,
|
|
906
|
+
accessKeyId: credentials.accessKeyId,
|
|
907
|
+
secretAccessKey: credentials.secretAccessKey,
|
|
908
|
+
sessionToken: credentials.sessionToken,
|
|
909
|
+
service: "bedrock"
|
|
910
|
+
});
|
|
911
|
+
const signingResult = await signer.sign();
|
|
912
|
+
const signedHeaders = convertHeadersToRecord(signingResult.headers);
|
|
913
|
+
return fetch(input, {
|
|
914
|
+
...init,
|
|
915
|
+
body,
|
|
916
|
+
headers: removeUndefinedEntries(
|
|
917
|
+
combineHeaders3(originalHeaders, signedHeaders)
|
|
918
|
+
)
|
|
919
|
+
});
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
function prepareBodyString(body) {
|
|
923
|
+
if (typeof body === "string") {
|
|
924
|
+
return body;
|
|
925
|
+
} else if (body instanceof Uint8Array) {
|
|
926
|
+
return new TextDecoder().decode(body);
|
|
927
|
+
} else if (body instanceof ArrayBuffer) {
|
|
928
|
+
return new TextDecoder().decode(new Uint8Array(body));
|
|
929
|
+
} else {
|
|
930
|
+
return JSON.stringify(body);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
636
933
|
|
|
637
934
|
// src/bedrock-provider.ts
|
|
638
935
|
function createAmazonBedrock(options = {}) {
|
|
639
|
-
const
|
|
936
|
+
const sigv4Fetch = createSigV4FetchFunction(
|
|
937
|
+
() => ({
|
|
938
|
+
region: loadSetting({
|
|
939
|
+
settingValue: options.region,
|
|
940
|
+
settingName: "region",
|
|
941
|
+
environmentVariableName: "AWS_REGION",
|
|
942
|
+
description: "AWS region"
|
|
943
|
+
}),
|
|
944
|
+
accessKeyId: loadSetting({
|
|
945
|
+
settingValue: options.accessKeyId,
|
|
946
|
+
settingName: "accessKeyId",
|
|
947
|
+
environmentVariableName: "AWS_ACCESS_KEY_ID",
|
|
948
|
+
description: "AWS access key ID"
|
|
949
|
+
}),
|
|
950
|
+
secretAccessKey: loadSetting({
|
|
951
|
+
settingValue: options.secretAccessKey,
|
|
952
|
+
settingName: "secretAccessKey",
|
|
953
|
+
environmentVariableName: "AWS_SECRET_ACCESS_KEY",
|
|
954
|
+
description: "AWS secret access key"
|
|
955
|
+
}),
|
|
956
|
+
sessionToken: loadOptionalSetting({
|
|
957
|
+
settingValue: options.sessionToken,
|
|
958
|
+
environmentVariableName: "AWS_SESSION_TOKEN"
|
|
959
|
+
})
|
|
960
|
+
}),
|
|
961
|
+
options.fetch
|
|
962
|
+
);
|
|
963
|
+
const getBaseUrl = () => {
|
|
964
|
+
var _a, _b;
|
|
965
|
+
return (_b = withoutTrailingSlash(
|
|
966
|
+
(_a = options.baseURL) != null ? _a : `https://bedrock-runtime.${loadSetting({
|
|
967
|
+
settingValue: options.region,
|
|
968
|
+
settingName: "region",
|
|
969
|
+
environmentVariableName: "AWS_REGION",
|
|
970
|
+
description: "AWS region"
|
|
971
|
+
})}.amazonaws.com`
|
|
972
|
+
)) != null ? _b : `https://bedrock-runtime.us-east-1.amazonaws.com`;
|
|
973
|
+
};
|
|
974
|
+
const createChatModel = (modelId, settings = {}) => {
|
|
640
975
|
var _a;
|
|
641
|
-
return new
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
description: "AWS region"
|
|
648
|
-
}),
|
|
649
|
-
credentials: {
|
|
650
|
-
accessKeyId: loadSetting({
|
|
651
|
-
settingValue: options.accessKeyId,
|
|
652
|
-
settingName: "accessKeyId",
|
|
653
|
-
environmentVariableName: "AWS_ACCESS_KEY_ID",
|
|
654
|
-
description: "AWS access key ID"
|
|
655
|
-
}),
|
|
656
|
-
secretAccessKey: loadSetting({
|
|
657
|
-
settingValue: options.secretAccessKey,
|
|
658
|
-
settingName: "secretAccessKey",
|
|
659
|
-
environmentVariableName: "AWS_SECRET_ACCESS_KEY",
|
|
660
|
-
description: "AWS secret access key"
|
|
661
|
-
}),
|
|
662
|
-
sessionToken: loadOptionalSetting({
|
|
663
|
-
settingValue: options.sessionToken,
|
|
664
|
-
environmentVariableName: "AWS_SESSION_TOKEN"
|
|
665
|
-
})
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
);
|
|
976
|
+
return new BedrockChatLanguageModel(modelId, settings, {
|
|
977
|
+
baseUrl: getBaseUrl,
|
|
978
|
+
headers: (_a = options.headers) != null ? _a : {},
|
|
979
|
+
fetch: sigv4Fetch,
|
|
980
|
+
generateId
|
|
981
|
+
});
|
|
669
982
|
};
|
|
670
|
-
const createChatModel = (modelId, settings = {}) => new BedrockChatLanguageModel(modelId, settings, {
|
|
671
|
-
client: createBedrockRuntimeClient(),
|
|
672
|
-
generateId
|
|
673
|
-
});
|
|
674
983
|
const provider = function(modelId, settings) {
|
|
675
984
|
if (new.target) {
|
|
676
985
|
throw new Error(
|
|
@@ -679,9 +988,14 @@ function createAmazonBedrock(options = {}) {
|
|
|
679
988
|
}
|
|
680
989
|
return createChatModel(modelId, settings);
|
|
681
990
|
};
|
|
682
|
-
const createEmbeddingModel = (modelId, settings = {}) =>
|
|
683
|
-
|
|
684
|
-
|
|
991
|
+
const createEmbeddingModel = (modelId, settings = {}) => {
|
|
992
|
+
var _a;
|
|
993
|
+
return new BedrockEmbeddingModel(modelId, settings, {
|
|
994
|
+
baseUrl: getBaseUrl,
|
|
995
|
+
headers: (_a = options.headers) != null ? _a : {},
|
|
996
|
+
fetch: sigv4Fetch
|
|
997
|
+
});
|
|
998
|
+
};
|
|
685
999
|
provider.languageModel = createChatModel;
|
|
686
1000
|
provider.embedding = createEmbeddingModel;
|
|
687
1001
|
provider.textEmbedding = createEmbeddingModel;
|