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