@aeye/aws 0.3.9 → 0.7.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/dist/aws.js CHANGED
@@ -5,11 +5,12 @@
5
5
  * Uses AWS SDK v3 to automatically pick up credentials from environment, IAM roles, or credential files.
6
6
  * All chat LLM calls use the Bedrock Converse API for a unified request/response format across models.
7
7
  */
8
- import { isModelInfo, resolveStrictFormat } from '@aeye/ai';
9
- import { getDescriptor, getModel, LENIENT, SchemaBudget, strictestOf, strictify, strictPriority, toJSONSchema, } from '@aeye/core';
8
+ import { allocateToolDescriptors, buildSchemaBudget, isModelInfo } from '@aeye/ai';
9
+ import { deliverSchema, describeTool, getModel, getResponseFromChunks, LENIENT, forcesTool, schemaRejection, strictify, toJSONSchema, withAllowedTools, } from '@aeye/core';
10
10
  import { BedrockClient, ListFoundationModelsCommand } from '@aws-sdk/client-bedrock';
11
11
  import { BedrockRuntimeClient, ConverseCommand, ConverseStreamCommand, InvokeModelCommand, } from '@aws-sdk/client-bedrock-runtime';
12
12
  import { convertAWSModel } from './common';
13
+ import { ALWAYS_THINKING_CLAUDE, BEDROCK_PROVIDER, contentBlockChunk, endChunk, streamChunk, toAssistantBlocks, toBedrockServiceTier, toContentBlocks, toDocument, toReasoningRequest, toSystemBlocks, toToolResultBlocks, withoutCachePoints, } from './converse';
13
14
  import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLimitError } from './types';
14
15
  // ============================================================================
15
16
  // AWS Bedrock Provider Configuration
@@ -18,23 +19,44 @@ import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLi
18
19
  * Resolve the full ModelInfo for the request when available.
19
20
  *
20
21
  * 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).
22
+ * selection; on the standard execution path we read strict-format and
23
+ * reasoning declarations from there. Returns undefined when no ModelInfo is
24
+ * available (the convert call then falls back to LENIENT — silent best-effort).
24
25
  */
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
- }
26
+ function pickAwsModelInfo(model, ctx) {
27
+ if (isModelInfo(model)) {
28
+ return model;
36
29
  }
37
- return undefined;
30
+ const selected = ctx?.metadata?.model;
31
+ // An inference profile id (e.g. us.anthropic...) ends with the model id
32
+ return selected && isModelInfo(selected) && (selected.id === model.id || model.id.endsWith(`.${selected.id}`))
33
+ ? selected
34
+ : undefined;
35
+ }
36
+ /**
37
+ * Bedrock errors that mean the credentials aren't accepted.
38
+ */
39
+ const AUTH_ERRORS = new Set(['UnrecognizedClientException', 'InvalidSignatureException', 'AccessDeniedException', 'ExpiredTokenException']);
40
+ /**
41
+ * Bedrock errors that clear up when retried later.
42
+ */
43
+ const RATE_LIMIT_ERRORS = new Set(['ThrottlingException', 'TooManyRequestsException', 'ServiceUnavailableException']);
44
+ /**
45
+ * Messages Bedrock models reject an over-long prompt with, such as "Input is
46
+ * too long for requested model", "prompt is too long: 210000 tokens > 200000
47
+ * maximum" or Nova's "Input Tokens Exceeded".
48
+ */
49
+ const CONTEXT_WINDOW_ERROR = /context (length|window)|token limit|too long|too many (input )?tokens|input tokens exceed/i;
50
+ /**
51
+ * How Bedrock rejects a model id it serves in the region only through an
52
+ * inference profile.
53
+ */
54
+ const PROFILE_REQUIRED = /on-demand throughput isn.t supported/i;
55
+ /**
56
+ * The inference profile geography for a region, as profile ids prefix it.
57
+ */
58
+ function regionGeography(region) {
59
+ return region.startsWith('us-gov') ? 'us-gov' : region.startsWith('ap-') ? 'apac' : region.split('-')[0];
38
60
  }
39
61
  // ============================================================================
40
62
  // AWS Bedrock Provider Class
