@aeye/aws 0.3.9 → 0.4.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);
@@ -165,7 +189,8 @@ export class AWSBedrockProvider {
165
189
  if (!modelInput) {
166
190
  throw new AWSError('Model is required for AWS Bedrock requests');
167
191
  }
168
- return self.executeWithConverse(modelInput, request, ctx);
192
+ // Converse has no structured output or JSON mode, so a schema goes in the prompt
193
+ return self.executeWithConverse(modelInput, deliverSchema(request), ctx);
169
194
  };
170
195
  }
171
196
  /**
@@ -179,31 +204,83 @@ export class AWSBedrockProvider {
179
204
  if (!modelInput) {
180
205
  throw new AWSError('Model is required for AWS Bedrock requests');
181
206
  }
182
- yield* self.streamWithConverse(modelInput, request, ctx);
207
+ yield* self.streamWithConverse(modelInput, deliverSchema(request), ctx);
183
208
  };
184
209
  }
185
210
  // ============================================================================
186
211
  // Unified Converse API Implementation
187
212
  // ============================================================================
188
213
  /**
189
- * Build a ConverseCommandInput from a generic @aeye/core Request.
214
+ * The id to call a chat model by. A configured `modelPrefix` picks a
215
+ * cross-region inference profile; otherwise a model Bedrock serves only
216
+ * through inference profiles (per the registry, or as Bedrock answered an
217
+ * earlier call in this region) uses the profile for the client region's
218
+ * geography, or the global one when only that is listed.
190
219
  */
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);
220
+ async resolveModelId(id, info) {
221
+ const prefix = this.config.modelPrefix;
222
+ if (prefix) {
223
+ return id.startsWith(prefix) ? id : `${prefix}${id}`;
224
+ }
225
+ if (info?.metadata?.inRegion !== false && !this.profileOnly.has(id)) {
226
+ return id;
227
+ }
228
+ const listed = info?.metadata?.inferenceIds;
229
+ const profiles = Array.isArray(listed) ? listed.filter((p) => typeof p === 'string') : [];
230
+ const geography = regionGeography(await this.bedrockRuntimeClient.config.region());
231
+ const candidates = [geography, 'global'].map(g => `${g}.${id}`);
232
+ return profiles.length ? candidates.find(profile => profiles.includes(profile)) ?? id : candidates[0];
233
+ }
234
+ /**
235
+ * Make a chat call, and when Bedrock answers that the model needs an
236
+ * inference profile in this region (the registry's `inRegion` holds for
237
+ * the region it was gathered in), make it again by profile.
238
+ */
239
+ async byProfileWhenRequired(id, call) {
240
+ try {
241
+ return await call();
242
+ }
243
+ catch (error) {
244
+ if (this.config.modelPrefix || this.profileOnly.has(id) || !(error instanceof Error && PROFILE_REQUIRED.test(error.message))) {
245
+ throw error;
246
+ }
247
+ this.profileOnly.add(id);
248
+ return call();
249
+ }
250
+ }
251
+ /**
252
+ * Build the Converse input from a generic @aeye/core Request, without the
253
+ * guardrail, whose shape differs between Converse and ConverseStream.
254
+ */
255
+ async convertRequestToConverse(model, request, ctx) {
256
+ const info = pickAwsModelInfo(model, ctx);
257
+ const modelId = await this.resolveModelId(model.id, info);
258
+ // Built the same way as the OpenAI provider's so strictness selection
259
+ // stays consistent across tools and structured output.
260
+ const budget = buildSchemaBudget(info ?? { id: model.id, provider: this.name }, this.supportedStrictFamilies);
261
+ // Bedrock can't limit which tools a model calls, so only the allowed ones are sent
262
+ const allowed = withAllowedTools(request);
263
+ // Claude that always thinks can't be forced to call a tool, so it's
264
+ // offered only the forced tools instead
265
+ const choice = allowed.toolChoice;
266
+ const offered = ALWAYS_THINKING_CLAUDE.test(modelId) && forcesTool(choice)
267
+ ? withAllowedTools({ ...allowed, toolChoice: { allowed: typeof choice === 'object' && 'tool' in choice ? [choice.tool] : (allowed.tools ?? []).map(tool => tool.name) } })
268
+ : allowed;
269
+ const toolConfig = this.convertToolsToConverse(offered, budget);
270
+ const textFormat = this.convertResponseFormat(request, budget);
271
+ // A schema Converse can't take natively goes in the prompt
272
+ const sent = typeof request.responseFormat === 'object' && !textFormat ? deliverSchema(request, LENIENT, 'prompt') : request;
273
+ const maxTokens = request.maxTokens ?? (info ?? model).maxOutputTokens;
274
+ const reasoning = toReasoningRequest(modelId, request.reason, info?.reasoningEfforts, maxTokens, forcesTool(offered.toolChoice));
275
+ const fields = reasoning.fields || request.extra ? { ...reasoning.fields, ...request.extra } : undefined;
276
+ const messages = await this.convertMessagesToConverse(sent);
277
+ const system = await toSystemBlocks(sent.messages);
278
+ // Models the registry prices no cache reads for reject cache points
279
+ const caches = !info || info.pricing.text?.cached !== undefined;
203
280
  return {
204
281
  modelId,
205
- messages,
206
- system,
282
+ messages: caches ? messages : messages.map(message => ({ ...message, content: withoutCachePoints(message.content) })),
283
+ system: caches ? system : withoutCachePoints(system),
207
284
  inferenceConfig: {
208
285
  maxTokens,
209
286
  temperature: request.temperature,
@@ -211,9 +288,14 @@ export class AWSBedrockProvider {
211
288
  stopSequences: request.stop
212
289
  ? Array.isArray(request.stop) ? request.stop : [request.stop]
213
290
  : undefined,
291
+ ...reasoning.cleared,
214
292
  },
215
293
  toolConfig,
216
- additionalModelRequestFields: request.extra,
294
+ outputConfig: textFormat || reasoning.effort ? { textFormat, effort: reasoning.effort } : undefined,
295
+ serviceTier: toBedrockServiceTier(request.serviceTier),
296
+ performanceConfig: this.config.latency && { latency: this.config.latency },
297
+ requestMetadata: request.metadata,
298
+ additionalModelRequestFields: fields,
217
299
  };
218
300
  }
219
301
  /**
@@ -221,54 +303,25 @@ export class AWSBedrockProvider {
221
303
  */
222
304
  async executeWithConverse(modelInput, request, ctx) {
223
305
  const model = getModel(modelInput);
224
- const modelId = this.applyModelPrefix(model.id);
225
- const params = this.convertRequestToConverse(modelId, request, ctx);
306
+ const guardrail = this.config.guardrail;
226
307
  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
- };
308
+ const { command, response } = await this.byProfileWhenRequired(model.id, async () => {
309
+ const command = new ConverseCommand({
310
+ ...await this.convertRequestToConverse(model, request, ctx),
311
+ guardrailConfig: guardrail && { guardrailIdentifier: guardrail.guardrailIdentifier, guardrailVersion: guardrail.guardrailVersion, trace: guardrail.trace },
312
+ });
313
+ await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
314
+ return { command, response: await this.bedrockRuntimeClient.send(command) };
315
+ });
316
+ const result = getResponseFromChunks([
317
+ ...(response.output?.message?.content ?? []).map(contentBlockChunk),
318
+ endChunk(response.stopReason, response.usage, response.serviceTier),
319
+ ], modelInput);
267
320
  await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
268
321
  return result;
269
322
  }
