@aeye/aws 0.3.7 → 0.3.8

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/dist/aws.js CHANGED
@@ -3,12 +3,12 @@
3
3
  *
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
+ * All chat LLM calls use the Bedrock Converse API for a unified request/response format across models.
6
7
  */
7
8
  import { getModel, toJSONSchema, } from '@aeye/core';
8
9
  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';
10
+ import { BedrockRuntimeClient, ConverseCommand, ConverseStreamCommand, InvokeModelCommand, } from '@aws-sdk/client-bedrock-runtime';
11
+ import { convertAWSModel } from './common';
12
12
  import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLimitError } from './types';
13
13
  // ============================================================================
14
14
  // AWS Bedrock Provider Class
@@ -139,21 +139,7 @@ export class AWSBedrockProvider {
139
139
  if (!modelInput) {
140
140
  throw new AWSError('Model is required for AWS Bedrock requests');
141
141
  }
142
- const model = getModel(modelInput);
143
- const family = detectAWSFamily(model.id);
144
- // Route to appropriate model handler
145
- if (family === 'anthropic') {
146
- return self.executeAnthropicModel(modelInput, request, ctx);
147
- }
148
- else if (family === 'meta' || family === 'mistral') {
149
- return self.executeLlamaStyleModel(model.id, request, ctx);
150
- }
151
- else if (family === 'cohere') {
152
- return self.executeCohereModel(model.id, request, ctx);
153
- }
154
- else {
155
- throw new AWSError(`Unsupported model family: ${family}`);
156
- }
142
+ return self.executeWithConverse(modelInput, request, ctx);
157
143
  };
158
144
  }
159
145
  /**
@@ -163,136 +149,89 @@ export class AWSBedrockProvider {
163
149
  const effectiveConfig = { ...this.config, ...config };
164
150
  const self = this;
165
151
  return async function* (request, ctx, metadata) {
166
- const model = getModel(request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat);
167
- if (!model) {
152
+ const modelInput = request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat;
153
+ if (!modelInput) {
168
154
  throw new AWSError('Model is required for AWS Bedrock requests');
169
155
  }
170
- const family = detectAWSFamily(model.id);
171
- // Route to appropriate model handler
172
- if (family === 'anthropic') {
173
- return yield* self.streamAnthropicModel(model.id, request, ctx);
174
- }
175
- else if (family === 'meta' || family === 'mistral') {
176
- return yield* self.streamLlamaStyleModel(model.id, request, ctx);
177
- }
178
- else if (family === 'cohere') {
179
- return yield* self.streamCohereModel(model.id, request, ctx);
180
- }
181
- else {
182
- throw new AWSError(`Unsupported model family for streaming: ${family}`);
183
- }
156
+ yield* self.streamWithConverse(modelInput, request, ctx);
184
157
  };
185
158
  }
186
159
  // ============================================================================
187
- // Anthropic (Claude) Model Implementation
160
+ // Unified Converse API Implementation
188
161
  // ============================================================================
189
162
  /**
190
- * Convert tools to Anthropic format
163
+ * Build a ConverseCommandInput from a generic @aeye/core Request.
191
164
  */
