@aeye/aws 0.3.7 → 0.3.9
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/aeye-aws.md +171 -0
- package/dist/aws.d.ts +92 -54
- package/dist/aws.d.ts.map +1 -1
- package/dist/aws.js +364 -534
- package/dist/aws.js.map +1 -1
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +5 -2
- package/dist/common.js.map +1 -1
- package/package.json +5 -5
package/dist/aws.js
CHANGED
|
@@ -3,14 +3,40 @@
|
|
|
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
|
-
import {
|
|
8
|
+
import { isModelInfo, resolveStrictFormat } from '@aeye/ai';
|
|
9
|
+
import { getDescriptor, getModel, LENIENT, SchemaBudget, strictestOf, strictify, strictPriority, toJSONSchema, } from '@aeye/core';
|
|
8
10
|
import { BedrockClient, ListFoundationModelsCommand } from '@aws-sdk/client-bedrock';
|
|
9
|
-
import { BedrockRuntimeClient, InvokeModelCommand,
|
|
10
|
-
import {
|
|
11
|
-
import { convertAWSModel, detectAWSFamily } from './common';
|
|
11
|
+
import { BedrockRuntimeClient, ConverseCommand, ConverseStreamCommand, InvokeModelCommand, } from '@aws-sdk/client-bedrock-runtime';
|
|
12
|
+
import { convertAWSModel } from './common';
|
|
12
13
|
import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLimitError } from './types';
|
|
13
14
|
// ============================================================================
|
|
15
|
+
// AWS Bedrock Provider Configuration
|
|
16
|
+
// ============================================================================
|
|
17
|
+
/**
|
|
18
|
+
* Resolve the full ModelInfo for the request when available.
|
|
19
|
+
*
|
|
20
|
+
* BaseAPI injects `selected.model` into `ctx.metadata.model` after model
|
|
21
|
+
* selection; on the standard execution path we read strict-format
|
|
22
|
+
* declarations from there. Returns undefined when no ModelInfo is available
|
|
23
|
+
* (the convert call then falls back to LENIENT — silent best-effort).
|
|
24
|
+
*/
|
|
25
|
+
function pickAwsModelInfo(ctx, modelId) {
|
|
26
|
+
const candidates = [ctx?.metadata?.model];
|
|
27
|
+
for (const c of candidates) {
|
|
28
|
+
if (c && typeof c === 'object' && isModelInfo(c)) {
|
|
29
|
+
// The Bedrock provider applies a model prefix at request build time
|
|
30
|
+
// (e.g. arn:aws:...) so the modelId we see here may not match the
|
|
31
|
+
// ModelInfo.id verbatim. Accept by suffix match for safety.
|
|
32
|
+
if (c.id === modelId || modelId.endsWith(c.id)) {
|
|
33
|
+
return c;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
// ============================================================================
|
|
14
40
|
// AWS Bedrock Provider Class
|
|
15
41
|
// ============================================================================
|
|
16
42
|
/**
|
|
@@ -139,21 +165,7 @@ export class AWSBedrockProvider {
|
|
|
139
165
|
if (!modelInput) {
|
|
140
166
|
throw new AWSError('Model is required for AWS Bedrock requests');
|
|
141
167
|
}
|
|
142
|
-
|
|
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
|
-
}
|
|
168
|
+
return self.executeWithConverse(modelInput, request, ctx);
|
|
157
169
|
};
|
|
158
170
|
}
|
|
159
171
|
/**
|
|
@@ -163,136 +175,95 @@ export class AWSBedrockProvider {
|
|
|
163
175
|
const effectiveConfig = { ...this.config, ...config };
|
|
164
176
|
const self = this;
|
|
165
177
|
return async function* (request, ctx, metadata) {
|
|
166
|
-
const
|
|
167
|
-
if (!
|
|
178
|
+
const modelInput = request.model || ctx.metadata?.model || metadata?.model || effectiveConfig.defaultModels?.chat;
|
|
179
|
+
if (!modelInput) {
|
|
168
180
|
throw new AWSError('Model is required for AWS Bedrock requests');
|
|
169
181
|
}
|
|
170
|
-
|
|
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
|
-
}
|
|
182
|
+
yield* self.streamWithConverse(modelInput, request, ctx);
|
|
184
183
|
};
|
|
185
184
|
}
|
|
186
185
|
// ============================================================================
|
|
187
|
-
//
|
|
186
|
+
// Unified Converse API Implementation
|
|
188
187
|
// ============================================================================
|
|
189
188
|
/**
|
|
190
|
-
*
|
|
189
|
+
* Build a ConverseCommandInput from a generic @aeye/core Request.
|
|
191
190
|
*/
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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;
|
|
191
|
+
convertRequestToConverse(modelId, request, ctx) {
|
|
192
|
+
const messages = this.convertMessagesToConverse(request);
|
|
193
|
+
const system = this.convertSystemToConverse(request);
|
|
194
|
+
const modelInfo = pickAwsModelInfo(ctx, modelId);
|
|
195
|
+
// Bedrock's Converse API has no separate structured-output endpoint, so
|
|
196
|
+
// the budget only needs to cover tool schemas. We still build it through
|
|
197
|
+
// the same helper so the strictness selection stays consistent with the
|
|
198
|
+
// OpenAI provider and any future structured-output extension.
|
|
199
|
+
const budget = this.buildSchemaBudget(modelInfo);
|
|
200
|
+
const toolConfig = this.convertToolsToConverse(request, modelInfo, budget);
|
|
201
|
+
const model = getModel(request.model);
|
|
202
|
+
const maxTokens = request.maxTokens ?? (typeof model !== 'string' && model?.maxOutputTokens ? model.maxOutputTokens : undefined);
|
|
230
203
|
return {
|
|
231
|
-
|
|
232
|
-
anthropic_beta: this.config.anthropic?.beta,
|
|
233
|
-
max_tokens: modelMax || 4096,
|
|
204
|
+
modelId,
|
|
234
205
|
messages,
|
|
235
206
|
system,
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
207
|
+
inferenceConfig: {
|
|
208
|
+
maxTokens,
|
|
209
|
+
temperature: request.temperature,
|
|
210
|
+
topP: request.topP,
|
|
211
|
+
stopSequences: request.stop
|
|
212
|
+
? Array.isArray(request.stop) ? request.stop : [request.stop]
|
|
213
|
+
: undefined,
|
|
243
214
|
},
|
|
244
|
-
|
|
215
|
+
toolConfig,
|
|
216
|
+
additionalModelRequestFields: request.extra,
|
|
245
217
|
};
|
|
246
218
|
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
219
|
+
/**
|
|
220
|
+
* Execute a non-streaming chat completion using the Converse API.
|
|
221
|
+
*/
|
|
222
|
+
async executeWithConverse(modelInput, request, ctx) {
|
|
223
|
+
const model = getModel(modelInput);
|
|
224
|
+
const modelId = this.applyModelPrefix(model.id);
|
|
225
|
+
const params = this.convertRequestToConverse(modelId, request, ctx);
|
|
250
226
|
try {
|
|
251
|
-
const command = new
|
|
252
|
-
modelId,
|
|
253
|
-
contentType: 'application/json',
|
|
254
|
-
accept: 'application/json',
|
|
255
|
-
body: JSON.stringify(body),
|
|
256
|
-
});
|
|
257
|
-
// Call pre-request hook with command
|
|
227
|
+
const command = new ConverseCommand(params);
|
|
258
228
|
await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
|
|
259
229
|
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
230
|
let content = '';
|
|
263
|
-
let reasoning
|
|
231
|
+
let reasoning;
|
|
264
232
|
const toolCalls = [];
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
233
|
+
const outputMessage = response.output?.message;
|
|
234
|
+
if (outputMessage?.content) {
|
|
235
|
+
for (const block of outputMessage.content) {
|
|
236
|
+
if ('text' in block && block.text !== undefined) {
|
|
268
237
|
content += block.text;
|
|
269
238
|
}
|
|
270
|
-
else if (block
|
|
239
|
+
else if ('toolUse' in block && block.toolUse) {
|
|
271
240
|
toolCalls.push({
|
|
272
|
-
id: block.
|
|
273
|
-
name: block.name,
|
|
274
|
-
arguments: JSON.stringify(block.input),
|
|
241
|
+
id: block.toolUse.toolUseId,
|
|
242
|
+
name: block.toolUse.name,
|
|
243
|
+
arguments: JSON.stringify(block.toolUse.input ?? {}),
|
|
275
244
|
});
|
|
276
245
|
}
|
|
277
|
-
else if (block
|
|
278
|
-
|
|
246
|
+
else if ('reasoningContent' in block && block.reasoningContent) {
|
|
247
|
+
const rc = block.reasoningContent;
|
|
248
|
+
if ('reasoningText' in rc && rc.reasoningText) {
|
|
249
|
+
reasoning = (reasoning ?? '') + rc.reasoningText.text;
|
|
250
|
+
}
|
|
279
251
|
}
|
|
280
252
|
}
|
|
281
253
|
}
|
|
282
254
|
const result = {
|
|
283
255
|
content,
|
|
284
|
-
reasoning,
|
|
256
|
+
reasoning: reasoning !== undefined ? { content: reasoning } : undefined,
|
|
285
257
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
286
|
-
finishReason: this.
|
|
287
|
-
model,
|
|
258
|
+
finishReason: this.mapStopReason(response.stopReason),
|
|
259
|
+
model: modelInput,
|
|
288
260
|
usage: {
|
|
289
261
|
text: {
|
|
290
|
-
input:
|
|
291
|
-
output:
|
|
262
|
+
input: response.usage?.inputTokens ?? -1,
|
|
263
|
+
output: response.usage?.outputTokens ?? -1,
|
|
292
264
|
},
|
|
293
265
|
},
|
|
294
266
|
};
|
|
295
|
-
// Call post-request hook with command
|
|
296
267
|
await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
|
|
297
268
|
return result;
|
|
298
269
|
}
|
|
@@ -301,127 +272,107 @@ export class AWSBedrockProvider {
|
|
|
301
272
|
throw error;
|
|
302
273
|
}
|
|
303
274
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
275
|
+
/**
|
|
276
|
+
* Execute a streaming chat completion using the Converse Stream API.
|
|
277
|
+
*/
|
|
278
|
+
async *streamWithConverse(modelInput, request, ctx) {
|
|
279
|
+
const model = getModel(modelInput);
|
|
280
|
+
const modelId = this.applyModelPrefix(model.id);
|
|
281
|
+
const params = this.convertRequestToConverse(modelId, request, ctx);
|
|
307
282
|
try {
|
|
308
|
-
const command = new
|
|
309
|
-
modelId,
|
|
310
|
-
contentType: 'application/json',
|
|
311
|
-
accept: 'application/json',
|
|
312
|
-
body: JSON.stringify(body),
|
|
313
|
-
});
|
|
314
|
-
// Call pre-request hook with command
|
|
283
|
+
const command = new ConverseStreamCommand(params);
|
|
315
284
|
await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
|
|
316
285
|
const response = await this.bedrockRuntimeClient.send(command);
|
|
317
|
-
if (!response.
|
|
318
|
-
throw new AWSError('No
|
|
286
|
+
if (!response.stream) {
|
|
287
|
+
throw new AWSError('No stream in streaming response');
|
|
319
288
|
}
|
|
320
289
|
let inputTokens = 0;
|
|
321
290
|
let outputTokens = 0;
|
|
322
291
|
let accumulatedContent = '';
|
|
323
|
-
let
|
|
324
|
-
let finishReason = undefined;
|
|
292
|
+
let finishReason = 'stop';
|
|
325
293
|
const toolCallsMap = new Map();
|
|
326
294
|
try {
|
|
327
|
-
for await (const event of response.
|
|
328
|
-
if (event.
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
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;
|
|
295
|
+
for await (const event of response.stream) {
|
|
296
|
+
if (event.contentBlockDelta?.delta) {
|
|
297
|
+
const delta = event.contentBlockDelta.delta;
|
|
298
|
+
const index = event.contentBlockDelta.contentBlockIndex ?? 0;
|
|
299
|
+
if ('text' in delta && delta.text !== undefined) {
|
|
300
|
+
accumulatedContent += delta.text;
|
|
301
|
+
yield { content: delta.text };
|
|
302
|
+
}
|
|
303
|
+
else if ('toolUse' in delta && delta.toolUse?.input !== undefined) {
|
|
304
|
+
const toolCall = toolCallsMap.get(index);
|
|
305
|
+
if (toolCall) {
|
|
306
|
+
toolCall.arguments += delta.toolUse.input;
|
|
307
|
+
yield {
|
|
308
|
+
toolCallArguments: {
|
|
309
|
+
id: toolCall.id,
|
|
310
|
+
name: toolCall.name,
|
|
311
|
+
arguments: toolCall.arguments,
|
|
312
|
+
},
|
|
313
|
+
};
|
|
364
314
|
}
|
|
365
315
|
}
|
|
366
|
-
else if (
|
|
367
|
-
|
|
368
|
-
|
|
316
|
+
else if ('reasoningContent' in delta && delta.reasoningContent) {
|
|
317
|
+
const rc = delta.reasoningContent;
|
|
318
|
+
if ('text' in rc && rc.text !== undefined) {
|
|
319
|
+
yield { reasoning: { content: rc.text } };
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
else if (event.contentBlockStart?.start) {
|
|
324
|
+
const start = event.contentBlockStart.start;
|
|
325
|
+
const index = event.contentBlockStart.contentBlockIndex ?? 0;
|
|
326
|
+
if ('toolUse' in start && start.toolUse) {
|
|
369
327
|
const toolCall = {
|
|
370
|
-
id:
|
|
371
|
-
name:
|
|
372
|
-
arguments:
|
|
373
|
-
named: true,
|
|
328
|
+
id: start.toolUse.toolUseId,
|
|
329
|
+
name: start.toolUse.name,
|
|
330
|
+
arguments: '',
|
|
374
331
|
finished: false,
|
|
375
332
|
};
|
|
376
333
|
toolCallsMap.set(index, toolCall);
|
|
377
|
-
// Yield toolCallNamed event
|
|
378
334
|
yield {
|
|
379
335
|
toolCallNamed: {
|
|
380
336
|
id: toolCall.id,
|
|
381
337
|
name: toolCall.name,
|
|
382
|
-
arguments:
|
|
338
|
+
arguments: '',
|
|
383
339
|
},
|
|
384
340
|
};
|
|
385
341
|
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
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
|
-
}
|
|
342
|
+
}
|
|
343
|
+
else if (event.contentBlockStop) {
|
|
344
|
+
const index = event.contentBlockStop.contentBlockIndex ?? 0;
|
|
345
|
+
const toolCall = toolCallsMap.get(index);
|
|
346
|
+
if (toolCall && !toolCall.finished) {
|
|
347
|
+
toolCall.finished = true;
|
|
348
|
+
yield {
|
|
349
|
+
toolCall: {
|
|
350
|
+
id: toolCall.id,
|
|
351
|
+
name: toolCall.name,
|
|
352
|
+
arguments: toolCall.arguments,
|
|
353
|
+
},
|
|
354
|
+
};
|
|
419
355
|
}
|
|
420
356
|
}
|
|
357
|
+
else if (event.messageStop) {
|
|
358
|
+
finishReason = this.mapStopReason(event.messageStop.stopReason);
|
|
359
|
+
yield { finishReason };
|
|
360
|
+
}
|
|
361
|
+
else if (event.metadata?.usage) {
|
|
362
|
+
inputTokens = event.metadata.usage.inputTokens ?? 0;
|
|
363
|
+
outputTokens = event.metadata.usage.outputTokens ?? 0;
|
|
364
|
+
yield {
|
|
365
|
+
usage: {
|
|
366
|
+
text: {
|
|
367
|
+
input: inputTokens,
|
|
368
|
+
output: outputTokens,
|
|
369
|
+
},
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
}
|
|
421
373
|
}
|
|
422
374
|
}
|
|
423
375
|
finally {
|
|
424
|
-
// Call post-request hook with accumulated response
|
|
425
376
|
const toolCalls = Array.from(toolCallsMap.values()).map(tc => ({
|
|
426
377
|
id: tc.id,
|
|
427
378
|
name: tc.name,
|
|
@@ -431,7 +382,7 @@ export class AWSBedrockProvider {
|
|
|
431
382
|
content: accumulatedContent,
|
|
432
383
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
433
384
|
finishReason,
|
|
434
|
-
model,
|
|
385
|
+
model: modelInput,
|
|
435
386
|
usage: {
|
|
436
387
|
text: {
|
|
437
388
|
input: inputTokens,
|
|
@@ -447,367 +398,246 @@ export class AWSBedrockProvider {
|
|
|
447
398
|
throw error;
|
|
448
399
|
}
|
|
449
400
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
401
|
+
/**
|
|
402
|
+
* Convert system messages to the Converse API system format.
|
|
403
|
+
*/
|
|
404
|
+
convertSystemToConverse(request) {
|
|
405
|
+
const systemMessages = request.messages.filter(m => m.role === 'system');
|
|
406
|
+
if (systemMessages.length === 0)
|
|
407
|
+
return undefined;
|
|
408
|
+
return systemMessages.map((m) => ({
|
|
409
|
+
text: typeof m.content === 'string'
|
|
410
|
+
? m.content
|
|
411
|
+
: m.content.map(c => String(c.content)).join('\n'),
|
|
412
|
+
}));
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Convert @aeye/core messages to AWS Bedrock Converse API message format.
|
|
416
|
+
* Filters out system messages (handled via convertSystemToConverse).
|
|
417
|
+
* Merges consecutive messages with the same role as required by the API.
|
|
418
|
+
*/
|
|
419
|
+
convertMessagesToConverse(request) {
|
|
420
|
+
const rawMessages = [];
|
|
421
|
+
for (const msg of request.messages) {
|
|
422
|
+
if (msg.role === 'system')
|
|
423
|
+
continue;
|
|
424
|
+
if (msg.role === 'user') {
|
|
425
|
+
const content = [];
|
|
426
|
+
if (typeof msg.content === 'string') {
|
|
427
|
+
if (msg.content.trim()) {
|
|
428
|
+
content.push({ text: msg.content });
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
else {
|
|
432
|
+
for (const part of msg.content) {
|
|
433
|
+
if (part.type === 'text') {
|
|
434
|
+
if (String(part.content).trim()) {
|
|
435
|
+
content.push({ text: String(part.content) });
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
else if (part.type === 'image') {
|
|
439
|
+
const imageBlock = this.convertImageContent(part.content);
|
|
440
|
+
if (imageBlock) {
|
|
441
|
+
content.push(imageBlock);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (content.length > 0) {
|
|
447
|
+
rawMessages.push({ role: 'user', content });
|
|
448
|
+
}
|
|
457
449
|
}
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
// Handle assistant messages with tool calls
|
|
450
|
+
else if (msg.role === 'assistant') {
|
|
451
|
+
const content = [];
|
|
452
|
+
if (msg.content && typeof msg.content === 'string' && msg.content.trim()) {
|
|
453
|
+
content.push({ text: msg.content });
|
|
454
|
+
}
|
|
464
455
|
if (msg.toolCalls && msg.toolCalls.length > 0) {
|
|
465
|
-
const
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
456
|
+
for (const tc of msg.toolCalls) {
|
|
457
|
+
let input = {};
|
|
458
|
+
try {
|
|
459
|
+
input = JSON.parse(tc.arguments);
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
input = { _raw: tc.arguments };
|
|
463
|
+
}
|
|
472
464
|
content.push({
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
return JSON.parse(toolCall.arguments);
|
|
479
|
-
}
|
|
480
|
-
catch (e) {
|
|
481
|
-
return { badArguments: toolCall.arguments };
|
|
482
|
-
}
|
|
483
|
-
})(),
|
|
465
|
+
toolUse: {
|
|
466
|
+
toolUseId: tc.id,
|
|
467
|
+
name: tc.name,
|
|
468
|
+
input: input,
|
|
469
|
+
},
|
|
484
470
|
});
|
|
485
471
|
}
|
|
486
|
-
return {
|
|
487
|
-
role: 'assistant',
|
|
488
|
-
content,
|
|
489
|
-
};
|
|
490
472
|
}
|
|
491
|
-
|
|
492
|
-
role: 'assistant',
|
|
493
|
-
|
|
494
|
-
};
|
|
473
|
+
if (content.length > 0) {
|
|
474
|
+
rawMessages.push({ role: 'assistant', content });
|
|
475
|
+
}
|
|
495
476
|
}
|
|
496
477
|
else if (msg.role === 'tool') {
|
|
497
|
-
|
|
498
|
-
return {
|
|
478
|
+
rawMessages.push({
|
|
499
479
|
role: 'user',
|
|
500
480
|
content: [
|
|
501
481
|
{
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
482
|
+
toolResult: {
|
|
483
|
+
toolUseId: msg.toolCallId,
|
|
484
|
+
content: [
|
|
485
|
+
{
|
|
486
|
+
text: typeof msg.content === 'string'
|
|
487
|
+
? msg.content
|
|
488
|
+
: JSON.stringify(msg.content),
|
|
489
|
+
},
|
|
490
|
+
],
|
|
491
|
+
},
|
|
505
492
|
},
|
|
506
493
|
],
|
|
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
|
-
}
|
|
494
|
+
});
|
|
566
495
|
}
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
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;
|
|
496
|
+
}
|
|
497
|
+
// Merge consecutive messages with the same role (required by Converse API)
|
|
498
|
+
const merged = [];
|
|
499
|
+
for (const msg of rawMessages) {
|
|
500
|
+
const last = merged[merged.length - 1];
|
|
501
|
+
if (last && last.role === msg.role) {
|
|
502
|
+
last.content = [...(last.content ?? []), ...(msg.content ?? [])];
|
|
586
503
|
}
|
|
587
504
|
else {
|
|
588
|
-
|
|
589
|
-
joinedMessages.push(lastMessage);
|
|
590
|
-
}
|
|
591
|
-
lastMessage = msg;
|
|
505
|
+
merged.push({ role: msg.role, content: [...(msg.content ?? [])] });
|
|
592
506
|
}
|
|
593
507
|
}
|
|
594
|
-
|
|
595
|
-
|
|
508
|
+
// Ensure there is at least one user message
|
|
509
|
+
if (merged.length === 0) {
|
|
510
|
+
merged.push({ role: 'user', content: [{ text: 'Perform the requested operation.' }] });
|
|
596
511
|
}
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
512
|
+
return merged;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Convert an image content value to a Converse API ContentBlock.
|
|
516
|
+
* Only base64 data URIs are natively supported; URL images are not supported
|
|
517
|
+
* by the Converse API without fetching the bytes first.
|
|
518
|
+
*/
|
|
519
|
+
convertImageContent(content) {
|
|
520
|
+
const src = content instanceof URL ? content.href : typeof content === 'string' ? content : null;
|
|
521
|
+
if (!src)
|
|
522
|
+
return null;
|
|
523
|
+
// data URI: data:<mediaType>;base64,<data>
|
|
524
|
+
const match = src.match(/^data:([^;]+);base64,(.+)$/);
|
|
525
|
+
if (match) {
|
|
526
|
+
const mediaType = match[1].toLowerCase();
|
|
527
|
+
const format = (mediaType.includes('png') ? 'png' :
|
|
528
|
+
mediaType.includes('jpeg') || mediaType.includes('jpg') ? 'jpeg' :
|
|
529
|
+
mediaType.includes('gif') ? 'gif' :
|
|
530
|
+
mediaType.includes('webp') ? 'webp' : null);
|
|
531
|
+
if (format) {
|
|
532
|
+
const bytes = Buffer.from(match[2], 'base64');
|
|
533
|
+
return { image: { format, source: { bytes } } };
|
|
602
534
|
}
|
|
603
535
|
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
536
|
+
// URL images are not natively supported by the Converse API
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Convert @aeye/core tool definitions to AWS Bedrock Converse API tool format.
|
|
541
|
+
*
|
|
542
|
+
* Strict-tool support is best-effort and per-model: the descriptor is
|
|
543
|
+
* picked via `resolveStrictFormat(model)`, which falls back through
|
|
544
|
+
* `model.strictFormat` → `model.provider` → `id` prefix. Bedrock
|
|
545
|
+
* surfaces both Anthropic-family Claude models and (in some regions)
|
|
546
|
+
* OpenAI-shaped tools. Models without a declared family fall back to
|
|
547
|
+
* LENIENT — silent degradation. The chosen descriptor is pinned on each
|
|
548
|
+
* `ToolDefinition.descriptor` so the Prompt loop can apply the matching
|
|
549
|
+
* strictify when validating tool arguments.
|
|
550
|
+
*
|
|
551
|
+
* Anthropic enforces per-request limits (20 strict tools, 24 optional
|
|
552
|
+
* params, 16 union types across the whole request) — those are tracked
|
|
553
|
+
* by the shared `SchemaBudget` so over-budget tools degrade to LENIENT
|
|
554
|
+
* silently rather than failing the API call.
|
|
555
|
+
*/
|
|
556
|
+
convertToolsToConverse(request, model, budget) {
|
|
557
|
+
if (!request.tools || request.tools.length === 0)
|
|
558
|
+
return undefined;
|
|
559
|
+
const localBudget = budget ?? this.buildSchemaBudget(model);
|
|
560
|
+
// Allocate descriptors in descending-priority order so the most-wanted
|
|
561
|
+
// strict tools consume budget first, then emit in original order.
|
|
562
|
+
const order = request.tools
|
|
563
|
+
.map((t, i) => ({ i, p: strictPriority(t.strict) }))
|
|
564
|
+
.sort((a, b) => b.p - a.p);
|
|
565
|
+
const descriptors = new Array(request.tools.length);
|
|
566
|
+
for (const { i } of order) {
|
|
567
|
+
const tool = request.tools[i];
|
|
568
|
+
descriptors[i] = localBudget.allocateTool(tool.parameters, tool.strict);
|
|
569
|
+
tool.descriptor = descriptors[i].id;
|
|
570
|
+
}
|
|
571
|
+
const tools = request.tools.map((tool, i) => {
|
|
572
|
+
const descriptor = descriptors[i];
|
|
573
|
+
const strictifiedSchema = strictify(tool.parameters, descriptor);
|
|
574
|
+
return {
|
|
575
|
+
toolSpec: {
|
|
576
|
+
name: tool.name,
|
|
577
|
+
description: tool.description,
|
|
578
|
+
inputSchema: {
|
|
579
|
+
json: toJSONSchema(strictifiedSchema, descriptor),
|
|
580
|
+
},
|
|
581
|
+
},
|
|
582
|
+
};
|
|
583
|
+
});
|
|
584
|
+
let toolChoice;
|
|
585
|
+
if (request.toolChoice === 'auto') {
|
|
586
|
+
toolChoice = { auto: {} };
|
|
587
|
+
}
|
|
588
|
+
else if (request.toolChoice === 'required') {
|
|
589
|
+
toolChoice = { any: {} };
|
|
590
|
+
}
|
|
591
|
+
else if (typeof request.toolChoice === 'object' && request.toolChoice !== null) {
|
|
592
|
+
toolChoice = { tool: { name: request.toolChoice.tool } };
|
|
614
593
|
}
|
|
615
|
-
return
|
|
594
|
+
return { tools, toolChoice };
|
|
616
595
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
596
|
+
/**
|
|
597
|
+
* The set of strict descriptor families this provider can speak through
|
|
598
|
+
* Bedrock. Defaults to `['openai', 'anthropic', 'google']` — Bedrock
|
|
599
|
+
* surfaces all three. Subclasses can extend to accept custom registered
|
|
600
|
+
* families.
|
|
601
|
+
*/
|
|
602
|
+
supportedStrictFamilies = new Set(['openai', 'anthropic', 'google']);
|
|
603
|
+
/**
|
|
604
|
+
* Build a SchemaBudget tuned to the resolved strict-format family.
|
|
605
|
+
* Bedrock surfaces multiple model families; the descriptor pick handles
|
|
606
|
+
* any in `supportedStrictFamilies`. Mismatched families fall back to
|
|
607
|
+
* LENIENT silently.
|
|
608
|
+
*/
|
|
609
|
+
buildSchemaBudget(model) {
|
|
610
|
+
const family = model ? resolveStrictFormat(model) : undefined;
|
|
611
|
+
const familySupported = family !== undefined && this.supportedStrictFamilies.has(family);
|
|
612
|
+
const tools = familySupported && model.capabilities.has('toolsStrict')
|
|
613
|
+
? getDescriptor(family, true)
|
|
614
|
+
: LENIENT;
|
|
615
|
+
const out = familySupported && model.capabilities.has('structured')
|
|
616
|
+
? getDescriptor(family, true)
|
|
617
|
+
: LENIENT;
|
|
618
|
+
return new SchemaBudget(strictestOf(tools, out));
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Map a Bedrock Converse API stop reason to the @aeye/core FinishReason type.
|
|
622
|
+
*/
|
|
623
|
+
mapStopReason(stopReason) {
|
|
624
|
+
switch (stopReason) {
|
|
621
625
|
case 'end_turn':
|
|
622
626
|
return 'stop';
|
|
623
627
|
case 'max_tokens':
|
|
628
|
+
case 'model_context_window_exceeded':
|
|
624
629
|
return 'length';
|
|
625
630
|
case 'stop_sequence':
|
|
626
631
|
return 'stop';
|
|
627
632
|
case 'tool_use':
|
|
628
633
|
return 'tool_calls';
|
|
634
|
+
case 'content_filtered':
|
|
635
|
+
return 'content_filter';
|
|
629
636
|
default:
|
|
630
637
|
return 'stop';
|
|
631
638
|
}
|
|
632
639
|
}
|
|
633
640
|
// ============================================================================
|
|
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
641
|
// Image Generation (Stability AI)
|
|
812
642
|
// ============================================================================
|
|
813
643
|
generateImage = async (request, ctx, config) => {
|