270
323
  catch (error) {
271
- this.handleAWSError(error);
324
+ this.handleAWSError(error, request);
272
325
  throw error;
273
326
  }
274
327
  }
@@ -277,232 +330,68 @@ export class AWSBedrockProvider {
277
330
  */
278
331
  async *streamWithConverse(modelInput, request, ctx) {
279
332
  const model = getModel(modelInput);
280
- const modelId = this.applyModelPrefix(model.id);
281
- const params = this.convertRequestToConverse(modelId, request, ctx);
282
333
  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);
334
+ const { command, response } = await this.byProfileWhenRequired(model.id, async () => {
335
+ const command = new ConverseStreamCommand({ ...await this.convertRequestToConverse(model, request, ctx), guardrailConfig: this.config.guardrail });
336
+ await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
337
+ return { command, response: await this.bedrockRuntimeClient.send(command) };
338
+ });
286
339
  if (!response.stream) {
287
340
  throw new AWSError('No stream in streaming response');
288
341
  }
289
- let inputTokens = 0;
290
- let outputTokens = 0;
291
- let accumulatedContent = '';
292
- let finishReason = 'stop';
293
- const toolCallsMap = new Map();
342
+ // Tool calls in progress, by content block index
343
+ const calls = new Map();
344
+ const chunks = [];
294
345
  try {
295
346
  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
- };
347
+ const chunk = streamChunk(event, calls);
348
+ if (chunk) {
349
+ chunks.push(chunk);
350
+ yield chunk;
372
351
  }
373
352
  }