192
- convertToolsToAnthropic(request) {
193
- if (!request.tools || request.tools.length === 0)
194
- return undefined;
195
- return request.tools.map((tool) => ({
196
- name: tool.name,
197
- description: tool.description,
198
- input_schema: toJSONSchema(tool.parameters, tool.strict ?? true),
199
- }));
200
- }
201
- /**
202
- * Convert tool choice to Anthropic format
203
- */
204
- convertToolChoiceToAnthropic(request) {
205
- if (!request.toolChoice)
206
- return undefined;
207
- if (request.toolChoice === 'auto')
208
- return { type: 'auto' };
209
- if (request.toolChoice === 'required')
210
- return { type: 'any' };
211
- if (request.toolChoice === 'none')
212
- return undefined;
213
- if (typeof request.toolChoice === 'object') {
214
- return { type: 'tool', name: request.toolChoice.tool };
215
- }
216
- return undefined;
217
- }
218
- convertRequestToAnthropic(model, request) {
219
- const messages = this.convertMessagesToAnthropic(request);
220
- const tools = this.convertToolsToAnthropic(request);
221
- const tool_choice = tools ? this.convertToolChoiceToAnthropic(request) : undefined;
222
- const systemMessages = request.messages.filter(m => m.role === 'system');
223
- const system = systemMessages.length > 0
224
- ? systemMessages.map((m) => ({
225
- type: 'text',
226
- text: typeof m.content === 'string' ? m.content : m.content.map(m => m.content).join('\n'),
227
- }))
228
- : undefined;
229
- const modelMax = isModelInfo(model) ? model.maxOutputTokens : undefined;
165
+ convertRequestToConverse(modelId, request) {
166
+ const messages = this.convertMessagesToConverse(request);
167
+ const system = this.convertSystemToConverse(request);
168
+ const toolConfig = this.convertToolsToConverse(request);
169
+ const model = getModel(request.model);
170
+ const maxTokens = request.maxTokens ?? (typeof model !== 'string' && model?.maxOutputTokens ? model.maxOutputTokens : undefined);
230
171
  return {
231
- anthropic_version: this.config.anthropic?.version ?? 'bedrock-2023-05-31',
232
- anthropic_beta: this.config.anthropic?.beta,
233
- max_tokens: modelMax || 4096,
172
+ modelId,
234
173
  messages,
235
174
  system,
236
- temperature: request.temperature,
237
- top_p: request.topP,
238
- stop_sequences: request.stop ? Array.isArray(request.stop) ? request.stop : [request.stop] : undefined,
239
- tools,
240
- tool_choice,
241
- metadata: {
242
- user_id: request.userKey || undefined,
175
+ inferenceConfig: {
176
+ maxTokens,
177
+ temperature: request.temperature,
178
+ topP: request.topP,
179
+ stopSequences: request.stop
180
+ ? Array.isArray(request.stop) ? request.stop : [request.stop]
181
+ : undefined,
243
182
  },
244
- ...request.extra,
183
+ toolConfig,
184
+ additionalModelRequestFields: request.extra,
245
185
  };
246
186
  }
247
- async executeAnthropicModel(model, request, ctx) {
248
- const body = this.convertRequestToAnthropic(model, request);
249
- const modelId = this.applyModelPrefix(getModel(model)?.id || '');
187
+ /**
188
+ * Execute a non-streaming chat completion using the Converse API.
189
+ */
190
+ async executeWithConverse(modelInput, request, ctx) {
191
+ const model = getModel(modelInput);
192
+ const modelId = this.applyModelPrefix(model.id);
193
+ const params = this.convertRequestToConverse(modelId, request);
250
194
  try {
251
- const command = new InvokeModelCommand({
252
- modelId,
253
- contentType: 'application/json',
254
- accept: 'application/json',
255
- body: JSON.stringify(body),
256
- });
257
- // Call pre-request hook with command
195
+ const command = new ConverseCommand(params);
258
196
  await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
259
197
  const response = await this.bedrockRuntimeClient.send(command);
260
- const responseBody = JSON.parse(new TextDecoder().decode(response.body));
261
- // Extract text content and tool calls
262
198
  let content = '';
263
- let reasoning = undefined;
199
+ let reasoning;
264
200
  const toolCalls = [];
265
- if (responseBody.content) {
266
- for (const block of responseBody.content) {
267
- if (block.type === 'text') {
201
+ const outputMessage = response.output?.message;
202
+ if (outputMessage?.content) {
203
+ for (const block of outputMessage.content) {
204
+ if ('text' in block && block.text !== undefined) {
268
205
  content += block.text;
269
206
  }
270
- else if (block.type === 'tool_use') {
207
+ else if ('toolUse' in block && block.toolUse) {
271
208
  toolCalls.push({
272
- id: block.id,
273
- name: block.name,
274
- arguments: JSON.stringify(block.input),
209
+ id: block.toolUse.toolUseId,
210
+ name: block.toolUse.name,
211
+ arguments: JSON.stringify(block.toolUse.input ?? {}),
275
212
  });
276
213
  }
277
- else if (block.type === 'thinking') {
278
- reasoning = (reasoning || '') + block.thinking;
214
+ else if ('reasoningContent' in block && block.reasoningContent) {
215
+ const rc = block.reasoningContent;
216
+ if ('reasoningText' in rc && rc.reasoningText) {
217
+ reasoning = (reasoning ?? '') + rc.reasoningText.text;
218
+ }
279
219
  }
280
220
  }
281
221
  }
282
222
  const result = {
283
223
  content,
284
- reasoning,
224
+ reasoning: reasoning !== undefined ? { content: reasoning } : undefined,
285
225
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
286
- finishReason: this.mapAnthropicStopReason(responseBody.stop_reason),
287
- model,
226
+ finishReason: this.mapStopReason(response.stopReason),
227
+ model: modelInput,
288
228
  usage: {
289
229
  text: {
290
- input: responseBody.usage?.input_tokens ?? -1,
291
- output: responseBody.usage?.output_tokens ?? -1,
230
+ input: response.usage?.inputTokens ?? -1,
231
+ output: response.usage?.outputTokens ?? -1,
292
232
  },
293
233
  },
294
234
  };
295
- // Call post-request hook with command
296
235
  await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
297
236
  return result;
298
237
  }
@@ -301,127 +240,107 @@ export class AWSBedrockProvider {
301
240
  throw error;
302
241
  }
303
242
  }
304
- async *streamAnthropicModel(model, request, ctx) {
305
- const body = this.convertRequestToAnthropic(model, request);
306
- const modelId = this.applyModelPrefix(getModel(model)?.id || '');
243
+ /**
244
+ * Execute a streaming chat completion using the Converse Stream API.
245
+ */
246
+ async *streamWithConverse(modelInput, request, ctx) {
247
+ const model = getModel(modelInput);
248
+ const modelId = this.applyModelPrefix(model.id);
249
+ const params = this.convertRequestToConverse(modelId, request);
307
250
  try {
308
- const command = new InvokeModelWithResponseStreamCommand({
309
- modelId,
310
- contentType: 'application/json',
311
- accept: 'application/json',
312
- body: JSON.stringify(body),
313
- });
314
- // Call pre-request hook with command
251
+ const command = new ConverseStreamCommand(params);
315
252
  await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
316
253
  const response = await this.bedrockRuntimeClient.send(command);
317
- if (!response.body) {
318
- throw new AWSError('No response body in streaming response');
254
+ if (!response.stream) {
255
+ throw new AWSError('No stream in streaming response');
319
256
  }
320
257
  let inputTokens = 0;
321
258
  let outputTokens = 0;
322
259
  let accumulatedContent = '';
323
- let accumulatedReasoning = '';
324
- let finishReason = undefined;
260
+ let finishReason = 'stop';
325
261
  const toolCallsMap = new Map();
326
262
  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;
263
+ for await (const event of response.stream) {
264
+ if (event.contentBlockDelta?.delta) {
265
+ const delta = event.contentBlockDelta.delta;
266
+ const index = event.contentBlockDelta.contentBlockIndex ?? 0;
267
+ if ('text' in delta && delta.text !== undefined) {
268
+ accumulatedContent += delta.text;
269
+ yield { content: delta.text };
270
+ }
271
+ else if ('toolUse' in delta && delta.toolUse?.input !== undefined) {
272
+ const toolCall = toolCallsMap.get(index);
273
+ if (toolCall) {
274
+ toolCall.arguments += delta.toolUse.input;
275
+ yield {
276
+ toolCallArguments: {
277
+ id: toolCall.id,
278
+ name: toolCall.name,
279
+ arguments: toolCall.arguments,
280
+ },
281
+ };
282
+ }
283
+ }
284
+ else if ('reasoningContent' in delta && delta.reasoningContent) {
285
+ const rc = delta.reasoningContent;
286
+ if ('text' in rc && rc.text !== undefined) {
287
+ yield { reasoning: { content: rc.text } };
364
288
  }
365
289
  }
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;
290
+ }
291
+ else if (event.contentBlockStart?.start) {
292
+ const start = event.contentBlockStart.start;
293
+ const index = event.contentBlockStart.contentBlockIndex ?? 0;
294
+ if ('toolUse' in start && start.toolUse) {
369
295
  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,
296
+ id: start.toolUse.toolUseId,
297
+ name: start.toolUse.name,
298
+ arguments: '',
374
299
  finished: false,
375
300
  };
376
301
  toolCallsMap.set(index, toolCall);
377
- // Yield toolCallNamed event
378
302
  yield {
379
303
  toolCallNamed: {
380
304
  id: toolCall.id,
381
305
  name: toolCall.name,
382
- arguments: toolCall.arguments,
306
+ arguments: '',
383
307
  },
384
308
  };
385
309
  }
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,
398
- },
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
- }
310
+ }
311
+ else if (event.contentBlockStop) {
312
+ const index = event.contentBlockStop.contentBlockIndex ?? 0;
313
+ const toolCall = toolCallsMap.get(index);
314
+ if (toolCall && !toolCall.finished) {
315
+ toolCall.finished = true;
316
+ yield {
317
+ toolCall: {
318
+ id: toolCall.id,
319
+ name: toolCall.name,
320
+ arguments: toolCall.arguments,
321
+ },
322
+ };
419
323
  }
420
324
  }
325
+ else if (event.messageStop) {
326
+ finishReason = this.mapStopReason(event.messageStop.stopReason);
327
+ yield { finishReason };
328
+ }
329
+ else if (event.metadata?.usage) {
330
+ inputTokens = event.metadata.usage.inputTokens ?? 0;
331
+ outputTokens = event.metadata.usage.outputTokens ?? 0;
332
+ yield {
333
+ usage: {
334
+ text: {
335
+ input: inputTokens,
336
+ output: outputTokens,
337
+ },
338
+ },
339
+ };
340
+ }
421
341
  }
422
342
  }
423
343
  finally {
424
- // Call post-request hook with accumulated response
425
344
  const toolCalls = Array.from(toolCallsMap.values()).map(tc => ({
426
345
  id: tc.id,
427
346
  name: tc.name,
@@ -431,7 +350,7 @@ export class AWSBedrockProvider {
431
350
  content: accumulatedContent,
432
351
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
433
352
  finishReason,
434
- model,
353
+ model: modelInput,
435
354
  usage: {
436
355
  text: {
437
356
  input: inputTokens,
@@ -447,367 +366,192 @@ export class AWSBedrockProvider {
447
366
  throw error;
448
367
  }
449
368
  }
450
- convertMessagesToAnthropic(request) {
451
- const toContent = (part) => {
452
- if (typeof part === 'string') {
453
- return [{ type: 'text', text: part }];
454
- }
455
- else {
456
- return part;
369
+ /**
370
+ * Convert system messages to the Converse API system format.
371
+ */
372
+ convertSystemToConverse(request) {
373
+ const systemMessages = request.messages.filter(m => m.role === 'system');
374
+ if (systemMessages.length === 0)
375
+ return undefined;
376
+ return systemMessages.map((m) => ({
377
+ text: typeof m.content === 'string'
378
+ ? m.content
379
+ : m.content.map(c => String(c.content)).join('\n'),
380
+ }));
381
+ }
382
+ /**
383
+ * Convert @aeye/core messages to AWS Bedrock Converse API message format.
384
+ * Filters out system messages (handled via convertSystemToConverse).
385
+ * Merges consecutive messages with the same role as required by the API.
386
+ */
387
+ convertMessagesToConverse(request) {
388
+ const rawMessages = [];
389
+ for (const msg of request.messages) {
390
+ if (msg.role === 'system')
391
+ continue;
392
+ if (msg.role === 'user') {
393
+ const content = [];
394
+ if (typeof msg.content === 'string') {
395
+ if (msg.content.trim()) {
396
+ content.push({ text: msg.content });
397
+ }
398
+ }
399
+ else {
400
+ for (const part of msg.content) {
401
+ if (part.type === 'text') {
402
+ if (String(part.content).trim()) {
403
+ content.push({ text: String(part.content) });
404
+ }
405
+ }
406
+ else if (part.type === 'image') {
407
+ const imageBlock = this.convertImageContent(part.content);
408
+ if (imageBlock) {
409
+ content.push(imageBlock);
410
+ }
411
+ }
412
+ }
413
+ }
414
+ if (content.length > 0) {
415
+ rawMessages.push({ role: 'user', content });
416
+ }
457
417
  }
458
- };
459
- const messages = request.messages
460
- .filter(m => m.role !== 'system')
461
- .map((msg) => {
462
- if (msg.role === 'assistant') {
463
- // Handle assistant messages with tool calls
418
+ else if (msg.role === 'assistant') {
419
+ const content = [];
420
+ if (msg.content && typeof msg.content === 'string' && msg.content.trim()) {
421
+ content.push({ text: msg.content });
422
+ }
464
423
  if (msg.toolCalls && msg.toolCalls.length > 0) {
465
- const content = [];
466
- // Add text content if present
467
- if (msg.content && typeof msg.content === 'string' && msg.content.trim()) {
468
- content.push({ type: 'text', text: msg.content });
469
- }
470
- // Add tool use blocks
471
- for (const toolCall of msg.toolCalls) {
424
+ for (const tc of msg.toolCalls) {
425
+ let input = {};
426
+ try {
427
+ input = JSON.parse(tc.arguments);
428
+ }
429
+ catch {
430
+ input = { _raw: tc.arguments };
431
+ }
472
432
  content.push({
473
- type: 'tool_use',
474
- id: toolCall.id,
475
- name: toolCall.name,
476
- input: (() => {
477
- try {
478
- return JSON.parse(toolCall.arguments);
479
- }
480
- catch (e) {
481
- return { badArguments: toolCall.arguments };
482
- }
483
- })(),
433
+ toolUse: {
434
+ toolUseId: tc.id,
435
+ name: tc.name,
436
+ input: input,
437
+ },
484
438
  });
485
439
  }
486
- return {
487
- role: 'assistant',
488
- content,
489
- };
490
440
  }
491
- return {
492
- role: 'assistant',
493
- content: typeof msg.content === 'string' ? msg.content : msg.content.map(m => m.content).join('\n\n'),
494
- };
441
+ if (content.length > 0) {
442
+ rawMessages.push({ role: 'assistant', content });
443
+ }
495
444
  }
496
445
  else if (msg.role === 'tool') {
497
- // Handle tool result messages
498
- return {
446
+ rawMessages.push({
499
447
  role: 'user',
500
448
  content: [
501
449
  {
502
- type: 'tool_result',
503
- tool_use_id: msg.toolCallId,
504
- content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
450
+ toolResult: {
451
+ toolUseId: msg.toolCallId,
452
+ content: [
453
+ {
454
+ text: typeof msg.content === 'string'
455
+ ? msg.content
456
+ : JSON.stringify(msg.content),
457
+ },
458
+ ],
459
+ },
505
460
  },
506
461
  ],
507
- };
508
- }
509
- else if (msg.role === 'user') {
510
- // Handle text and image content
511
- if (typeof msg.content === 'string') {
512
- return {
513
- role: 'user',
514
- content: msg.content,
515
- };
516
- }
517
- else if (Array.isArray(msg.content)) {
518
- const content = msg.content.map((part) => {
519
- if (part.type === 'text') {
520
- return { type: 'text', text: String(part.content) };
521
- }
522
- else if (part.type === 'image') {
523
- // Convert image to base64 if needed
524
- let source;
525
- if (typeof part.content === 'string') {
526
- if (part.content.startsWith('data:')) {
527
- const match = part.content.match(/^data:([^;]+);base64,(.+)$/);
528
- if (match) {
529
- source = {
530
- type: 'base64',
531
- media_type: match[1],
532
- data: match[2],
533
- };
534
- }
535
- else if (part.content.startsWith('http')) {
536
- source = {
537
- type: 'url',
538
- url: part.content,
539
- };
540
- }
541
- }
542
- else {
543
- source = {
544
- type: 'url',
545
- url: part.content,
546
- };
547
- }
548
- }
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
- }
558
- }
559
- return { type: 'text', text: '[Unsupported content type]' };
560
- });
561
- return {
562
- role: 'user',
563
- content,
564
- };
565
- }
462
+ });
566
463
  }
567
- return {
568
- role: 'user',
569
- content: '<unsupported role>',
570
- };
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;
464
+ }
465
+ // Merge consecutive messages with the same role (required by Converse API)
466
+ const merged = [];
467
+ for (const msg of rawMessages) {
468
+ const last = merged[merged.length - 1];
469
+ if (last && last.role === msg.role) {
470
+ last.content = [...(last.content ?? []), ...(msg.content ?? [])];
586
471
  }
587
472
  else {
588
- if (lastMessage) {
589
- joinedMessages.push(lastMessage);
590
- }
591
- lastMessage = msg;
473
+ merged.push({ role: msg.role, content: [...(msg.content ?? [])] });
592
474
  }
593
475
  }
594
- if (lastMessage) {
595
- joinedMessages.push(lastMessage);
476
+ // Ensure there is at least one user message
477
+ if (merged.length === 0) {
478
+ merged.push({ role: 'user', content: [{ text: 'Perform the requested operation.' }] });
596
479
  }
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');
480
+ return merged;
481
+ }
482
+ /**
483
+ * Convert an image content value to a Converse API ContentBlock.
484
+ * Only base64 data URIs are natively supported; URL images are not supported
485
+ * by the Converse API without fetching the bytes first.
486
+ */
487
+ convertImageContent(content) {
488
+ const src = content instanceof URL ? content.href : typeof content === 'string' ? content : null;
489
+ if (!src)
490
+ return null;
491
+ // data URI: data:<mediaType>;base64,<data>
492
+ const match = src.match(/^data:([^;]+);base64,(.+)$/);
493
+ if (match) {
494
+ const mediaType = match[1].toLowerCase();
495
+ const format = (mediaType.includes('png') ? 'png' :
496
+ mediaType.includes('jpeg') || mediaType.includes('jpg') ? 'jpeg' :
497
+ mediaType.includes('gif') ? 'gif' :
498
+ mediaType.includes('webp') ? 'webp' : null);
499
+ if (format) {
500
+ const bytes = Buffer.from(match[2], 'base64');
501
+ return { image: { format, source: { bytes } } };
602
502
  }
603
503
  }
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
- }
504
+ // URL images are not natively supported by the Converse API
505
+ return null;
506
+ }
507
+ /**
508
+ * Convert @aeye/core tool definitions to AWS Bedrock Converse API tool format.
509
+ */
510
+ convertToolsToConverse(request) {
511
+ if (!request.tools || request.tools.length === 0)
512
+ return undefined;
513
+ const tools = request.tools.map(tool => ({
514
+ toolSpec: {
515
+ name: tool.name,
516
+ description: tool.description,
517
+ inputSchema: {
518
+ json: toJSONSchema(tool.parameters, tool.strict ?? true),
519
+ },
520
+ },
521
+ }));
522
+ let toolChoice;
523
+ if (request.toolChoice === 'auto') {
524
+ toolChoice = { auto: {} };
525
+ }
526
+ else if (request.toolChoice === 'required') {
527
+ toolChoice = { any: {} };
614
528
  }
615
- return joinedMessages;
529
+ else if (typeof request.toolChoice === 'object' && request.toolChoice !== null) {
530
+ toolChoice = { tool: { name: request.toolChoice.tool } };
531
+ }
532
+ return { tools, toolChoice };
616
533
  }
617
- mapAnthropicStopReason(reason) {
618
- if (!reason)
619
- return 'stop';
620
- switch (reason) {
534
+ /**
535
+ * Map a Bedrock Converse API stop reason to the @aeye/core FinishReason type.
536
+ */
537
+ mapStopReason(stopReason) {
538
+ switch (stopReason) {
621
539
  case 'end_turn':
622
540
  return 'stop';
623
541
  case 'max_tokens':
542
+ case 'model_context_window_exceeded':
624
543
  return 'length';
625
544
  case 'stop_sequence':
626
545
  return 'stop';
627
546
  case 'tool_use':
628
547
  return 'tool_calls';
548
+ case 'content_filtered':
549
+ return 'content_filter';
629
550
  default:
630
551
  return 'stop';
631
552
  }
632
553
  }
633
554
  // ============================================================================
634
- // Llama/Mistral Model Implementation
635
- // ============================================================================
636
- async executeLlamaStyleModel(modelId, request, ctx) {
637
- const prompt = this.convertMessagesToLlamaPrompt(request);
638
- const body = {
639
- prompt,
640
- max_gen_len: request.maxTokens || 2048,
641
- temperature: request.temperature,
642
- top_p: request.topP,
643
- };
644
- try {
645
- const command = new InvokeModelCommand({
646
- modelId: this.applyModelPrefix(modelId),
647
- contentType: 'application/json',
648
- accept: 'application/json',
649
- body: JSON.stringify(body),
650
- });
651
- // Call pre-request hook with command
652
- await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
653
- const response = await this.bedrockRuntimeClient.send(command);
654
- const responseBody = JSON.parse(new TextDecoder().decode(response.body));
655
- const result = {
656
- content: responseBody.generation || '',
657
- toolCalls: [],
658
- finishReason: responseBody.stop_reason === 'stop' ? 'stop' : 'length',
659
- model: { id: modelId },
660
- usage: {
661
- text: {
662
- input: responseBody.prompt_token_count ?? -1,
663
- output: responseBody.generation_token_count ?? -1,
664
- },
665
- },
666
- };
667
- // Call post-request hook with command
668
- await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
669
- return result;
670
- }
671
- catch (error) {
672
- this.handleAWSError(error);
673
- throw error;
674
- }
675
- }
676
- async *streamLlamaStyleModel(modelId, request, ctx) {
677
- const prompt = this.convertMessagesToLlamaPrompt(request);
678
- const body = {
679
- prompt,
680
- max_gen_len: request.maxTokens || 2048,
681
- temperature: request.temperature,
682
- top_p: request.topP,
683
- };
684
- try {
685
- const command = new InvokeModelWithResponseStreamCommand({
686
- modelId: this.applyModelPrefix(modelId),
687
- contentType: 'application/json',
688
- accept: 'application/json',
689
- body: JSON.stringify(body),
690
- });
691
- const response = await this.bedrockRuntimeClient.send(command);
692
- if (!response.body) {
693
- throw new AWSError('No response body in streaming response');
694
- }
695
- for await (const event of response.body) {
696
- if (event.chunk) {
697
- const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
698
- if (chunk.generation) {
699
- yield {
700
- content: chunk.generation,
701
- finishReason: chunk.stop_reason === 'stop' ? 'stop' : undefined,
702
- };
703
- }
704
- }
705
- }
706
- }
707
- catch (error) {
708
- this.handleAWSError(error);
709
- throw error;
710
- }
711
- }
712
- convertMessagesToLlamaPrompt(request) {
713
- // Simple prompt construction for Llama-style models
714
- const messages = request.messages.map(msg => {
715
- const role = msg.role === 'assistant' ? 'Assistant' : msg.role === 'system' ? 'System' : 'User';
716
- const content = typeof msg.content === 'string' ? msg.content : '[Complex content]';
717
- return `${role}: ${content}`;
718
- });
719
- return messages.join('\n\n') + '\n\nAssistant:';
720
- }
721
- // ============================================================================
722
- // Cohere Model Implementation
723
- // ============================================================================
724
- async executeCohereModel(modelId, request, ctx) {
725
- const prompt = this.convertMessagesToCoherePrompt(request);
726
- const body = {
727
- prompt,
728
- max_tokens: request.maxTokens || 2048,
729
- temperature: request.temperature,
730
- p: request.topP,
731
- stop_sequences: request.stop,
732
- };
733
- try {
734
- const command = new InvokeModelCommand({
735
- modelId: this.applyModelPrefix(modelId),
736
- contentType: 'application/json',
737
- accept: 'application/json',
738
- body: JSON.stringify(body),
739
- });
740
- // Call pre-request hook with command
741
- await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
742
- const response = await this.bedrockRuntimeClient.send(command);
743
- const responseBody = JSON.parse(new TextDecoder().decode(response.body));
744
- const result = {
745
- content: responseBody.generations?.[0]?.text || '',
746
- toolCalls: [],
747
- finishReason: responseBody.generations?.[0]?.finish_reason === 'COMPLETE' ? 'stop' : 'length',
748
- model: { id: modelId },
749
- usage: {
750
- text: {
751
- input: -1,
752
- output: -1,
753
- },
754
- },
755
- };
756
- // Call post-request hook with command
757
- await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
758
- return result;
759
- }
760
- catch (error) {
761
- this.handleAWSError(error);
762
- throw error;
763
- }
764
- }
765
- async *streamCohereModel(modelId, request, ctx) {
766
- const prompt = this.convertMessagesToCoherePrompt(request);
767
- const body = {
768
- prompt,
769
- max_tokens: request.maxTokens || 2048,
770
- temperature: request.temperature,
771
- p: request.topP,
772
- stop_sequences: request.stop,
773
- stream: true,
774
- };
775
- try {
776
- const command = new InvokeModelWithResponseStreamCommand({
777
- modelId: this.applyModelPrefix(modelId),
778
- contentType: 'application/json',
779
- accept: 'application/json',
780
- body: JSON.stringify(body),
781
- });
782
- const response = await this.bedrockRuntimeClient.send(command);
783
- if (!response.body) {
784
- throw new AWSError('No response body in streaming response');
785
- }
786
- for await (const event of response.body) {
787
- if (event.chunk) {
788
- const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
789
- if (chunk.text) {
790
- yield {
791
- content: chunk.text,
792
- finishReason: chunk.finish_reason === 'COMPLETE' ? 'stop' : undefined,
793
- };
794
- }
795
- }
796
- }
797
- }
798
- catch (error) {
799
- this.handleAWSError(error);
800
- throw error;
801
- }
802
- }
803
- convertMessagesToCoherePrompt(request) {
804
- const messages = request.messages.map(msg => {
805
- const content = typeof msg.content === 'string' ? msg.content : '[Complex content]';
806
- return content;
807
- });
808
- return messages.join('\n\n');
809
- }
810
- // ============================================================================
811
555
  // Image Generation (Stability AI)
812
556
  // ============================================================================
813
557
  generateImage = async (request, ctx, config) => {