@aeye/aws 0.1.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 +407 -0
- package/dist/aws.d.ts +135 -0
- package/dist/aws.d.ts.map +1 -0
- package/dist/aws.js +835 -0
- package/dist/aws.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +52 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +59 -0
- package/dist/types.js.map +1 -0
- package/package.json +60 -0
package/dist/aws.js
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AWS Bedrock Provider
|
|
3
|
+
*
|
|
4
|
+
* Provider for AWS Bedrock models including Claude, Llama, Titan, Mistral, and more.
|
|
5
|
+
* Uses AWS SDK v3 to automatically pick up credentials from environment, IAM roles, or credential files.
|
|
6
|
+
*/
|
|
7
|
+
import { detectTier } from '@aeye/ai';
|
|
8
|
+
import { getModel } from '@aeye/core';
|
|
9
|
+
import { BedrockClient, ListFoundationModelsCommand, } from '@aws-sdk/client-bedrock';
|
|
10
|
+
import { BedrockRuntimeClient, InvokeModelCommand, InvokeModelWithResponseStreamCommand, } from '@aws-sdk/client-bedrock-runtime';
|
|
11
|
+
import z from 'zod';
|
|
12
|
+
import { AWSError, AWSAuthError, AWSRateLimitError, AWSQuotaError, AWSContextWindowError } from './types';
|
|
13
|
+
// ============================================================================
|
|
14
|
+
// AWS Bedrock Provider Class
|
|
15
|
+
// ============================================================================
|
|
16
|
+
/**
|
|
17
|
+
* AWS Bedrock provider implementation for the @aeye framework.
|
|
18
|
+
*
|
|
19
|
+
* Supports the full range of AWS Bedrock capabilities including:
|
|
20
|
+
* - Chat completions with Claude, Llama, Mistral, Cohere, and more
|
|
21
|
+
* - Image generation with Stability AI models
|
|
22
|
+
* - Text embeddings with Amazon Titan
|
|
23
|
+
* - Streaming responses
|
|
24
|
+
*
|
|
25
|
+
* Uses AWS SDK v3 for automatic credential discovery and management.
|
|
26
|
+
*
|
|
27
|
+
* @example Basic usage
|
|
28
|
+
* ```typescript
|
|
29
|
+
* import { AWSBedrockProvider } from '@aeye/aws';
|
|
30
|
+
*
|
|
31
|
+
* const provider = new AWSBedrockProvider({
|
|
32
|
+
* region: 'us-east-1',
|
|
33
|
+
* });
|
|
34
|
+
*
|
|
35
|
+
* const executor = provider.createExecutor();
|
|
36
|
+
* const response = await executor(
|
|
37
|
+
* {
|
|
38
|
+
* messages: [
|
|
39
|
+
* { role: 'user', content: 'Hello!' }
|
|
40
|
+
* ]
|
|
41
|
+
* },
|
|
42
|
+
* {},
|
|
43
|
+
* { model: 'anthropic.claude-3-sonnet-20240229-v1:0' }
|
|
44
|
+
* );
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export class AWSBedrockProvider {
|
|
48
|
+
name = 'aws-bedrock';
|
|
49
|
+
config;
|
|
50
|
+
defaultMetadata;
|
|
51
|
+
bedrockClient;
|
|
52
|
+
bedrockRuntimeClient;
|
|
53
|
+
constructor(config) {
|
|
54
|
+
this.config = config;
|
|
55
|
+
const clientConfig = {
|
|
56
|
+
region: config.region || process.env.AWS_REGION || 'us-east-1',
|
|
57
|
+
credentials: config.credentials,
|
|
58
|
+
};
|
|
59
|
+
this.bedrockClient = new BedrockClient(clientConfig);
|
|
60
|
+
this.bedrockRuntimeClient = new BedrockRuntimeClient(clientConfig);
|
|
61
|
+
}
|
|
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
|
+
/**
|
|
86
|
+
* Convert AWS Bedrock model to @aeye ModelInfo format
|
|
87
|
+
*/
|
|
88
|
+
convertModel(model) {
|
|
89
|
+
const modelId = model.modelId || '';
|
|
90
|
+
const family = this.detectModelFamily(modelId);
|
|
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
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
// ============================================================================
|
|
135
|
+
// Provider Interface Implementation
|
|
136
|
+
// ============================================================================
|
|
137
|
+
/**
|
|
138
|
+
* List available models from AWS Bedrock
|
|
139
|
+
*/
|
|
140
|
+
async listModels(config) {
|
|
141
|
+
try {
|
|
142
|
+
const command = new ListFoundationModelsCommand({});
|
|
143
|
+
const response = await this.bedrockClient.send(command);
|
|
144
|
+
if (!response.modelSummaries) {
|
|
145
|
+
return [];
|
|
146
|
+
}
|
|
147
|
+
return response.modelSummaries
|
|
148
|
+
.filter(m => m.modelId) // Filter out models without IDs
|
|
149
|
+
.map(m => this.convertModel(m));
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
throw new AWSError('Failed to list models', error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Check if AWS Bedrock is accessible
|
|
157
|
+
*/
|
|
158
|
+
async checkHealth(config) {
|
|
159
|
+
try {
|
|
160
|
+
const command = new ListFoundationModelsCommand({});
|
|
161
|
+
await this.bedrockClient.send(command);
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Create an executor for chat completion requests
|
|
170
|
+
*/
|
|
171
|
+
createExecutor(config) {
|
|
172
|
+
const effectiveConfig = { ...this.config, ...config };
|
|
173
|
+
return async (request, ctx, metadata) => {
|
|
174
|
+
const model = getModel(request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat);
|
|
175
|
+
if (!model) {
|
|
176
|
+
throw new AWSError('Model is required for AWS Bedrock requests');
|
|
177
|
+
}
|
|
178
|
+
const family = this.detectModelFamily(model.id);
|
|
179
|
+
// Route to appropriate model handler
|
|
180
|
+
if (family === 'anthropic') {
|
|
181
|
+
return this.executeAnthropicModel(model.id, request, ctx);
|
|
182
|
+
}
|
|
183
|
+
else if (family === 'meta' || family === 'mistral') {
|
|
184
|
+
return this.executeLlamaStyleModel(model.id, request, ctx);
|
|
185
|
+
}
|
|
186
|
+
else if (family === 'cohere') {
|
|
187
|
+
return this.executeCohereModel(model.id, request, ctx);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
throw new AWSError(`Unsupported model family: ${family}`);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Create a streamer for streaming chat completion requests
|
|
196
|
+
*/
|
|
197
|
+
createStreamer(config) {
|
|
198
|
+
const effectiveConfig = { ...this.config, ...config };
|
|
199
|
+
return async function* (request, ctx, metadata) {
|
|
200
|
+
const model = getModel(request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat);
|
|
201
|
+
if (!model) {
|
|
202
|
+
throw new AWSError('Model is required for AWS Bedrock requests');
|
|
203
|
+
}
|
|
204
|
+
const family = this.detectModelFamily(model.id);
|
|
205
|
+
// Route to appropriate model handler
|
|
206
|
+
if (family === 'anthropic') {
|
|
207
|
+
yield* this.streamAnthropicModel(model.id, request, ctx);
|
|
208
|
+
}
|
|
209
|
+
else if (family === 'meta' || family === 'mistral') {
|
|
210
|
+
yield* this.streamLlamaStyleModel(model.id, request, ctx);
|
|
211
|
+
}
|
|
212
|
+
else if (family === 'cohere') {
|
|
213
|
+
yield* this.streamCohereModel(model.id, request, ctx);
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
throw new AWSError(`Unsupported model family for streaming: ${family}`);
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
// ============================================================================
|
|
221
|
+
// Anthropic (Claude) Model Implementation
|
|
222
|
+
// ============================================================================
|
|
223
|
+
/**
|
|
224
|
+
* Convert tools to Anthropic format
|
|
225
|
+
*/
|
|
226
|
+
convertToolsToAnthropic(request) {
|
|
227
|
+
if (!request.tools || request.tools.length === 0)
|
|
228
|
+
return undefined;
|
|
229
|
+
return request.tools.map((tool) => ({
|
|
230
|
+
name: tool.name,
|
|
231
|
+
description: tool.description,
|
|
232
|
+
input_schema: z.toJSONSchema(tool.parameters, { target: 'draft-7' }),
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Convert tool choice to Anthropic format
|
|
237
|
+
*/
|
|
238
|
+
convertToolChoiceToAnthropic(request) {
|
|
239
|
+
if (!request.toolChoice)
|
|
240
|
+
return undefined;
|
|
241
|
+
if (request.toolChoice === 'auto')
|
|
242
|
+
return { type: 'auto' };
|
|
243
|
+
if (request.toolChoice === 'required')
|
|
244
|
+
return { type: 'any' };
|
|
245
|
+
if (request.toolChoice === 'none')
|
|
246
|
+
return undefined;
|
|
247
|
+
if (typeof request.toolChoice === 'object') {
|
|
248
|
+
return { type: 'tool', name: request.toolChoice.tool };
|
|
249
|
+
}
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
async executeAnthropicModel(modelId, request, ctx) {
|
|
253
|
+
// Convert messages to Anthropic format
|
|
254
|
+
const messages = this.convertMessagesToAnthropic(request);
|
|
255
|
+
// Join all system messages
|
|
256
|
+
const systemMessages = request.messages.filter(m => m.role === 'system');
|
|
257
|
+
const system = systemMessages.length > 0
|
|
258
|
+
? systemMessages.map(m => typeof m.content === 'string' ? m.content : '').join('\n\n')
|
|
259
|
+
: undefined;
|
|
260
|
+
// Convert tools
|
|
261
|
+
const tools = this.convertToolsToAnthropic(request);
|
|
262
|
+
const tool_choice = tools ? this.convertToolChoiceToAnthropic(request) : undefined;
|
|
263
|
+
const body = {
|
|
264
|
+
anthropic_version: 'bedrock-2023-05-31',
|
|
265
|
+
max_tokens: request.maxTokens || 4096,
|
|
266
|
+
messages,
|
|
267
|
+
system,
|
|
268
|
+
temperature: request.temperature,
|
|
269
|
+
top_p: request.topP,
|
|
270
|
+
stop_sequences: request.stop,
|
|
271
|
+
tools,
|
|
272
|
+
tool_choice,
|
|
273
|
+
};
|
|
274
|
+
try {
|
|
275
|
+
const command = new InvokeModelCommand({
|
|
276
|
+
modelId,
|
|
277
|
+
contentType: 'application/json',
|
|
278
|
+
accept: 'application/json',
|
|
279
|
+
body: JSON.stringify(body),
|
|
280
|
+
});
|
|
281
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
282
|
+
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
283
|
+
// Extract text content and tool calls
|
|
284
|
+
let content = '';
|
|
285
|
+
const toolCalls = [];
|
|
286
|
+
if (responseBody.content && Array.isArray(responseBody.content)) {
|
|
287
|
+
for (const block of responseBody.content) {
|
|
288
|
+
if (block.type === 'text') {
|
|
289
|
+
content += block.text;
|
|
290
|
+
}
|
|
291
|
+
else if (block.type === 'tool_use') {
|
|
292
|
+
toolCalls.push({
|
|
293
|
+
id: block.id,
|
|
294
|
+
name: block.name,
|
|
295
|
+
arguments: JSON.stringify(block.input),
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
content,
|
|
302
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
303
|
+
finishReason: this.mapAnthropicStopReason(responseBody.stop_reason),
|
|
304
|
+
model: { id: modelId },
|
|
305
|
+
usage: {
|
|
306
|
+
text: {
|
|
307
|
+
input: responseBody.usage?.input_tokens ?? -1,
|
|
308
|
+
output: responseBody.usage?.output_tokens ?? -1,
|
|
309
|
+
},
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
this.handleAWSError(error);
|
|
315
|
+
throw error;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async *streamAnthropicModel(modelId, request, ctx) {
|
|
319
|
+
const messages = this.convertMessagesToAnthropic(request);
|
|
320
|
+
// Join all system messages
|
|
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
|
+
};
|
|
339
|
+
try {
|
|
340
|
+
const command = new InvokeModelWithResponseStreamCommand({
|
|
341
|
+
modelId,
|
|
342
|
+
contentType: 'application/json',
|
|
343
|
+
accept: 'application/json',
|
|
344
|
+
body: JSON.stringify(body),
|
|
345
|
+
});
|
|
346
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
347
|
+
if (!response.body) {
|
|
348
|
+
throw new AWSError('No response body in streaming response');
|
|
349
|
+
}
|
|
350
|
+
let inputTokens = 0;
|
|
351
|
+
let outputTokens = 0;
|
|
352
|
+
const toolCallsMap = new Map();
|
|
353
|
+
for await (const event of response.body) {
|
|
354
|
+
if (event.chunk) {
|
|
355
|
+
const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
|
|
356
|
+
if (chunk.type === 'content_block_delta' && chunk.delta?.text) {
|
|
357
|
+
yield {
|
|
358
|
+
content: chunk.delta.text,
|
|
359
|
+
finishReason: undefined,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
else if (chunk.type === 'content_block_start' && chunk.content_block?.type === 'tool_use') {
|
|
363
|
+
// Start of a tool use block
|
|
364
|
+
const index = chunk.index;
|
|
365
|
+
const toolCall = {
|
|
366
|
+
id: chunk.content_block.id,
|
|
367
|
+
name: chunk.content_block.name,
|
|
368
|
+
arguments: '',
|
|
369
|
+
named: true,
|
|
370
|
+
finished: false,
|
|
371
|
+
};
|
|
372
|
+
toolCallsMap.set(index, toolCall);
|
|
373
|
+
// Yield toolCallNamed event
|
|
374
|
+
yield {
|
|
375
|
+
toolCallNamed: {
|
|
376
|
+
id: toolCall.id,
|
|
377
|
+
name: toolCall.name,
|
|
378
|
+
arguments: toolCall.arguments,
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
else if (chunk.type === 'content_block_delta' && chunk.delta?.type === 'input_json_delta') {
|
|
383
|
+
// Tool input accumulation
|
|
384
|
+
const index = chunk.index;
|
|
385
|
+
const toolCall = toolCallsMap.get(index);
|
|
386
|
+
if (toolCall) {
|
|
387
|
+
toolCall.arguments += chunk.delta.partial_json;
|
|
388
|
+
// Yield toolCallArguments event
|
|
389
|
+
yield {
|
|
390
|
+
toolCallArguments: {
|
|
391
|
+
id: toolCall.id,
|
|
392
|
+
name: toolCall.name,
|
|
393
|
+
arguments: toolCall.arguments,
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
else if (chunk.type === 'content_block_stop') {
|
|
399
|
+
// Tool use block completed
|
|
400
|
+
const index = chunk.index;
|
|
401
|
+
const toolCall = toolCallsMap.get(index);
|
|
402
|
+
if (toolCall && !toolCall.finished) {
|
|
403
|
+
toolCall.finished = true;
|
|
404
|
+
// Yield toolCall event
|
|
405
|
+
yield {
|
|
406
|
+
toolCall: {
|
|
407
|
+
id: toolCall.id,
|
|
408
|
+
name: toolCall.name,
|
|
409
|
+
arguments: toolCall.arguments,
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
else if (chunk.type === 'message_start' && chunk.message?.usage) {
|
|
415
|
+
inputTokens = chunk.message.usage.input_tokens || 0;
|
|
416
|
+
}
|
|
417
|
+
else if (chunk.type === 'message_delta') {
|
|
418
|
+
if (chunk.delta?.stop_reason) {
|
|
419
|
+
yield {
|
|
420
|
+
content: undefined,
|
|
421
|
+
finishReason: this.mapAnthropicStopReason(chunk.delta.stop_reason),
|
|
422
|
+
usage: {
|
|
423
|
+
text: {
|
|
424
|
+
input: inputTokens,
|
|
425
|
+
output: chunk.usage?.output_tokens || 0,
|
|
426
|
+
},
|
|
427
|
+
},
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
catch (error) {
|
|
435
|
+
this.handleAWSError(error);
|
|
436
|
+
throw error;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
convertMessagesToAnthropic(request) {
|
|
440
|
+
return request.messages
|
|
441
|
+
.filter(m => m.role !== 'system')
|
|
442
|
+
.map(msg => {
|
|
443
|
+
if (msg.role === 'assistant') {
|
|
444
|
+
// Handle assistant messages with tool calls
|
|
445
|
+
if (msg.toolCalls && msg.toolCalls.length > 0) {
|
|
446
|
+
const content = [];
|
|
447
|
+
// Add text content if present
|
|
448
|
+
if (msg.content && typeof msg.content === 'string' && msg.content.trim()) {
|
|
449
|
+
content.push({ type: 'text', text: msg.content });
|
|
450
|
+
}
|
|
451
|
+
// Add tool use blocks
|
|
452
|
+
for (const toolCall of msg.toolCalls) {
|
|
453
|
+
content.push({
|
|
454
|
+
type: 'tool_use',
|
|
455
|
+
id: toolCall.id,
|
|
456
|
+
name: toolCall.name,
|
|
457
|
+
input: JSON.parse(toolCall.arguments),
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
role: 'assistant',
|
|
462
|
+
content,
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
return {
|
|
466
|
+
role: 'assistant',
|
|
467
|
+
content: typeof msg.content === 'string' ? msg.content : '',
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
else if (msg.role === 'tool') {
|
|
471
|
+
// Handle tool result messages
|
|
472
|
+
return {
|
|
473
|
+
role: 'user',
|
|
474
|
+
content: [
|
|
475
|
+
{
|
|
476
|
+
type: 'tool_result',
|
|
477
|
+
tool_use_id: msg.toolCallId,
|
|
478
|
+
content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
|
|
479
|
+
},
|
|
480
|
+
],
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
else if (msg.role === 'user') {
|
|
484
|
+
// Handle text and image content
|
|
485
|
+
if (typeof msg.content === 'string') {
|
|
486
|
+
return {
|
|
487
|
+
role: 'user',
|
|
488
|
+
content: msg.content,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
else if (Array.isArray(msg.content)) {
|
|
492
|
+
const content = msg.content.map(part => {
|
|
493
|
+
if (part.type === 'text') {
|
|
494
|
+
return { type: 'text', text: String(part.content) };
|
|
495
|
+
}
|
|
496
|
+
else if (part.type === 'image') {
|
|
497
|
+
// Convert image to base64 if needed
|
|
498
|
+
let source;
|
|
499
|
+
if (typeof part.content === 'string') {
|
|
500
|
+
if (part.content.startsWith('data:')) {
|
|
501
|
+
const match = part.content.match(/^data:([^;]+);base64,(.+)$/);
|
|
502
|
+
if (match) {
|
|
503
|
+
source = {
|
|
504
|
+
type: 'base64',
|
|
505
|
+
media_type: match[1],
|
|
506
|
+
data: match[2],
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
else if (part.content.startsWith('http')) {
|
|
511
|
+
source = {
|
|
512
|
+
type: 'url',
|
|
513
|
+
url: part.content,
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
return { type: 'image', source };
|
|
518
|
+
}
|
|
519
|
+
return { type: 'text', text: '[Unsupported content type]' };
|
|
520
|
+
});
|
|
521
|
+
return {
|
|
522
|
+
role: 'user',
|
|
523
|
+
content,
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return {
|
|
528
|
+
role: 'user',
|
|
529
|
+
content: '',
|
|
530
|
+
};
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
mapAnthropicStopReason(reason) {
|
|
534
|
+
switch (reason) {
|
|
535
|
+
case 'end_turn':
|
|
536
|
+
return 'stop';
|
|
537
|
+
case 'max_tokens':
|
|
538
|
+
return 'length';
|
|
539
|
+
case 'stop_sequence':
|
|
540
|
+
return 'stop';
|
|
541
|
+
case 'tool_use':
|
|
542
|
+
return 'tool_calls';
|
|
543
|
+
default:
|
|
544
|
+
return 'stop';
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
// ============================================================================
|
|
548
|
+
// Llama/Mistral Model Implementation
|
|
549
|
+
// ============================================================================
|
|
550
|
+
async executeLlamaStyleModel(modelId, request, ctx) {
|
|
551
|
+
const prompt = this.convertMessagesToLlamaPrompt(request);
|
|
552
|
+
const body = {
|
|
553
|
+
prompt,
|
|
554
|
+
max_gen_len: request.maxTokens || 2048,
|
|
555
|
+
temperature: request.temperature,
|
|
556
|
+
top_p: request.topP,
|
|
557
|
+
};
|
|
558
|
+
try {
|
|
559
|
+
const command = new InvokeModelCommand({
|
|
560
|
+
modelId,
|
|
561
|
+
contentType: 'application/json',
|
|
562
|
+
accept: 'application/json',
|
|
563
|
+
body: JSON.stringify(body),
|
|
564
|
+
});
|
|
565
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
566
|
+
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
567
|
+
return {
|
|
568
|
+
content: responseBody.generation || '',
|
|
569
|
+
toolCalls: [],
|
|
570
|
+
finishReason: responseBody.stop_reason === 'stop' ? 'stop' : 'length',
|
|
571
|
+
model: { id: modelId },
|
|
572
|
+
usage: {
|
|
573
|
+
text: {
|
|
574
|
+
input: responseBody.prompt_token_count ?? -1,
|
|
575
|
+
output: responseBody.generation_token_count ?? -1,
|
|
576
|
+
},
|
|
577
|
+
},
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
this.handleAWSError(error);
|
|
582
|
+
throw error;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
async *streamLlamaStyleModel(modelId, request, ctx) {
|
|
586
|
+
const prompt = this.convertMessagesToLlamaPrompt(request);
|
|
587
|
+
const body = {
|
|
588
|
+
prompt,
|
|
589
|
+
max_gen_len: request.maxTokens || 2048,
|
|
590
|
+
temperature: request.temperature,
|
|
591
|
+
top_p: request.topP,
|
|
592
|
+
};
|
|
593
|
+
try {
|
|
594
|
+
const command = new InvokeModelWithResponseStreamCommand({
|
|
595
|
+
modelId,
|
|
596
|
+
contentType: 'application/json',
|
|
597
|
+
accept: 'application/json',
|
|
598
|
+
body: JSON.stringify(body),
|
|
599
|
+
});
|
|
600
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
601
|
+
if (!response.body) {
|
|
602
|
+
throw new AWSError('No response body in streaming response');
|
|
603
|
+
}
|
|
604
|
+
for await (const event of response.body) {
|
|
605
|
+
if (event.chunk) {
|
|
606
|
+
const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
|
|
607
|
+
if (chunk.generation) {
|
|
608
|
+
yield {
|
|
609
|
+
content: chunk.generation,
|
|
610
|
+
finishReason: chunk.stop_reason === 'stop' ? 'stop' : undefined,
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
catch (error) {
|
|
617
|
+
this.handleAWSError(error);
|
|
618
|
+
throw error;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
convertMessagesToLlamaPrompt(request) {
|
|
622
|
+
// Simple prompt construction for Llama-style models
|
|
623
|
+
const messages = request.messages.map(msg => {
|
|
624
|
+
const role = msg.role === 'assistant' ? 'Assistant' : msg.role === 'system' ? 'System' : 'User';
|
|
625
|
+
const content = typeof msg.content === 'string' ? msg.content : '[Complex content]';
|
|
626
|
+
return `${role}: ${content}`;
|
|
627
|
+
});
|
|
628
|
+
return messages.join('\n\n') + '\n\nAssistant:';
|
|
629
|
+
}
|
|
630
|
+
// ============================================================================
|
|
631
|
+
// Cohere Model Implementation
|
|
632
|
+
// ============================================================================
|
|
633
|
+
async executeCohereModel(modelId, request, ctx) {
|
|
634
|
+
const prompt = this.convertMessagesToCoherePrompt(request);
|
|
635
|
+
const body = {
|
|
636
|
+
prompt,
|
|
637
|
+
max_tokens: request.maxTokens || 2048,
|
|
638
|
+
temperature: request.temperature,
|
|
639
|
+
p: request.topP,
|
|
640
|
+
stop_sequences: request.stop,
|
|
641
|
+
};
|
|
642
|
+
try {
|
|
643
|
+
const command = new InvokeModelCommand({
|
|
644
|
+
modelId,
|
|
645
|
+
contentType: 'application/json',
|
|
646
|
+
accept: 'application/json',
|
|
647
|
+
body: JSON.stringify(body),
|
|
648
|
+
});
|
|
649
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
650
|
+
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
651
|
+
return {
|
|
652
|
+
content: responseBody.generations?.[0]?.text || '',
|
|
653
|
+
toolCalls: [],
|
|
654
|
+
finishReason: responseBody.generations?.[0]?.finish_reason === 'COMPLETE' ? 'stop' : 'length',
|
|
655
|
+
model: { id: modelId },
|
|
656
|
+
usage: {
|
|
657
|
+
text: {
|
|
658
|
+
input: -1,
|
|
659
|
+
output: -1,
|
|
660
|
+
},
|
|
661
|
+
},
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
this.handleAWSError(error);
|
|
666
|
+
throw error;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
async *streamCohereModel(modelId, request, ctx) {
|
|
670
|
+
const prompt = this.convertMessagesToCoherePrompt(request);
|
|
671
|
+
const body = {
|
|
672
|
+
prompt,
|
|
673
|
+
max_tokens: request.maxTokens || 2048,
|
|
674
|
+
temperature: request.temperature,
|
|
675
|
+
p: request.topP,
|
|
676
|
+
stop_sequences: request.stop,
|
|
677
|
+
stream: true,
|
|
678
|
+
};
|
|
679
|
+
try {
|
|
680
|
+
const command = new InvokeModelWithResponseStreamCommand({
|
|
681
|
+
modelId,
|
|
682
|
+
contentType: 'application/json',
|
|
683
|
+
accept: 'application/json',
|
|
684
|
+
body: JSON.stringify(body),
|
|
685
|
+
});
|
|
686
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
687
|
+
if (!response.body) {
|
|
688
|
+
throw new AWSError('No response body in streaming response');
|
|
689
|
+
}
|
|
690
|
+
for await (const event of response.body) {
|
|
691
|
+
if (event.chunk) {
|
|
692
|
+
const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
|
|
693
|
+
if (chunk.text) {
|
|
694
|
+
yield {
|
|
695
|
+
content: chunk.text,
|
|
696
|
+
finishReason: chunk.finish_reason === 'COMPLETE' ? 'stop' : undefined,
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
this.handleAWSError(error);
|
|
704
|
+
throw error;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
convertMessagesToCoherePrompt(request) {
|
|
708
|
+
const messages = request.messages.map(msg => {
|
|
709
|
+
const content = typeof msg.content === 'string' ? msg.content : '[Complex content]';
|
|
710
|
+
return content;
|
|
711
|
+
});
|
|
712
|
+
return messages.join('\n\n');
|
|
713
|
+
}
|
|
714
|
+
// ============================================================================
|
|
715
|
+
// Image Generation (Stability AI)
|
|
716
|
+
// ============================================================================
|
|
717
|
+
generateImage = async (request, ctx, config) => {
|
|
718
|
+
const effectiveConfig = { ...this.config, ...config };
|
|
719
|
+
const model = getModel(request.model || effectiveConfig.defaultModels?.imageGenerate);
|
|
720
|
+
if (!model) {
|
|
721
|
+
throw new AWSError('Model is required for image generation');
|
|
722
|
+
}
|
|
723
|
+
// Parse size string (e.g., "1024x1024")
|
|
724
|
+
let width = 1024;
|
|
725
|
+
let height = 1024;
|
|
726
|
+
if (request.size) {
|
|
727
|
+
const sizeMatch = request.size.match(/^(\d+)x(\d+)$/);
|
|
728
|
+
if (sizeMatch) {
|
|
729
|
+
width = parseInt(sizeMatch[1], 10);
|
|
730
|
+
height = parseInt(sizeMatch[2], 10);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const body = {
|
|
734
|
+
text_prompts: [
|
|
735
|
+
{
|
|
736
|
+
text: request.prompt,
|
|
737
|
+
weight: 1,
|
|
738
|
+
},
|
|
739
|
+
],
|
|
740
|
+
cfg_scale: 7,
|
|
741
|
+
steps: 30,
|
|
742
|
+
seed: request.seed,
|
|
743
|
+
width,
|
|
744
|
+
height,
|
|
745
|
+
};
|
|
746
|
+
try {
|
|
747
|
+
const command = new InvokeModelCommand({
|
|
748
|
+
modelId: model.id,
|
|
749
|
+
contentType: 'application/json',
|
|
750
|
+
accept: 'application/json',
|
|
751
|
+
body: JSON.stringify(body),
|
|
752
|
+
});
|
|
753
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
754
|
+
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
755
|
+
const images = responseBody.artifacts?.map((artifact) => ({
|
|
756
|
+
url: `data:image/png;base64,${artifact.base64}`,
|
|
757
|
+
base64: artifact.base64,
|
|
758
|
+
revisedPrompt: undefined,
|
|
759
|
+
})) || [];
|
|
760
|
+
return {
|
|
761
|
+
images,
|
|
762
|
+
model,
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
this.handleAWSError(error);
|
|
767
|
+
throw error;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
// ============================================================================
|
|
771
|
+
// Embeddings (Amazon Titan)
|
|
772
|
+
// ============================================================================
|
|
773
|
+
embed = async (request, ctx, config) => {
|
|
774
|
+
const effectiveConfig = { ...this.config, ...config };
|
|
775
|
+
const model = getModel(request.model || effectiveConfig.defaultModels?.embedding);
|
|
776
|
+
if (!model) {
|
|
777
|
+
throw new AWSError('Model is required for embeddings');
|
|
778
|
+
}
|
|
779
|
+
// AWS Titan embeddings expect a single text input
|
|
780
|
+
const body = {
|
|
781
|
+
inputText: request.texts[0] || '',
|
|
782
|
+
};
|
|
783
|
+
try {
|
|
784
|
+
const command = new InvokeModelCommand({
|
|
785
|
+
modelId: model.id,
|
|
786
|
+
contentType: 'application/json',
|
|
787
|
+
accept: 'application/json',
|
|
788
|
+
body: JSON.stringify(body),
|
|
789
|
+
});
|
|
790
|
+
const response = await this.bedrockRuntimeClient.send(command);
|
|
791
|
+
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
|
792
|
+
// Handle multiple texts if provided
|
|
793
|
+
const embeddings = request.texts.map(() => responseBody.embedding);
|
|
794
|
+
return {
|
|
795
|
+
embeddings,
|
|
796
|
+
model,
|
|
797
|
+
usage: {
|
|
798
|
+
embeddings: {
|
|
799
|
+
tokens: responseBody.inputTextTokenCount ?? -1,
|
|
800
|
+
},
|
|
801
|
+
},
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
catch (error) {
|
|
805
|
+
this.handleAWSError(error);
|
|
806
|
+
throw error;
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
// ============================================================================
|
|
810
|
+
// Error Handling
|
|
811
|
+
// ============================================================================
|
|
812
|
+
handleAWSError(error) {
|
|
813
|
+
const errorName = error.name || '';
|
|
814
|
+
const errorMessage = error.message || '';
|
|
815
|
+
// Authentication errors
|
|
816
|
+
if (errorName === 'UnrecognizedClientException' || errorName === 'InvalidSignatureException') {
|
|
817
|
+
throw new AWSAuthError(error);
|
|
818
|
+
}
|
|
819
|
+
// Rate limiting
|
|
820
|
+
if (errorName === 'ThrottlingException' || errorName === 'TooManyRequestsException') {
|
|
821
|
+
throw new AWSRateLimitError('Rate limit exceeded', undefined, error);
|
|
822
|
+
}
|
|
823
|
+
// Quota errors
|
|
824
|
+
if (errorName === 'ServiceQuotaExceededException') {
|
|
825
|
+
throw new AWSQuotaError(error);
|
|
826
|
+
}
|
|
827
|
+
// Context window errors
|
|
828
|
+
if (errorMessage.includes('context length') || errorMessage.includes('token limit')) {
|
|
829
|
+
throw new AWSContextWindowError('Context window exceeded', undefined, error);
|
|
830
|
+
}
|
|
831
|
+
// Re-throw as generic AWS error
|
|
832
|
+
throw new AWSError(errorMessage || 'Unknown AWS Bedrock error', error);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
//# sourceMappingURL=aws.js.map
|