374
353
  }
375
354
  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);
355
+ await this.config.hooks?.chat?.afterRequest?.(request, command, getResponseFromChunks(chunks, modelInput), ctx);
394
356
  }
395
357
  }
396
358
  catch (error) {
397
- this.handleAWSError(error);
359
+ this.handleAWSError(error, request);
398
360
  throw error;
399
361
  }
400
362
  }
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
363
  /**
415
364
  * Convert @aeye/core messages to AWS Bedrock Converse API message format.
416
- * Filters out system messages (handled via convertSystemToConverse).
365
+ * Filters out system messages (handled via toSystemBlocks).
417
366
  * Merges consecutive messages with the same role as required by the API.
418
367
  */
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
- }
449
- }
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
- }
368
+ async convertMessagesToConverse(request) {
369
+ // An assistant turn split across messages replays its reasoning once
370
+ const replayed = new Set();
371
+ const rawMessages = await Promise.all(request.messages.map(async (msg) => {
372
+ switch (msg.role) {
373
+ case 'system':
374
+ return undefined;
375
+ case 'user':
376
+ return { role: 'user', content: await toContentBlocks(msg.content) };
377
+ case 'assistant':
378
+ return { role: 'assistant', content: await toAssistantBlocks(msg, replayed) };
379
+ case 'tool':
380
+ return { role: 'user', content: await toToolResultBlocks(msg) };
476
381
  }
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
- }
382
+ }));
497
383
  // Merge consecutive messages with the same role (required by Converse API)
498
384
  const merged = [];
499
385
  for (const msg of rawMessages) {
386
+ if (!msg?.content?.length) {
387
+ continue;
388
+ }
500
389
  const last = merged[merged.length - 1];
501
390
  if (last && last.role === msg.role) {
502
- last.content = [...(last.content ?? []), ...(msg.content ?? [])];
391
+ last.content = [...(last.content ?? []), ...msg.content];
503
392
  }
504
393
  else {
505
- merged.push({ role: msg.role, content: [...(msg.content ?? [])] });
394
+ merged.push(msg);
506
395
  }
507
396
  }
508
397
  // Ensure there is at least one user message
@@ -511,40 +400,17 @@ export class AWSBedrockProvider {
511
400
  }
512
401
  return merged;
513
402
  }
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
403
  /**
540
404
  * Convert @aeye/core tool definitions to AWS Bedrock Converse API tool format.
541
405
  *
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
406
+ * Strict-tool support is best-effort and per-model: the budget's
407
+ * descriptor comes from `buildSchemaBudget` (see `@aeye/ai`). Bedrock
545
408
  * 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
409
+ * OpenAI-shaped tools. Models without strict support use their family's
410
+ * non-strict descriptor, and models without a family Bedrock speaks fall
411
+ * back to LENIENT — silent degradation. Tools with a strict descriptor are
412
+ * sent with Converse's `strict` flag, which constrains the model's calls to
413
+ * the schema. The chosen descriptor is pinned on each
548
414
  * `ToolDefinition.descriptor` so the Prompt loop can apply the matching
549
415
  * strictify when validating tool arguments.
550
416
  *
@@ -552,47 +418,61 @@ export class AWSBedrockProvider {
552
418
  * params, 16 union types across the whole request) — those are tracked
553
419
  * by the shared `SchemaBudget` so over-budget tools degrade to LENIENT
554
420
  * silently rather than failing the API call.
421
+ *
422
+ * Converse has no free-text tools, so those go as their one-field function
423
+ * with any grammar in the description. It has no `none` choice either, so
424
+ * tools are left out then, unless the conversation already used them
425
+ * (Converse rejects tool blocks without a tool config).
555
426
  */
