@aeye/aws 0.1.0 → 0.2.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/README.md +1 -1
- package/dist/aws.d.ts +65 -8
- package/dist/aws.d.ts.map +1 -1
- package/dist/aws.js +315 -209
- package/dist/aws.js.map +1 -1
- package/dist/common.d.ts +20 -0
- package/dist/common.d.ts.map +1 -0
- package/dist/common.js +188 -0
- package/dist/common.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/aws.js
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
* Provider for AWS Bedrock models including Claude, Llama, Titan, Mistral, and more.
|
|
5
5
|
* Uses AWS SDK v3 to automatically pick up credentials from environment, IAM roles, or credential files.
|
|
6
6
|
*/
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import
|
|
12
|
-
import {
|
|
7
|
+
import { getModel, toJSONSchema, } from '@aeye/core';
|
|
8
|
+
import { BedrockClient, ListFoundationModelsCommand } from '@aws-sdk/client-bedrock';
|
|
9
|
+
import { BedrockRuntimeClient, InvokeModelCommand, InvokeModelWithResponseStreamCommand } from '@aws-sdk/client-bedrock-runtime';
|
|
10
|
+
import { isModelInfo } from 'packages/ai/src/common';
|
|
11
|
+
import { convertAWSModel, detectAWSFamily } from './common';
|
|
12
|
+
import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLimitError } from './types';
|
|
13
13
|
// ============================================================================
|
|
14
14
|
// AWS Bedrock Provider Class
|
|
15
15
|
// ============================================================================
|
|
@@ -52,84 +52,40 @@ export class AWSBedrockProvider {
|
|
|
52
52
|
bedrockRuntimeClient;
|
|
53
53
|
constructor(config) {
|
|
54
54
|
this.config = config;
|
|
55
|
-
const clientConfig =
|
|
56
|
-
region: config.region || process.env.AWS_REGION || 'us-east-1',
|
|
57
|
-
credentials: config.credentials,
|
|
58
|
-
};
|
|
55
|
+
const clientConfig = AWSBedrockProvider.convertConfig(config);
|
|
59
56
|
this.bedrockClient = new BedrockClient(clientConfig);
|
|
60
57
|
this.bedrockRuntimeClient = new BedrockRuntimeClient(clientConfig);
|
|
61
58
|
}
|
|
62
|
-
// ============================================================================
|
|
63
|
-
// Model Information & Detection
|
|
64
|
-
// ============================================================================
|
|
65
59
|
/**
|
|
66
|
-
*
|
|
60
|
+
* Convert AWSBedrockConfig to BedrockClientConfig
|
|
61
|
+
*
|
|
62
|
+
* @param config
|
|
63
|
+
* @returns
|
|
67
64
|
*/
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return 'ai21';
|
|
81
|
-
if (modelId.startsWith('stability.'))
|
|
82
|
-
return 'stability';
|
|
83
|
-
return 'unknown';
|
|
65
|
+
static convertConfig(config) {
|
|
66
|
+
const clientConfig = {
|
|
67
|
+
region: config.region || process.env.AWS_REGION || 'us-east-1',
|
|
68
|
+
};
|
|
69
|
+
if (config.credentials && config.credentials.accessKeyId && config.credentials.secretAccessKey) {
|
|
70
|
+
clientConfig.credentials = {
|
|
71
|
+
accessKeyId: config.credentials.accessKeyId,
|
|
72
|
+
secretAccessKey: config.credentials.secretAccessKey,
|
|
73
|
+
sessionToken: config.credentials.sessionToken,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return clientConfig;
|
|
84
77
|
}
|
|
85
78
|
/**
|
|
86
|
-
*
|
|
79
|
+
* Prepend model prefix if configured
|
|
80
|
+
*
|
|
81
|
+
* @param modelId - The base model ID
|
|
82
|
+
* @returns Model ID with prefix prepended if configured
|
|
87
83
|
*/
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const tier = detectTier(modelId);
|
|
92
|
-
// Detect capabilities based on model family and ID
|
|
93
|
-
const capabilities = new Set();
|
|
94
|
-
// Chat models
|
|
95
|
-
if (family === 'anthropic' || family === 'meta' || family === 'mistral' || family === 'cohere' || family === 'ai21') {
|
|
96
|
-
capabilities.add('chat');
|
|
97
|
-
capabilities.add('streaming');
|
|
98
|
-
}
|
|
99
|
-
// Vision support (Claude 3 models)
|
|
100
|
-
if (modelId.includes('claude-3') || modelId.includes('claude-3-5')) {
|
|
101
|
-
capabilities.add('vision');
|
|
102
|
-
}
|
|
103
|
-
// Tools support
|
|
104
|
-
if (family === 'anthropic' && (modelId.includes('claude-3') || modelId.includes('claude-3-5'))) {
|
|
105
|
-
capabilities.add('tools');
|
|
106
|
-
}
|
|
107
|
-
// Image generation
|
|
108
|
-
if (family === 'stability') {
|
|
109
|
-
capabilities.add('image');
|
|
110
|
-
}
|
|
111
|
-
// Embeddings
|
|
112
|
-
if (family === 'amazon' && modelId.includes('embed')) {
|
|
113
|
-
capabilities.add('embedding');
|
|
84
|
+
applyModelPrefix(modelId) {
|
|
85
|
+
if (this.config.modelPrefix) {
|
|
86
|
+
return `${this.config.modelPrefix}${modelId}`;
|
|
114
87
|
}
|
|
115
|
-
return
|
|
116
|
-
provider: this.name,
|
|
117
|
-
id: modelId,
|
|
118
|
-
name: model.modelName || modelId,
|
|
119
|
-
capabilities,
|
|
120
|
-
tier,
|
|
121
|
-
pricing: {},
|
|
122
|
-
contextWindow: 0, // Will need to be populated from external sources
|
|
123
|
-
maxOutputTokens: undefined,
|
|
124
|
-
metadata: {
|
|
125
|
-
modelArn: model.modelArn,
|
|
126
|
-
responseStreamingSupported: model.responseStreamingSupported,
|
|
127
|
-
customizationsSupported: model.customizationsSupported,
|
|
128
|
-
inferenceTypesSupported: model.inferenceTypesSupported,
|
|
129
|
-
inputModalities: model.inputModalities,
|
|
130
|
-
outputModalities: model.outputModalities,
|
|
131
|
-
},
|
|
132
|
-
};
|
|
88
|
+
return modelId;
|
|
133
89
|
}
|
|
134
90
|
// ============================================================================
|
|
135
91
|
// Provider Interface Implementation
|
|
@@ -139,14 +95,18 @@ export class AWSBedrockProvider {
|
|
|
139
95
|
*/
|
|
140
96
|
async listModels(config) {
|
|
141
97
|
try {
|
|
98
|
+
const client = config && JSON.stringify(config) !== JSON.stringify(this.config)
|
|
99
|
+
? new BedrockClient(AWSBedrockProvider.convertConfig(config))
|
|
100
|
+
: this.bedrockClient;
|
|
142
101
|
const command = new ListFoundationModelsCommand({});
|
|
143
|
-
const response = await
|
|
102
|
+
const response = await client.send(command);
|
|
144
103
|
if (!response.modelSummaries) {
|
|
145
104
|
return [];
|
|
146
105
|
}
|
|
147
106
|
return response.modelSummaries
|
|
148
107
|
.filter(m => m.modelId) // Filter out models without IDs
|
|
149
|
-
.map(m =>
|
|
108
|
+
.map(m => convertAWSModel(m))
|
|
109
|
+
.filter(m => !!m);
|
|
150
110
|
}
|
|
151
111
|
catch (error) {
|
|
152
112
|
throw new AWSError('Failed to list models', error);
|
|
@@ -157,8 +117,11 @@ export class AWSBedrockProvider {
|
|
|
157
117
|
*/
|
|
158
118
|
async checkHealth(config) {
|
|
159
119
|
try {
|
|
120
|
+
const client = config && JSON.stringify(config) !== JSON.stringify(this.config)
|
|
121
|
+
? new BedrockClient(AWSBedrockProvider.convertConfig(config))
|
|
122
|
+
: this.bedrockClient;
|
|
160
123
|
const command = new ListFoundationModelsCommand({});
|
|
161
|
-
await
|
|
124
|
+
await client.send(command);
|
|
162
125
|
return true;
|
|
163
126
|
}
|
|
164
127
|
catch {
|
|
@@ -170,21 +133,23 @@ export class AWSBedrockProvider {
|
|
|
170
133
|
*/
|
|
171
134
|
createExecutor(config) {
|
|
172
135
|
const effectiveConfig = { ...this.config, ...config };
|
|
136
|
+
const self = this;
|
|
173
137
|
return async (request, ctx, metadata) => {
|
|
174
|
-
const
|
|
175
|
-
if (!
|
|
138
|
+
const modelInput = request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat;
|
|
139
|
+
if (!modelInput) {
|
|
176
140
|
throw new AWSError('Model is required for AWS Bedrock requests');
|
|
177
141
|
}
|
|
178
|
-
const
|
|
142
|
+
const model = getModel(modelInput);
|
|
143
|
+
const family = detectAWSFamily(model.id);
|
|
179
144
|
// Route to appropriate model handler
|
|
180
145
|
if (family === 'anthropic') {
|
|
181
|
-
return
|
|
146
|
+
return self.executeAnthropicModel(modelInput, request, ctx);
|
|
182
147
|
}
|
|
183
148
|
else if (family === 'meta' || family === 'mistral') {
|
|
184
|
-
return
|
|
149
|
+
return self.executeLlamaStyleModel(model.id, request, ctx);
|
|
185
150
|
}
|
|
186
151
|
else if (family === 'cohere') {
|
|
187
|
-
return
|
|
152
|
+
return self.executeCohereModel(model.id, request, ctx);
|
|
188
153
|
}
|
|
189
154
|
else {
|
|
190
155
|
throw new AWSError(`Unsupported model family: ${family}`);
|
|
@@ -196,21 +161,22 @@ export class AWSBedrockProvider {
|
|
|
196
161
|
*/
|
|
197
162
|
createStreamer(config) {
|
|
198
163
|
const effectiveConfig = { ...this.config, ...config };
|
|
164
|
+
const self = this;
|
|
199
165
|
return async function* (request, ctx, metadata) {
|
|
200
166
|
const model = getModel(request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat);
|
|
201
167
|
if (!model) {
|
|
202
168
|
throw new AWSError('Model is required for AWS Bedrock requests');
|
|
203
169
|
}
|
|
204
|
-
const family =
|
|
170
|
+
const family = detectAWSFamily(model.id);
|
|
205
171
|
// Route to appropriate model handler
|
|
206
172
|
if (family === 'anthropic') {
|
|
207
|
-
yield*
|
|
173
|
+
return yield* self.streamAnthropicModel(model.id, request, ctx);
|
|
208
174
|
}
|
|
209
175
|
else if (family === 'meta' || family === 'mistral') {
|
|
210
|
-
yield*
|
|
176
|
+
return yield* self.streamLlamaStyleModel(model.id, request, ctx);
|
|
211
177
|
}
|
|
212
178
|
else if (family === 'cohere') {
|
|
213
|
-
yield*
|
|
179
|
+
return yield* self.streamCohereModel(model.id, request, ctx);
|
|
214
180
|
}
|
|
215
181
|
else {
|
|
216
182
|
throw new AWSError(`Unsupported model family for streaming: ${family}`);
|
|
@@ -229,7 +195,7 @@ export class AWSBedrockProvider {
|
|
|
229
195
|
return request.tools.map((tool) => ({
|
|
230
196
|
name: tool.name,
|
|
231
197
|
description: tool.description,
|
|
232
|
-
input_schema:
|
|
198
|
+
input_schema: toJSONSchema(tool.parameters, tool.strict ?? true),
|
|
233
199
|
}));
|
|
234
200
|
}
|
|
235
201
|
/**
|
|
@@ -249,28 +215,38 @@ export class AWSBedrockProvider {
|
|
|
249
215
|
}
|
|
250
216
|
return undefined;
|
|
251
217
|
}
|
|
252
|
-
|
|
253
|
-
// Convert messages to Anthropic format
|
|
218
|
+
convertRequestToAnthropic(model, request) {
|
|
254
219
|
const messages = this.convertMessagesToAnthropic(request);
|
|
255
|
-
|
|
220
|
+
const tools = this.convertToolsToAnthropic(request);
|
|
221
|
+
const tool_choice = tools ? this.convertToolChoiceToAnthropic(request) : undefined;
|
|
256
222
|
const systemMessages = request.messages.filter(m => m.role === 'system');
|
|
257
223
|
const system = systemMessages.length > 0
|
|
258
|
-
? systemMessages.map(m =>
|
|
224
|
+
? systemMessages.map((m) => ({
|
|
225
|
+
type: 'text',
|
|
226
|
+
text: typeof m.content === 'string' ? m.content : m.content.map(m => m.content).join('\n'),
|
|
227
|
+
}))
|
|
259
228
|
: undefined;
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
max_tokens: request.maxTokens || 4096,
|
|
229
|
+
const modelMax = isModelInfo(model) ? model.maxOutputTokens : undefined;
|
|
230
|
+
return {
|
|
231
|
+
anthropic_version: this.config.anthropic?.version ?? 'bedrock-2023-05-31',
|
|
232
|
+
anthropic_beta: this.config.anthropic?.beta,
|
|
233
|
+
max_tokens: modelMax || 4096,
|
|
266
234
|
messages,
|
|
267
235
|
system,
|
|
268
236
|
temperature: request.temperature,
|
|
269
237
|
top_p: request.topP,
|
|
270
|
-
stop_sequences: request.stop,
|
|
238
|
+
stop_sequences: request.stop ? Array.isArray(request.stop) ? request.stop : [request.stop] : undefined,
|
|
271
239
|
tools,
|
|
272
240
|
tool_choice,
|
|
241
|
+
metadata: {
|
|
242
|
+
user_id: request.userKey || undefined,
|
|
243
|
+
},
|
|
244
|
+
...request.extra,
|
|
273
245
|
};
|
|
246
|
+
}
|
|
247
|
+
async executeAnthropicModel(model, request, ctx) {
|
|
248
|
+
const body = this.convertRequestToAnthropic(model, request);
|
|
249
|
+
const modelId = this.applyModelPrefix(getModel(model)?.id || '');
|
|
274
250
|
try {
|
|
275
251
|
const command = new InvokeModelCommand({
|
|
276
252
|
modelId,
|
|
@@ -278,12 +254,15 @@ export class AWSBedrockProvider {
|
|
|
278
254
|
accept: 'application/json',
|
|
279
255
|
body: JSON.stringify(body),
|
|
280
256
|
});
|
|
257
|
+
// Call pre-request hook with command
|
|
258
|
+
await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
|
|
281
259
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
282
260
|
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
283
261
|
// Extract text content and tool calls
|
|
284
262
|
let content = '';
|
|
263
|
+
let reasoning = undefined;
|
|
285
264
|
const toolCalls = [];
|
|
286
|
-
if (responseBody.content
|
|
265
|
+
if (responseBody.content) {
|
|
287
266
|
for (const block of responseBody.content) {
|
|
288
267
|
if (block.type === 'text') {
|
|
289
268
|
content += block.text;
|
|
@@ -295,13 +274,17 @@ export class AWSBedrockProvider {
|
|
|
295
274
|
arguments: JSON.stringify(block.input),
|
|
296
275
|
});
|
|
297
276
|
}
|
|
277
|
+
else if (block.type === 'thinking') {
|
|
278
|
+
reasoning = (reasoning || '') + block.thinking;
|
|
279
|
+
}
|
|
298
280
|
}
|
|
299
281
|
}
|
|
300
|
-
|
|
282
|
+
const result = {
|
|
301
283
|
content,
|
|
284
|
+
reasoning,
|
|
302
285
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
303
286
|
finishReason: this.mapAnthropicStopReason(responseBody.stop_reason),
|
|
304
|
-
model
|
|
287
|
+
model,
|
|
305
288
|
usage: {
|
|
306
289
|
text: {
|
|
307
290
|
input: responseBody.usage?.input_tokens ?? -1,
|
|
@@ -309,33 +292,18 @@ export class AWSBedrockProvider {
|
|
|
309
292
|
},
|
|
310
293
|
},
|
|
311
294
|
};
|
|
295
|
+
// Call post-request hook with command
|
|
296
|
+
await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
|
|
297
|
+
return result;
|
|
312
298
|
}
|
|
313
299
|
catch (error) {
|
|
314
300
|
this.handleAWSError(error);
|
|
315
301
|
throw error;
|
|
316
302
|
}
|
|
317
303
|
}
|
|
318
|
-
async *streamAnthropicModel(
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
const systemMessages = request.messages.filter(m => m.role === 'system');
|
|
322
|
-
const system = systemMessages.length > 0
|
|
323
|
-
? systemMessages.map(m => typeof m.content === 'string' ? m.content : '').join('\n\n')
|
|
324
|
-
: undefined;
|
|
325
|
-
// Convert tools
|
|
326
|
-
const tools = this.convertToolsToAnthropic(request);
|
|
327
|
-
const tool_choice = tools ? this.convertToolChoiceToAnthropic(request) : undefined;
|
|
328
|
-
const body = {
|
|
329
|
-
anthropic_version: 'bedrock-2023-05-31',
|
|
330
|
-
max_tokens: request.maxTokens || 4096,
|
|
331
|
-
messages,
|
|
332
|
-
system,
|
|
333
|
-
temperature: request.temperature,
|
|
334
|
-
top_p: request.topP,
|
|
335
|
-
stop_sequences: request.stop,
|
|
336
|
-
tools,
|
|
337
|
-
tool_choice,
|
|
338
|
-
};
|
|
304
|
+
async *streamAnthropicModel(model, request, ctx) {
|
|
305
|
+
const body = this.convertRequestToAnthropic(model, request);
|
|
306
|
+
const modelId = this.applyModelPrefix(getModel(model)?.id || '');
|
|
339
307
|
try {
|
|
340
308
|
const command = new InvokeModelWithResponseStreamCommand({
|
|
341
309
|
modelId,
|
|
@@ -343,93 +311,136 @@ export class AWSBedrockProvider {
|
|
|
343
311
|
accept: 'application/json',
|
|
344
312
|
body: JSON.stringify(body),
|
|
345
313
|
});
|
|
314
|
+
// Call pre-request hook with command
|
|
315
|
+
await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
|
|
346
316
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
347
317
|
if (!response.body) {
|
|
348
318
|
throw new AWSError('No response body in streaming response');
|
|
349
319
|
}
|
|
350
320
|
let inputTokens = 0;
|
|
351
321
|
let outputTokens = 0;
|
|
322
|
+
let accumulatedContent = '';
|
|
323
|
+
let accumulatedReasoning = '';
|
|
324
|
+
let finishReason = undefined;
|
|
352
325
|
const toolCallsMap = new Map();
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
name: toolCall.name,
|
|
393
|
-
arguments: toolCall.arguments,
|
|
394
|
-
},
|
|
395
|
-
};
|
|
326
|
+
try {
|
|
327
|
+
for await (const event of response.body) {
|
|
328
|
+
if (event.chunk) {
|
|
329
|
+
const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
|
|
330
|
+
if (chunk.type === 'content_block_delta' && chunk.delta) {
|
|
331
|
+
switch (chunk.delta.type) {
|
|
332
|
+
case 'text_delta':
|
|
333
|
+
accumulatedContent += chunk.delta.text;
|
|
334
|
+
yield {
|
|
335
|
+
content: chunk.delta.text,
|
|
336
|
+
finishReason: undefined,
|
|
337
|
+
};
|
|
338
|
+
break;
|
|
339
|
+
case 'thinking_delta':
|
|
340
|
+
accumulatedReasoning += chunk.delta.thinking;
|
|
341
|
+
yield {
|
|
342
|
+
reasoning: chunk.delta.thinking,
|
|
343
|
+
};
|
|
344
|
+
break;
|
|
345
|
+
case 'input_json_delta':
|
|
346
|
+
// Tool input accumulation
|
|
347
|
+
const index = chunk.index;
|
|
348
|
+
const toolCall = toolCallsMap.get(index);
|
|
349
|
+
if (toolCall && chunk.delta.partial_json) {
|
|
350
|
+
if (toolCall.arguments === '{}') {
|
|
351
|
+
toolCall.arguments = '';
|
|
352
|
+
}
|
|
353
|
+
toolCall.arguments += chunk.delta.partial_json;
|
|
354
|
+
// Yield toolCallArguments event
|
|
355
|
+
yield {
|
|
356
|
+
toolCallArguments: {
|
|
357
|
+
id: toolCall.id,
|
|
358
|
+
name: toolCall.name,
|
|
359
|
+
arguments: toolCall.arguments,
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
396
365
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
366
|
+
else if (chunk.type === 'content_block_start' && chunk.content_block?.type === 'tool_use') {
|
|
367
|
+
// Start of a tool use block
|
|
368
|
+
const index = chunk.index;
|
|
369
|
+
const toolCall = {
|
|
370
|
+
id: chunk.content_block.id,
|
|
371
|
+
name: chunk.content_block.name,
|
|
372
|
+
arguments: chunk.content_block.input ? JSON.stringify(chunk.content_block.input) : '',
|
|
373
|
+
named: true,
|
|
374
|
+
finished: false,
|
|
375
|
+
};
|
|
376
|
+
toolCallsMap.set(index, toolCall);
|
|
377
|
+
// Yield toolCallNamed event
|
|
405
378
|
yield {
|
|
406
|
-
|
|
379
|
+
toolCallNamed: {
|
|
407
380
|
id: toolCall.id,
|
|
408
381
|
name: toolCall.name,
|
|
409
382
|
arguments: toolCall.arguments,
|
|
410
383
|
},
|
|
411
384
|
};
|
|
412
385
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
output: chunk.usage?.output_tokens || 0,
|
|
386
|
+
else if (chunk.type === 'content_block_stop') {
|
|
387
|
+
// Tool use block completed
|
|
388
|
+
const index = chunk.index;
|
|
389
|
+
const toolCall = toolCallsMap.get(index);
|
|
390
|
+
if (toolCall && !toolCall.finished) {
|
|
391
|
+
toolCall.finished = true;
|
|
392
|
+
// Yield toolCall event
|
|
393
|
+
yield {
|
|
394
|
+
toolCall: {
|
|
395
|
+
id: toolCall.id,
|
|
396
|
+
name: toolCall.name,
|
|
397
|
+
arguments: toolCall.arguments,
|
|
426
398
|
},
|
|
427
|
-
}
|
|
428
|
-
}
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
else if (chunk.type === 'message_start' && chunk.message?.usage) {
|
|
403
|
+
inputTokens = chunk.message.usage.input_tokens || 0;
|
|
404
|
+
}
|
|
405
|
+
else if (chunk.type === 'message_delta') {
|
|
406
|
+
if (chunk.delta?.stop_reason) {
|
|
407
|
+
finishReason = this.mapAnthropicStopReason(chunk.delta.stop_reason);
|
|
408
|
+
yield {
|
|
409
|
+
finishReason,
|
|
410
|
+
usage: {
|
|
411
|
+
text: {
|
|
412
|
+
input: chunk.usage.input_tokens || inputTokens || undefined,
|
|
413
|
+
output: chunk.usage.output_tokens || undefined,
|
|
414
|
+
cached: chunk.usage.cache_read_input_tokens || undefined,
|
|
415
|
+
},
|
|
416
|
+
},
|
|
417
|
+
};
|
|
418
|
+
}
|
|
429
419
|
}
|
|
430
420
|
}
|
|
431
421
|
}
|
|
432
422
|
}
|
|
423
|
+
finally {
|
|
424
|
+
// Call post-request hook with accumulated response
|
|
425
|
+
const toolCalls = Array.from(toolCallsMap.values()).map(tc => ({
|
|
426
|
+
id: tc.id,
|
|
427
|
+
name: tc.name,
|
|
428
|
+
arguments: tc.arguments,
|
|
429
|
+
}));
|
|
430
|
+
const accumulatedResponse = {
|
|
431
|
+
content: accumulatedContent,
|
|
432
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
433
|
+
finishReason,
|
|
434
|
+
model,
|
|
435
|
+
usage: {
|
|
436
|
+
text: {
|
|
437
|
+
input: inputTokens,
|
|
438
|
+
output: outputTokens,
|
|
439
|
+
},
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
await this.config.hooks?.chat?.afterRequest?.(request, command, accumulatedResponse, ctx);
|
|
443
|
+
}
|
|
433
444
|
}
|
|
434
445
|
catch (error) {
|
|
435
446
|
this.handleAWSError(error);
|
|
@@ -437,9 +448,17 @@ export class AWSBedrockProvider {
|
|
|
437
448
|
}
|
|
438
449
|
}
|
|
439
450
|
convertMessagesToAnthropic(request) {
|
|
440
|
-
|
|
451
|
+
const toContent = (part) => {
|
|
452
|
+
if (typeof part === 'string') {
|
|
453
|
+
return [{ type: 'text', text: part }];
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
return part;
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
const messages = request.messages
|
|
441
460
|
.filter(m => m.role !== 'system')
|
|
442
|
-
.map(msg => {
|
|
461
|
+
.map((msg) => {
|
|
443
462
|
if (msg.role === 'assistant') {
|
|
444
463
|
// Handle assistant messages with tool calls
|
|
445
464
|
if (msg.toolCalls && msg.toolCalls.length > 0) {
|
|
@@ -454,7 +473,14 @@ export class AWSBedrockProvider {
|
|
|
454
473
|
type: 'tool_use',
|
|
455
474
|
id: toolCall.id,
|
|
456
475
|
name: toolCall.name,
|
|
457
|
-
input:
|
|
476
|
+
input: (() => {
|
|
477
|
+
try {
|
|
478
|
+
return JSON.parse(toolCall.arguments);
|
|
479
|
+
}
|
|
480
|
+
catch (e) {
|
|
481
|
+
return { badArguments: toolCall.arguments };
|
|
482
|
+
}
|
|
483
|
+
})(),
|
|
458
484
|
});
|
|
459
485
|
}
|
|
460
486
|
return {
|
|
@@ -464,7 +490,7 @@ export class AWSBedrockProvider {
|
|
|
464
490
|
}
|
|
465
491
|
return {
|
|
466
492
|
role: 'assistant',
|
|
467
|
-
content: typeof msg.content === 'string' ? msg.content : '',
|
|
493
|
+
content: typeof msg.content === 'string' ? msg.content : msg.content.map(m => m.content).join('\n\n'),
|
|
468
494
|
};
|
|
469
495
|
}
|
|
470
496
|
else if (msg.role === 'tool') {
|
|
@@ -489,7 +515,7 @@ export class AWSBedrockProvider {
|
|
|
489
515
|
};
|
|
490
516
|
}
|
|
491
517
|
else if (Array.isArray(msg.content)) {
|
|
492
|
-
const content = msg.content.map(part => {
|
|
518
|
+
const content = msg.content.map((part) => {
|
|
493
519
|
if (part.type === 'text') {
|
|
494
520
|
return { type: 'text', text: String(part.content) };
|
|
495
521
|
}
|
|
@@ -506,15 +532,29 @@ export class AWSBedrockProvider {
|
|
|
506
532
|
data: match[2],
|
|
507
533
|
};
|
|
508
534
|
}
|
|
535
|
+
else if (part.content.startsWith('http')) {
|
|
536
|
+
source = {
|
|
537
|
+
type: 'url',
|
|
538
|
+
url: part.content,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
509
541
|
}
|
|
510
|
-
else
|
|
542
|
+
else {
|
|
511
543
|
source = {
|
|
512
544
|
type: 'url',
|
|
513
545
|
url: part.content,
|
|
514
546
|
};
|
|
515
547
|
}
|
|
516
548
|
}
|
|
517
|
-
|
|
549
|
+
else if (part.content instanceof URL) {
|
|
550
|
+
source = {
|
|
551
|
+
type: 'url',
|
|
552
|
+
url: part.content.toString(),
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
if (source) {
|
|
556
|
+
return { type: 'image', source };
|
|
557
|
+
}
|
|
518
558
|
}
|
|
519
559
|
return { type: 'text', text: '[Unsupported content type]' };
|
|
520
560
|
});
|
|
@@ -526,11 +566,57 @@ export class AWSBedrockProvider {
|
|
|
526
566
|
}
|
|
527
567
|
return {
|
|
528
568
|
role: 'user',
|
|
529
|
-
content: '',
|
|
569
|
+
content: '<unsupported role>',
|
|
530
570
|
};
|
|
531
571
|
});
|
|
572
|
+
// Filter out empty messages
|
|
573
|
+
const nonEmptyMessages = messages.filter(m => {
|
|
574
|
+
const contentArray = toContent(m.content);
|
|
575
|
+
return contentArray.some(c => c.type === 'text' ? c.text.trim().length > 0 : true);
|
|
576
|
+
});
|
|
577
|
+
// Join up consecutive messages with the same role
|
|
578
|
+
const joinedMessages = [];
|
|
579
|
+
let lastMessage = null;
|
|
580
|
+
for (const msg of nonEmptyMessages) {
|
|
581
|
+
if (lastMessage && lastMessage.role === msg.role) {
|
|
582
|
+
const lastContent = toContent(lastMessage.content);
|
|
583
|
+
const newContent = toContent(msg.content);
|
|
584
|
+
const allContent = lastContent.concat(newContent);
|
|
585
|
+
lastMessage.content = allContent;
|
|
586
|
+
}
|
|
587
|
+
else {
|
|
588
|
+
if (lastMessage) {
|
|
589
|
+
joinedMessages.push(lastMessage);
|
|
590
|
+
}
|
|
591
|
+
lastMessage = msg;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (lastMessage) {
|
|
595
|
+
joinedMessages.push(lastMessage);
|
|
596
|
+
}
|
|
597
|
+
// Simplify content if single text block
|
|
598
|
+
for (const msg of joinedMessages) {
|
|
599
|
+
const contentArray = toContent(msg.content);
|
|
600
|
+
if (contentArray.every(c => c.type === 'text')) {
|
|
601
|
+
msg.content = contentArray.map(c => c.text).join('\n\n');
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
if (joinedMessages.length === 0) {
|
|
605
|
+
if (this.config.anthropic?.emptyMessage) {
|
|
606
|
+
joinedMessages.push(this.config.anthropic.emptyMessage);
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
joinedMessages.push({
|
|
610
|
+
role: 'user',
|
|
611
|
+
content: 'Perform the requested operation.',
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return joinedMessages;
|
|
532
616
|
}
|
|
533
617
|
mapAnthropicStopReason(reason) {
|
|
618
|
+
if (!reason)
|
|
619
|
+
return 'stop';
|
|
534
620
|
switch (reason) {
|
|
535
621
|
case 'end_turn':
|
|
536
622
|
return 'stop';
|
|
@@ -557,14 +643,16 @@ export class AWSBedrockProvider {
|
|
|
557
643
|
};
|
|
558
644
|
try {
|
|
559
645
|
const command = new InvokeModelCommand({
|
|
560
|
-
modelId,
|
|
646
|
+
modelId: this.applyModelPrefix(modelId),
|
|
561
647
|
contentType: 'application/json',
|
|
562
648
|
accept: 'application/json',
|
|
563
649
|
body: JSON.stringify(body),
|
|
564
650
|
});
|
|
651
|
+
// Call pre-request hook with command
|
|
652
|
+
await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
|
|
565
653
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
566
654
|
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
567
|
-
|
|
655
|
+
const result = {
|
|
568
656
|
content: responseBody.generation || '',
|
|
569
657
|
toolCalls: [],
|
|
570
658
|
finishReason: responseBody.stop_reason === 'stop' ? 'stop' : 'length',
|
|
@@ -576,6 +664,9 @@ export class AWSBedrockProvider {
|
|
|
576
664
|
},
|
|
577
665
|
},
|
|
578
666
|
};
|
|
667
|
+
// Call post-request hook with command
|
|
668
|
+
await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
|
|
669
|
+
return result;
|
|
579
670
|
}
|
|
580
671
|
catch (error) {
|
|
581
672
|
this.handleAWSError(error);
|
|
@@ -592,7 +683,7 @@ export class AWSBedrockProvider {
|
|
|
592
683
|
};
|
|
593
684
|
try {
|
|
594
685
|
const command = new InvokeModelWithResponseStreamCommand({
|
|
595
|
-
modelId,
|
|
686
|
+
modelId: this.applyModelPrefix(modelId),
|
|
596
687
|
contentType: 'application/json',
|
|
597
688
|
accept: 'application/json',
|
|
598
689
|
body: JSON.stringify(body),
|
|
@@ -641,14 +732,16 @@ export class AWSBedrockProvider {
|
|
|
641
732
|
};
|
|
642
733
|
try {
|
|
643
734
|
const command = new InvokeModelCommand({
|
|
644
|
-
modelId,
|
|
735
|
+
modelId: this.applyModelPrefix(modelId),
|
|
645
736
|
contentType: 'application/json',
|
|
646
737
|
accept: 'application/json',
|
|
647
738
|
body: JSON.stringify(body),
|
|
648
739
|
});
|
|
740
|
+
// Call pre-request hook with command
|
|
741
|
+
await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
|
|
649
742
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
650
743
|
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
651
|
-
|
|
744
|
+
const result = {
|
|
652
745
|
content: responseBody.generations?.[0]?.text || '',
|
|
653
746
|
toolCalls: [],
|
|
654
747
|
finishReason: responseBody.generations?.[0]?.finish_reason === 'COMPLETE' ? 'stop' : 'length',
|
|
@@ -660,6 +753,9 @@ export class AWSBedrockProvider {
|
|
|
660
753
|
},
|
|
661
754
|
},
|
|
662
755
|
};
|
|
756
|
+
// Call post-request hook with command
|
|
757
|
+
await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
|
|
758
|
+
return result;
|
|
663
759
|
}
|
|
664
760
|
catch (error) {
|
|
665
761
|
this.handleAWSError(error);
|
|
@@ -678,7 +774,7 @@ export class AWSBedrockProvider {
|
|
|
678
774
|
};
|
|
679
775
|
try {
|
|
680
776
|
const command = new InvokeModelWithResponseStreamCommand({
|
|
681
|
-
modelId,
|
|
777
|
+
modelId: this.applyModelPrefix(modelId),
|
|
682
778
|
contentType: 'application/json',
|
|
683
779
|
accept: 'application/json',
|
|
684
780
|
body: JSON.stringify(body),
|
|
@@ -745,11 +841,13 @@ export class AWSBedrockProvider {
|
|
|
745
841
|
};
|
|
746
842
|
try {
|
|
747
843
|
const command = new InvokeModelCommand({
|
|
748
|
-
modelId: model.id,
|
|
844
|
+
modelId: this.applyModelPrefix(model.id),
|
|
749
845
|
contentType: 'application/json',
|
|
750
846
|
accept: 'application/json',
|
|
751
847
|
body: JSON.stringify(body),
|
|
752
848
|
});
|
|
849
|
+
// Call pre-request hook with command
|
|
850
|
+
await effectiveConfig.hooks?.imageGenerate?.beforeRequest?.(request, command, ctx);
|
|
753
851
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
754
852
|
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
755
853
|
const images = responseBody.artifacts?.map((artifact) => ({
|
|
@@ -757,10 +855,13 @@ export class AWSBedrockProvider {
|
|
|
757
855
|
base64: artifact.base64,
|
|
758
856
|
revisedPrompt: undefined,
|
|
759
857
|
})) || [];
|
|
760
|
-
|
|
858
|
+
const result = {
|
|
761
859
|
images,
|
|
762
860
|
model,
|
|
763
861
|
};
|
|
862
|
+
// Call post-request hook with command
|
|
863
|
+
await effectiveConfig.hooks?.imageGenerate?.afterRequest?.(request, command, result, ctx);
|
|
864
|
+
return result;
|
|
764
865
|
}
|
|
765
866
|
catch (error) {
|
|
766
867
|
this.handleAWSError(error);
|
|
@@ -782,16 +883,18 @@ export class AWSBedrockProvider {
|
|
|
782
883
|
};
|
|
783
884
|
try {
|
|
784
885
|
const command = new InvokeModelCommand({
|
|
785
|
-
modelId: model.id,
|
|
886
|
+
modelId: this.applyModelPrefix(model.id),
|
|
786
887
|
contentType: 'application/json',
|
|
787
888
|
accept: 'application/json',
|
|
788
889
|
body: JSON.stringify(body),
|
|
789
890
|
});
|
|
891
|
+
// Call pre-request hook with command
|
|
892
|
+
await effectiveConfig.hooks?.embed?.beforeRequest?.(request, command, ctx);
|
|
790
893
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
791
894
|
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
792
895
|
// Handle multiple texts if provided
|
|
793
896
|
const embeddings = request.texts.map(() => responseBody.embedding);
|
|
794
|
-
|
|
897
|
+
const result = {
|
|
795
898
|
embeddings,
|
|
796
899
|
model,
|
|
797
900
|
usage: {
|
|
@@ -800,6 +903,9 @@ export class AWSBedrockProvider {
|
|
|
800
903
|
},
|
|
801
904
|
},
|
|
802
905
|
};
|
|
906
|
+
// Call post-request hook with command
|
|
907
|
+
await effectiveConfig.hooks?.embed?.afterRequest?.(request, command, result, ctx);
|
|
908
|
+
return result;
|
|
803
909
|
}
|
|
804
910
|
catch (error) {
|
|
805
911
|
this.handleAWSError(error);
|