@@ -71,11 +93,13 @@ function pickAwsModelInfo(ctx, modelId) {
71
93
  * ```
72
94
  */
73
95
  export class AWSBedrockProvider {
74
- name = 'aws-bedrock';
96
+ name = BEDROCK_PROVIDER;
75
97
  config;
76
98
  defaultMetadata;
77
99
  bedrockClient;
78
100
  bedrockRuntimeClient;
101
+ // Models found to need an inference profile in this region
102
+ profileOnly = new Set();
79
103
  constructor(config) {
80
104
  this.config = config;
81
105
  const clientConfig = AWSBedrockProvider.convertConfig(config);
@@ -92,6 +116,14 @@ export class AWSBedrockProvider {
92
116
  const clientConfig = {
93
117
  region: config.region || process.env.AWS_REGION || 'us-east-1',
94
118
  };
119
+ if (config.requestHandler) {
120
+ clientConfig.requestHandler = config.requestHandler;
121
+ }
122
+ if (config.apiKey) {
123
+ clientConfig.token = { token: config.apiKey };
124
+ clientConfig.authSchemePreference = ['httpBearerAuth'];
125
+ return clientConfig;
126
+ }
95
127
  if (config.credentials && config.credentials.accessKeyId && config.credentials.secretAccessKey) {
96
128
  clientConfig.credentials = {
97
129
  accessKeyId: config.credentials.accessKeyId,
@@ -165,7 +197,8 @@ export class AWSBedrockProvider {
165
197
  if (!modelInput) {
166
198
  throw new AWSError('Model is required for AWS Bedrock requests');
167
199
  }
168
- return self.executeWithConverse(modelInput, request, ctx);
200
+ // Converse has no structured output or JSON mode, so a schema goes in the prompt
201
+ return self.executeWithConverse(modelInput, deliverSchema(request), ctx);
169
202
  };
170
203
  }
171
204
  /**
@@ -179,31 +212,83 @@ export class AWSBedrockProvider {
179
212
  if (!modelInput) {
180
213
  throw new AWSError('Model is required for AWS Bedrock requests');
181
214
  }
182
- yield* self.streamWithConverse(modelInput, request, ctx);
215
+ yield* self.streamWithConverse(modelInput, deliverSchema(request), ctx);
183
216
  };
184
217
  }
185
218
  // ============================================================================
186
219
  // Unified Converse API Implementation
187
220
  // ============================================================================
188
221
  /**
189
- * Build a ConverseCommandInput from a generic @aeye/core Request.
222
+ * The id to call a chat model by. A configured `modelPrefix` picks a
223
+ * cross-region inference profile; otherwise a model Bedrock serves only
224
+ * through inference profiles (per the registry, or as Bedrock answered an
225
+ * earlier call in this region) uses the profile for the client region's
226
+ * geography, or the global one when only that is listed.
227
+ */
228
+ async resolveModelId(id, info) {
229
+ const prefix = this.config.modelPrefix;
230
+ if (prefix) {
231
+ return id.startsWith(prefix) ? id : `${prefix}${id}`;
232
+ }
233
+ if (info?.metadata?.inRegion !== false && !this.profileOnly.has(id)) {
234
+ return id;
235
+ }
236
+ const listed = info?.metadata?.inferenceIds;
237
+ const profiles = Array.isArray(listed) ? listed.filter((p) => typeof p === 'string') : [];
238
+ const geography = regionGeography(await this.bedrockRuntimeClient.config.region());
239
+ const candidates = [geography, 'global'].map(g => `${g}.${id}`);
240
+ return profiles.length ? candidates.find(profile => profiles.includes(profile)) ?? id : candidates[0];
241
+ }
242
+ /**
243
+ * Make a chat call, and when Bedrock answers that the model needs an
244
+ * inference profile in this region (the registry's `inRegion` holds for
245
+ * the region it was gathered in), make it again by profile.
246
+ */
247
+ async byProfileWhenRequired(id, call) {
248
+ try {
249
+ return await call();
250
+ }
251
+ catch (error) {
252
+ if (this.config.modelPrefix || this.profileOnly.has(id) || !(error instanceof Error && PROFILE_REQUIRED.test(error.message))) {
253
+ throw error;
254
+ }
255
+ this.profileOnly.add(id);
256
+ return call();
257
+ }
258
+ }
259
+ /**
260
+ * Build the Converse input from a generic @aeye/core Request, without the
261
+ * guardrail, whose shape differs between Converse and ConverseStream.
190
262
  */
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);
263
+ async convertRequestToConverse(model, request, ctx) {
264
+ const info = pickAwsModelInfo(model, ctx);
265
+ const modelId = await this.resolveModelId(model.id, info);
266
+ // Built the same way as the OpenAI provider's so strictness selection
267
+ // stays consistent across tools and structured output.
268
+ const budget = buildSchemaBudget(info ?? { id: model.id, provider: this.name }, this.supportedStrictFamilies);
269
+ // Bedrock can't limit which tools a model calls, so only the allowed ones are sent
270
+ const allowed = withAllowedTools(request);
271
+ // Claude that always thinks can't be forced to call a tool, so it's
272
+ // offered only the forced tools instead
273
+ const choice = allowed.toolChoice;
274
+ const offered = ALWAYS_THINKING_CLAUDE.test(modelId) && forcesTool(choice)
275
+ ? withAllowedTools({ ...allowed, toolChoice: { allowed: typeof choice === 'object' && 'tool' in choice ? [choice.tool] : (allowed.tools ?? []).map(tool => tool.name) } })
276
+ : allowed;
277
+ const toolConfig = this.convertToolsToConverse(offered, budget);
278
+ const textFormat = this.convertResponseFormat(request, budget);
279
+ // A schema Converse can't take natively goes in the prompt
280
+ const sent = typeof request.responseFormat === 'object' && !textFormat ? deliverSchema(request, LENIENT, 'prompt') : request;
281
+ const maxTokens = request.maxTokens ?? (info ?? model).maxOutputTokens;
282
+ const reasoning = toReasoningRequest(modelId, request.reason, info?.reasoningEfforts, maxTokens, forcesTool(offered.toolChoice));
283
+ const fields = reasoning.fields || request.extra ? { ...reasoning.fields, ...request.extra } : undefined;
284
+ const messages = await this.convertMessagesToConverse(sent);
285
+ const system = await toSystemBlocks(sent.messages);
286
+ // Models the registry prices no cache reads for reject cache points
287
+ const caches = !info || info.pricing.text?.cached !== undefined;
203
288
  return {
204
289
  modelId,
205
- messages,
206
- system,
290
+ messages: caches ? messages : messages.map(message => ({ ...message, content: withoutCachePoints(message.content) })),
291
+ system: caches ? system : withoutCachePoints(system),
207
292
  inferenceConfig: {
208
293
  maxTokens,
209
294
  temperature: request.temperature,
@@ -211,9 +296,14 @@ export class AWSBedrockProvider {
211
296
  stopSequences: request.stop
212
297
  ? Array.isArray(request.stop) ? request.stop : [request.stop]
213
298
  : undefined,
299
+ ...reasoning.cleared,
214
300
  },
215
301
  toolConfig,
216
- additionalModelRequestFields: request.extra,
302
+ outputConfig: textFormat || reasoning.effort ? { textFormat, effort: reasoning.effort } : undefined,
303
+ serviceTier: toBedrockServiceTier(request.serviceTier),
304
+ performanceConfig: this.config.latency && { latency: this.config.latency },
305
+ requestMetadata: request.metadata,
306
+ additionalModelRequestFields: fields,
217
307
  };
218
308
  }
219
309
  /**
@@ -221,54 +311,25 @@ export class AWSBedrockProvider {
221
311
  */
222
312
  async executeWithConverse(modelInput, request, ctx) {
223
313
  const model = getModel(modelInput);
224
- const modelId = this.applyModelPrefix(model.id);
225
- const params = this.convertRequestToConverse(modelId, request, ctx);
314
+ const guardrail = this.config.guardrail;
226
315
  try {
227
- const command = new ConverseCommand(params);
228
- await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
229
- const response = await this.bedrockRuntimeClient.send(command);
230
- let content = '';
231
- let reasoning;
232
- const toolCalls = [];
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) {
237
- content += block.text;
238
- }
239
- else if ('toolUse' in block && block.toolUse) {
240
- toolCalls.push({
241
- id: block.toolUse.toolUseId,
242
- name: block.toolUse.name,
243
- arguments: JSON.stringify(block.toolUse.input ?? {}),
244
- });
245
- }
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
- }
251
- }
252
- }
253
- }
254
- const result = {
255
- content,
256
- reasoning: reasoning !== undefined ? { content: reasoning } : undefined,
257
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
258
- finishReason: this.mapStopReason(response.stopReason),
259
- model: modelInput,
260
- usage: {
261
- text: {
262
- input: response.usage?.inputTokens ?? -1,
263
- output: response.usage?.outputTokens ?? -1,
264
- },
265
- },
266
- };
316
+ const { command, response } = await this.byProfileWhenRequired(model.id, async () => {
317
+ const command = new ConverseCommand({
318
+ ...await this.convertRequestToConverse(model, request, ctx),
319
+ guardrailConfig: guardrail && { guardrailIdentifier: guardrail.guardrailIdentifier, guardrailVersion: guardrail.guardrailVersion, trace: guardrail.trace },
320
+ });
321
+ await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
322
+ return { command, response: await this.bedrockRuntimeClient.send(command) };
323
+ });
324
+ const result = getResponseFromChunks([
325
+ ...(response.output?.message?.content ?? []).map(contentBlockChunk),
326
+ endChunk(response.stopReason, response.usage, response.serviceTier),
327
+ ], modelInput);
267
328
  await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
268
329
  return result;
269
330
  }
270
331
  catch (error) {
271
- this.handleAWSError(error);
332
+ this.handleAWSError(error, request);
272
333
  throw error;
273
334
  }
274
335
  }
@@ -277,232 +338,68 @@ export class AWSBedrockProvider {
277
338
  */
278
339
  async *streamWithConverse(modelInput, request, ctx) {
279
340
  const model = getModel(modelInput);
280
- const modelId = this.applyModelPrefix(model.id);
281
- const params = this.convertRequestToConverse(modelId, request, ctx);
282
341
  try {
283
- const command = new ConverseStreamCommand(params);
284
- await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
285
- const response = await this.bedrockRuntimeClient.send(command);
342
+ const { command, response } = await this.byProfileWhenRequired(model.id, async () => {
343
+ const command = new ConverseStreamCommand({ ...await this.convertRequestToConverse(model, request, ctx), guardrailConfig: this.config.guardrail });
344
+ await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
345
+ return { command, response: await this.bedrockRuntimeClient.send(command) };
346
+ });
286
347
  if (!response.stream) {
287
348
  throw new AWSError('No stream in streaming response');
288
349
  }
289
- let inputTokens = 0;
290
- let outputTokens = 0;
291
- let accumulatedContent = '';
292
- let finishReason = 'stop';
293
- const toolCallsMap = new Map();
350
+ // Tool calls in progress, by content block index
351
+ const calls = new Map();
352
+ const chunks = [];
294
353
  try {
295
354
  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
- };
314
- }
315
- }
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) {
327
- const toolCall = {
328
- id: start.toolUse.toolUseId,
329
- name: start.toolUse.name,
330
- arguments: '',
331
- finished: false,
332
- };
333
- toolCallsMap.set(index, toolCall);
334
- yield {
335
- toolCallNamed: {
336
- id: toolCall.id,
337
- name: toolCall.name,
338
- arguments: '',
339
- },
340
- };
341
- }
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
- };
355
- }
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
- };
355
+ const chunk = streamChunk(event, calls);
356
+ if (chunk) {
357
+ chunks.push(chunk);
358
+ yield chunk;
372
359
  }
373
360
  }
374
361
  }
375
362
  finally {
376
- const toolCalls = Array.from(toolCallsMap.values()).map(tc => ({
377
- id: tc.id,
378
- name: tc.name,
379
- arguments: tc.arguments,
380
- }));
381
- const accumulatedResponse = {
382
- content: accumulatedContent,
383
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
384
- finishReason,
385
- model: modelInput,
386
- usage: {
387
- text: {
388
- input: inputTokens,
389
- output: outputTokens,
390
- },
391
- },
392
- };
393
- await this.config.hooks?.chat?.afterRequest?.(request, command, accumulatedResponse, ctx);
363
+ await this.config.hooks?.chat?.afterRequest?.(request, command, getResponseFromChunks(chunks, modelInput), ctx);
394
364
  }
395
365
  }
396
366
  catch (error) {
397
- this.handleAWSError(error);
367
+ this.handleAWSError(error, request);
398
368
  throw error;
399
369
  }
400
370
  }
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
371
  /**
415
372
  * Convert @aeye/core messages to AWS Bedrock Converse API message format.
416
- * Filters out system messages (handled via convertSystemToConverse).
373
+ * Filters out system messages (handled via toSystemBlocks).
417
374
  * Merges consecutive messages with the same role as required by the API.
418
375
  */
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
- }
376
+ async convertMessagesToConverse(request) {
377
+ // An assistant turn split across messages replays its reasoning once
378
+ const replayed = new Set();
379
+ const rawMessages = await Promise.all(request.messages.map(async (msg) => {
380
+ switch (msg.role) {
381
+ case 'system':
382
+ return undefined;
383
+ case 'user':
384
+ return { role: 'user', content: await toContentBlocks(msg.content) };
385
+ case 'assistant':
386
+ return { role: 'assistant', content: await toAssistantBlocks(msg, replayed) };
387
+ case 'tool':
388
+ return { role: 'user', content: await toToolResultBlocks(msg) };
449
389
  }
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
- }
455
- if (msg.toolCalls && msg.toolCalls.length > 0) {
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
- }
464
- content.push({
465
- toolUse: {
466
- toolUseId: tc.id,
467
- name: tc.name,
468
- input: input,
469
- },
470
- });
471
- }
472
- }
473
- if (content.length > 0) {
474
- rawMessages.push({ role: 'assistant', content });
475
- }
476
- }
477
- else if (msg.role === 'tool') {
478
- rawMessages.push({
479
- role: 'user',
480
- content: [
481
- {
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
- },
492
- },
493
- ],
494
- });
495
- }
496
- }
390
+ }));
497
391
  // Merge consecutive messages with the same role (required by Converse API)
498
392
  const merged = [];
499
393
  for (const msg of rawMessages) {
394
+ if (!msg?.content?.length) {
395
+ continue;
396
+ }
500
397
  const last = merged[merged.length - 1];
501
398
  if (last && last.role === msg.role) {
502
- last.content = [...(last.content ?? []), ...(msg.content ?? [])];
399
+ last.content = [...(last.content ?? []), ...msg.content];
503
400
  }
504
401
  else {
505
- merged.push({ role: msg.role, content: [...(msg.content ?? [])] });
402
+ merged.push(msg);
506
403
  }
507
404
  }
508
405
  // Ensure there is at least one user message
@@ -511,40 +408,17 @@ export class AWSBedrockProvider {
511
408
  }
512
409
  return merged;
513
410
  }
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 } } };
534
- }
535
- }
536
- // URL images are not natively supported by the Converse API
537
- return null;
538
- }
539
411
  /**
540
412
  * Convert @aeye/core tool definitions to AWS Bedrock Converse API tool format.
541
413
  *
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
414
+ * Strict-tool support is best-effort and per-model: the budget's
415
+ * descriptor comes from `buildSchemaBudget` (see `@aeye/ai`). Bedrock
545
416
  * 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
417
+ * OpenAI-shaped tools. Models without strict support use their family's
418
+ * non-strict descriptor, and models without a family Bedrock speaks fall
419
+ * back to LENIENT — silent degradation. Tools with a strict descriptor are
420
+ * sent with Converse's `strict` flag, which constrains the model's calls to
421
+ * the schema. The chosen descriptor is pinned on each
548
422
  * `ToolDefinition.descriptor` so the Prompt loop can apply the matching
549
423
  * strictify when validating tool arguments.
550
424
  *
@@ -552,47 +426,61 @@ export class AWSBedrockProvider {
552
426
  * params, 16 union types across the whole request) — those are tracked
553
427
  * by the shared `SchemaBudget` so over-budget tools degrade to LENIENT
554
428
  * silently rather than failing the API call.
429
+ *
430
+ * Converse has no free-text tools, so those go as their one-field function
431
+ * with any grammar in the description. It has no `none` choice either, so
432
+ * tools are left out then, unless the conversation already used them
433
+ * (Converse rejects tool blocks without a tool config).
555
434
  */
556
- convertToolsToConverse(request, model, budget) {
435
+ convertToolsToConverse(request, budget) {
557
436
  if (!request.tools || request.tools.length === 0)
558
437
  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
- }
438
+ const choice = request.toolChoice;
439
+ if (choice === 'none' && !request.messages.some(m => m.role === 'tool' || m.toolCalls?.length))
440
+ return undefined;
441
+ const descriptors = allocateToolDescriptors(request.tools, budget);
571
442
  const tools = request.tools.map((tool, i) => {
572
443
  const descriptor = descriptors[i];
573
444
  const strictifiedSchema = strictify(tool.parameters, descriptor);
574
445
  return {
575
446
  toolSpec: {
576
447
  name: tool.name,
577
- description: tool.description,
448
+ description: describeTool(tool),
578
449
  inputSchema: {
579
- json: toJSONSchema(strictifiedSchema, descriptor),
450
+ json: toDocument(JSON.stringify(toJSONSchema(strictifiedSchema, descriptor))),
580
451
  },
452
+ strict: descriptor.strict || undefined,
581
453
  },
582
454
  };
583
455
  });
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 } };
593
- }
456
+ const toolChoice = choice === 'auto' ? { auto: {} }
457
+ : choice === 'required' ? { any: {} }
458
+ : typeof choice === 'object' && 'tool' in choice ? { tool: { name: choice.tool } }
459
+ : undefined;
594
460
  return { tools, toolChoice };
595
461
  }
462
+ /**
463
+ * Convert a schema response format to Converse structured output. Converse
464
+ * rejects schemas outside its strict subset, so a schema goes only when the
465
+ * model's strict descriptor can shape it; the descriptor is pinned on the
466
+ * format so the Prompt validator can apply the matching strictify. Plain
467
+ * JSON has no Converse mode.
468
+ */
469
+ convertResponseFormat(request, budget) {
470
+ const format = request.responseFormat;
471
+ if (typeof format !== 'object')
472
+ return undefined;
473
+ const descriptor = budget.allocateOutput(format.type, format.strict ?? 1);
474
+ if (!descriptor.strict)
475
+ return undefined;
476
+ format.descriptor = descriptor.id;
477
+ return {
478
+ type: 'json_schema',
479
+ structure: {
480
+ jsonSchema: { name: 'response', schema: JSON.stringify(toJSONSchema(strictify(format.type, descriptor), descriptor)) },
481
+ },
482
+ };
483
+ }
596
484
  /**
597
485
  * The set of strict descriptor families this provider can speak through
598
486
  * Bedrock. Defaults to `['openai', 'anthropic', 'google']` — Bedrock
@@ -600,43 +488,6 @@ export class AWSBedrockProvider {
600
488
  * families.
601
489
  */
602
490
  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) {
625
- case 'end_turn':
626
- return 'stop';
627
- case 'max_tokens':
628
- case 'model_context_window_exceeded':
629
- return 'length';
630
- case 'stop_sequence':
631
- return 'stop';
632
- case 'tool_use':
633
- return 'tool_calls';
634
- case 'content_filtered':
635
- return 'content_filter';
636
- default:
637
- return 'stop';
638
- }
639
- }
640
491
  // ============================================================================
641
492
  // Image Generation (Stability AI)
642
493
  // ============================================================================
@@ -745,15 +596,15 @@ export class AWSBedrockProvider {
745
596
  // ============================================================================
746
597
  // Error Handling
747
598
  // ============================================================================
748
- handleAWSError(error) {
599
+ handleAWSError(error, request) {
749
600
  const errorName = error.name || '';
750
601
  const errorMessage = error.message || '';
751
602
  // Authentication errors
752
- if (errorName === 'UnrecognizedClientException' || errorName === 'InvalidSignatureException') {
603
+ if (AUTH_ERRORS.has(errorName)) {
753
604
  throw new AWSAuthError(error);
754
605
  }
755
- // Rate limiting
756
- if (errorName === 'ThrottlingException' || errorName === 'TooManyRequestsException') {
606
+ // Rate limiting, and capacity that's busy for now
607
+ if (RATE_LIMIT_ERRORS.has(errorName)) {
757
608
  throw new AWSRateLimitError('Rate limit exceeded', undefined, error);
758
609
  }
759
610
  // Quota errors
@@ -761,9 +612,14 @@ export class AWSBedrockProvider {
761
612
  throw new AWSQuotaError(error);
762
613
  }
763
614
  // Context window errors
764
- if (errorMessage.includes('context length') || errorMessage.includes('token limit')) {
615
+ if (CONTEXT_WINDOW_ERROR.test(errorMessage)) {
765
616
  throw new AWSContextWindowError('Context window exceeded', undefined, error);
766
617
  }
618
+ // A rejected tool schema
619
+ const rejected = errorName === 'ValidationException' && request ? schemaRejection(request, error) : undefined;
620
+ if (rejected) {
621
+ throw rejected;
622
+ }
767
623
  // Re-throw as generic AWS error
768
624
  throw new AWSError(errorMessage || 'Unknown AWS Bedrock error', error);
769
625
  }