556
- convertToolsToConverse(request, model, budget) {
427
+ convertToolsToConverse(request, budget) {
557
428
  if (!request.tools || request.tools.length === 0)
558
429
  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
- }
430
+ const choice = request.toolChoice;
431
+ if (choice === 'none' && !request.messages.some(m => m.role === 'tool' || m.toolCalls?.length))
432
+ return undefined;
433
+ const descriptors = allocateToolDescriptors(request.tools, budget);
571
434
  const tools = request.tools.map((tool, i) => {
572
435
  const descriptor = descriptors[i];
573
436
  const strictifiedSchema = strictify(tool.parameters, descriptor);
574
437
  return {
575
438
  toolSpec: {
576
439
  name: tool.name,
577
- description: tool.description,
440
+ description: describeTool(tool),
578
441
  inputSchema: {
579
- json: toJSONSchema(strictifiedSchema, descriptor),
442
+ json: toDocument(JSON.stringify(toJSONSchema(strictifiedSchema, descriptor))),
580
443
  },
444
+ strict: descriptor.strict || undefined,
581
445
  },
582
446
  };
583
447
  });
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
- }
448
+ const toolChoice = choice === 'auto' ? { auto: {} }
449
+ : choice === 'required' ? { any: {} }
450
+ : typeof choice === 'object' && 'tool' in choice ? { tool: { name: choice.tool } }
451
+ : undefined;
594
452
  return { tools, toolChoice };
595
453
  }
454
+ /**
455
+ * Convert a schema response format to Converse structured output. Converse
456
+ * rejects schemas outside its strict subset, so a schema goes only when the
457
+ * model's strict descriptor can shape it; the descriptor is pinned on the
458
+ * format so the Prompt validator can apply the matching strictify. Plain
459
+ * JSON has no Converse mode.
460
+ */
461
+ convertResponseFormat(request, budget) {
462
+ const format = request.responseFormat;
463
+ if (typeof format !== 'object')
464
+ return undefined;
465
+ const descriptor = budget.allocateOutput(format.type, format.strict ?? 1);
466
+ if (!descriptor.strict)
467
+ return undefined;
468
+ format.descriptor = descriptor.id;
469
+ return {
470
+ type: 'json_schema',
471
+ structure: {
472
+ jsonSchema: { name: 'response', schema: JSON.stringify(toJSONSchema(strictify(format.type, descriptor), descriptor)) },
473
+ },
474
+ };
475
+ }
596
476
  /**
597
477
  * The set of strict descriptor families this provider can speak through
598
478
  * Bedrock. Defaults to `['openai', 'anthropic', 'google']` — Bedrock
@@ -600,43 +480,6 @@ export class AWSBedrockProvider {
600
480
  * families.
601
481
  */
602
482
  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
483
  // ============================================================================
641
484
  // Image Generation (Stability AI)
642
485
  // ============================================================================
@@ -745,15 +588,15 @@ export class AWSBedrockProvider {
745
588
  // ============================================================================
746
589
  // Error Handling
747
590
  // ============================================================================
748
- handleAWSError(error) {
591
+ handleAWSError(error, request) {
749
592
  const errorName = error.name || '';
750
593
  const errorMessage = error.message || '';
751
594
  // Authentication errors
752
- if (errorName === 'UnrecognizedClientException' || errorName === 'InvalidSignatureException') {
595
+ if (AUTH_ERRORS.has(errorName)) {
753
596
  throw new AWSAuthError(error);
754
597
  }
755
- // Rate limiting
756
- if (errorName === 'ThrottlingException' || errorName === 'TooManyRequestsException') {
598
+ // Rate limiting, and capacity that's busy for now
599
+ if (RATE_LIMIT_ERRORS.has(errorName)) {
757
600
  throw new AWSRateLimitError('Rate limit exceeded', undefined, error);
758
601
  }
759
602
  // Quota errors
@@ -761,9 +604,14 @@ export class AWSBedrockProvider {
761
604
  throw new AWSQuotaError(error);
762
605
  }
763
606
  // Context window errors
764
- if (errorMessage.includes('context length') || errorMessage.includes('token limit')) {
607
+ if (CONTEXT_WINDOW_ERROR.test(errorMessage)) {
765
608
  throw new AWSContextWindowError('Context window exceeded', undefined, error);
766
609
  }
610
+ // A rejected tool schema
611
+ const rejected = errorName === 'ValidationException' && request ? schemaRejection(request, error) : undefined;
612
+ if (rejected) {
613
+ throw rejected;
614
+ }
767
615
  // Re-throw as generic AWS error
768
616
  throw new AWSError(errorMessage || 'Unknown AWS Bedrock error', error);
769
617
  }