@aeye/aws 0.3.8 → 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,12 +5,60 @@
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 { getModel, 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';
9
10
  import { BedrockClient, ListFoundationModelsCommand } from '@aws-sdk/client-bedrock';
10
11
  import { BedrockRuntimeClient, ConverseCommand, ConverseStreamCommand, InvokeModelCommand, } from '@aws-sdk/client-bedrock-runtime';
11
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';
12
14
  import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLimitError } from './types';
13
15
  // ============================================================================
16
+ // AWS Bedrock Provider Configuration
17
+ // ============================================================================
18
+ /**
19
+ * Resolve the full ModelInfo for the request when available.
20
+ *
21
+ * BaseAPI injects `selected.model` into `ctx.metadata.model` after model
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).
25
+ */
26
+ function pickAwsModelInfo(model, ctx) {
27
+ if (isModelInfo(model)) {
28
+ return model;
29
+ }
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];
60
+ }
61
+ // ============================================================================
14
62
  // AWS Bedrock Provider Class
15
63
  // ============================================================================
16
64
  /**
@@ -45,11 +93,13 @@ import { AWSAuthError, AWSContextWindowError, AWSError, AWSQuotaError, AWSRateLi
45
93
  * ```
46
94
  */
47
95
  export class AWSBedrockProvider {
48
- name = 'aws-bedrock';
96
+ name = BEDROCK_PROVIDER;
49
97
  config;
50
98
  defaultMetadata;
51
99
  bedrockClient;
52
100
  bedrockRuntimeClient;
101
+ // Models found to need an inference profile in this region
102
+ profileOnly = new Set();
53
103
  constructor(config) {
54
104
  this.config = config;
55
105
  const clientConfig = AWSBedrockProvider.convertConfig(config);
@@ -139,7 +189,8 @@ export class AWSBedrockProvider {
139
189
  if (!modelInput) {
140
190
  throw new AWSError('Model is required for AWS Bedrock requests');
141
191
  }
142
- 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);
143
194
  };
144
195
  }
145
196
  /**
@@ -153,25 +204,83 @@ export class AWSBedrockProvider {
153
204
  if (!modelInput) {
154
205
  throw new AWSError('Model is required for AWS Bedrock requests');
155
206
  }
156
- yield* self.streamWithConverse(modelInput, request, ctx);
207
+ yield* self.streamWithConverse(modelInput, deliverSchema(request), ctx);
157
208
  };
158
209
  }
159
210
  // ============================================================================
160
211
  // Unified Converse API Implementation
161
212
  // ============================================================================
162
213
  /**
163
- * 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.
219
+ */
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.
164
254
  */
165
- convertRequestToConverse(modelId, request) {
166
- const messages = this.convertMessagesToConverse(request);
167
- const system = this.convertSystemToConverse(request);
168
- const toolConfig = this.convertToolsToConverse(request);
169
- const model = getModel(request.model);
170
- const maxTokens = request.maxTokens ?? (typeof model !== 'string' && model?.maxOutputTokens ? model.maxOutputTokens : undefined);
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;
171
280
  return {
172
281
  modelId,
173
- messages,
174
- system,
282
+ messages: caches ? messages : messages.map(message => ({ ...message, content: withoutCachePoints(message.content) })),
283
+ system: caches ? system : withoutCachePoints(system),
175
284
  inferenceConfig: {
176
285
  maxTokens,
177
286
  temperature: request.temperature,
@@ -179,9 +288,14 @@ export class AWSBedrockProvider {
179
288
  stopSequences: request.stop
180
289
  ? Array.isArray(request.stop) ? request.stop : [request.stop]
181
290
  : undefined,
291
+ ...reasoning.cleared,
182
292
  },
183
293
  toolConfig,
184
- 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,
185
299
  };
186
300
  }
187
301
  /**
@@ -189,54 +303,25 @@ export class AWSBedrockProvider {
189
303
  */
190
304
  async executeWithConverse(modelInput, request, ctx) {
191
305
  const model = getModel(modelInput);
192
- const modelId = this.applyModelPrefix(model.id);
193
- const params = this.convertRequestToConverse(modelId, request);
306
+ const guardrail = this.config.guardrail;
194
307
  try {
195
- const command = new ConverseCommand(params);
196
- await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
197
- const response = await this.bedrockRuntimeClient.send(command);
198
- let content = '';
199
- let reasoning;
200
- const toolCalls = [];
201
- const outputMessage = response.output?.message;
202
- if (outputMessage?.content) {
203
- for (const block of outputMessage.content) {
204
- if ('text' in block && block.text !== undefined) {
205
- content += block.text;
206
- }
207
- else if ('toolUse' in block && block.toolUse) {
208
- toolCalls.push({
209
- id: block.toolUse.toolUseId,
210
- name: block.toolUse.name,
211
- arguments: JSON.stringify(block.toolUse.input ?? {}),
212
- });
213
- }
214
- else if ('reasoningContent' in block && block.reasoningContent) {
215
- const rc = block.reasoningContent;
216
- if ('reasoningText' in rc && rc.reasoningText) {
217
- reasoning = (reasoning ?? '') + rc.reasoningText.text;
218
- }
219
- }
220
- }
221
- }
222
- const result = {
223
- content,
224
- reasoning: reasoning !== undefined ? { content: reasoning } : undefined,
225
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
226
- finishReason: this.mapStopReason(response.stopReason),
227
- model: modelInput,
228
- usage: {
229
- text: {
230
- input: response.usage?.inputTokens ?? -1,
231
- output: response.usage?.outputTokens ?? -1,
232
- },
233
- },
234
- };
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);
235
320
  await this.config.hooks?.chat?.afterRequest?.(request, command, result, ctx);
236
321
  return result;
237
322
  }
238
323
  catch (error) {
239
- this.handleAWSError(error);
324
+ this.handleAWSError(error, request);
240
325
  throw error;
241
326
  }
242
327
  }
@@ -245,232 +330,68 @@ export class AWSBedrockProvider {
245
330
  */
246
331
  async *streamWithConverse(modelInput, request, ctx) {
247
332
  const model = getModel(modelInput);
248
- const modelId = this.applyModelPrefix(model.id);
249
- const params = this.convertRequestToConverse(modelId, request);
250
333
  try {
251
- const command = new ConverseStreamCommand(params);
252
- await this.config.hooks?.chat?.beforeRequest?.(request, command, ctx);
253
- 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
+ });
254
339
  if (!response.stream) {
255
340
  throw new AWSError('No stream in streaming response');
256
341
  }
257
- let inputTokens = 0;
258
- let outputTokens = 0;
259
- let accumulatedContent = '';
260
- let finishReason = 'stop';
261
- const toolCallsMap = new Map();
342
+ // Tool calls in progress, by content block index
343
+ const calls = new Map();
344
+ const chunks = [];
262
345
  try {
263
346
  for await (const event of response.stream) {
264
- if (event.contentBlockDelta?.delta) {
265
- const delta = event.contentBlockDelta.delta;
266
- const index = event.contentBlockDelta.contentBlockIndex ?? 0;
267
- if ('text' in delta && delta.text !== undefined) {
268
- accumulatedContent += delta.text;
269
- yield { content: delta.text };
270
- }
271
- else if ('toolUse' in delta && delta.toolUse?.input !== undefined) {
272
- const toolCall = toolCallsMap.get(index);
273
- if (toolCall) {
274
- toolCall.arguments += delta.toolUse.input;
275
- yield {
276
- toolCallArguments: {
277
- id: toolCall.id,
278
- name: toolCall.name,
279
- arguments: toolCall.arguments,
280
- },
281
- };
282
- }
283
- }
284
- else if ('reasoningContent' in delta && delta.reasoningContent) {
285
- const rc = delta.reasoningContent;
286
- if ('text' in rc && rc.text !== undefined) {
287
- yield { reasoning: { content: rc.text } };
288
- }
289
- }
290
- }
291
- else if (event.contentBlockStart?.start) {
292
- const start = event.contentBlockStart.start;
293
- const index = event.contentBlockStart.contentBlockIndex ?? 0;
294
- if ('toolUse' in start && start.toolUse) {
295
- const toolCall = {
296
- id: start.toolUse.toolUseId,
297
- name: start.toolUse.name,
298
- arguments: '',
299
- finished: false,
300
- };
301
- toolCallsMap.set(index, toolCall);
302
- yield {
303
- toolCallNamed: {
304
- id: toolCall.id,
305
- name: toolCall.name,
306
- arguments: '',
307
- },
308
- };
309
- }
310
- }
311
- else if (event.contentBlockStop) {
312
- const index = event.contentBlockStop.contentBlockIndex ?? 0;
313
- const toolCall = toolCallsMap.get(index);
314
- if (toolCall && !toolCall.finished) {
315
- toolCall.finished = true;
316
- yield {
317
- toolCall: {
318
- id: toolCall.id,
319
- name: toolCall.name,
320
- arguments: toolCall.arguments,
321
- },
322
- };
323
- }
324
- }
325
- else if (event.messageStop) {
326
- finishReason = this.mapStopReason(event.messageStop.stopReason);
327
- yield { finishReason };
328
- }
329
- else if (event.metadata?.usage) {
330
- inputTokens = event.metadata.usage.inputTokens ?? 0;
331
- outputTokens = event.metadata.usage.outputTokens ?? 0;
332
- yield {
333
- usage: {
334
- text: {
335
- input: inputTokens,
336
- output: outputTokens,
337
- },
338
- },
339
- };
347
+ const chunk = streamChunk(event, calls);
348
+ if (chunk) {
349
+ chunks.push(chunk);
350
+ yield chunk;
340
351
  }
341
352
  }
342
353
  }
343
354
  finally {
344
- const toolCalls = Array.from(toolCallsMap.values()).map(tc => ({
345
- id: tc.id,
346
- name: tc.name,
347
- arguments: tc.arguments,
348
- }));
349
- const accumulatedResponse = {
350
- content: accumulatedContent,
351
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
352
- finishReason,
353
- model: modelInput,
354
- usage: {
355
- text: {
356
- input: inputTokens,
357
- output: outputTokens,
358
- },
359
- },
360
- };
361
- await this.config.hooks?.chat?.afterRequest?.(request, command, accumulatedResponse, ctx);
355
+ await this.config.hooks?.chat?.afterRequest?.(request, command, getResponseFromChunks(chunks, modelInput), ctx);
362
356
  }
363
357
  }
364
358
  catch (error) {
365
- this.handleAWSError(error);
359
+ this.handleAWSError(error, request);
366
360
  throw error;
367
361
  }
368
362
  }
369
- /**
370
- * Convert system messages to the Converse API system format.
371
- */
372
- convertSystemToConverse(request) {
373
- const systemMessages = request.messages.filter(m => m.role === 'system');
374
- if (systemMessages.length === 0)
375
- return undefined;
376
- return systemMessages.map((m) => ({
377
- text: typeof m.content === 'string'
378
- ? m.content
379
- : m.content.map(c => String(c.content)).join('\n'),
380
- }));
381
- }
382
363
  /**
383
364
  * Convert @aeye/core messages to AWS Bedrock Converse API message format.
384
- * Filters out system messages (handled via convertSystemToConverse).
365
+ * Filters out system messages (handled via toSystemBlocks).
385
366
  * Merges consecutive messages with the same role as required by the API.
386
367
  */
387
- convertMessagesToConverse(request) {
388
- const rawMessages = [];
389
- for (const msg of request.messages) {
390
- if (msg.role === 'system')
391
- continue;
392
- if (msg.role === 'user') {
393
- const content = [];
394
- if (typeof msg.content === 'string') {
395
- if (msg.content.trim()) {
396
- content.push({ text: msg.content });
397
- }
398
- }
399
- else {
400
- for (const part of msg.content) {
401
- if (part.type === 'text') {
402
- if (String(part.content).trim()) {
403
- content.push({ text: String(part.content) });
404
- }
405
- }
406
- else if (part.type === 'image') {
407
- const imageBlock = this.convertImageContent(part.content);
408
- if (imageBlock) {
409
- content.push(imageBlock);
410
- }
411
- }
412
- }
413
- }
414
- if (content.length > 0) {
415
- rawMessages.push({ role: 'user', content });
416
- }
417
- }
418
- else if (msg.role === 'assistant') {
419
- const content = [];
420
- if (msg.content && typeof msg.content === 'string' && msg.content.trim()) {
421
- content.push({ text: msg.content });
422
- }
423
- if (msg.toolCalls && msg.toolCalls.length > 0) {
424
- for (const tc of msg.toolCalls) {
425
- let input = {};
426
- try {
427
- input = JSON.parse(tc.arguments);
428
- }
429
- catch {
430
- input = { _raw: tc.arguments };
431
- }
432
- content.push({
433
- toolUse: {
434
- toolUseId: tc.id,
435
- name: tc.name,
436
- input: input,
437
- },
438
- });
439
- }
440
- }
441
- if (content.length > 0) {
442
- rawMessages.push({ role: 'assistant', content });
443
- }
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) };
444
381
  }
445
- else if (msg.role === 'tool') {
446
- rawMessages.push({
447
- role: 'user',
448
- content: [
449
- {
450
- toolResult: {
451
- toolUseId: msg.toolCallId,
452
- content: [
453
- {
454
- text: typeof msg.content === 'string'
455
- ? msg.content
456
- : JSON.stringify(msg.content),
457
- },
458
- ],
459
- },
460
- },
461
- ],
462
- });
463
- }
464
- }
382
+ }));
465
383
  // Merge consecutive messages with the same role (required by Converse API)
466
384
  const merged = [];
467
385
  for (const msg of rawMessages) {
386
+ if (!msg?.content?.length) {
387
+ continue;
388
+ }
468
389
  const last = merged[merged.length - 1];
469
390
  if (last && last.role === msg.role) {
470
- last.content = [...(last.content ?? []), ...(msg.content ?? [])];
391
+ last.content = [...(last.content ?? []), ...msg.content];
471
392
  }
472
393
  else {
473
- merged.push({ role: msg.role, content: [...(msg.content ?? [])] });
394
+ merged.push(msg);
474
395
  }
475
396
  }
476
397
  // Ensure there is at least one user message
@@ -479,78 +400,86 @@ export class AWSBedrockProvider {
479
400
  }
480
401
  return merged;
481
402
  }
482
- /**
483
- * Convert an image content value to a Converse API ContentBlock.
484
- * Only base64 data URIs are natively supported; URL images are not supported
485
- * by the Converse API without fetching the bytes first.
486
- */
487
- convertImageContent(content) {
488
- const src = content instanceof URL ? content.href : typeof content === 'string' ? content : null;
489
- if (!src)
490
- return null;
491
- // data URI: data:<mediaType>;base64,<data>
492
- const match = src.match(/^data:([^;]+);base64,(.+)$/);
493
- if (match) {
494
- const mediaType = match[1].toLowerCase();
495
- const format = (mediaType.includes('png') ? 'png' :
496
- mediaType.includes('jpeg') || mediaType.includes('jpg') ? 'jpeg' :
497
- mediaType.includes('gif') ? 'gif' :
498
- mediaType.includes('webp') ? 'webp' : null);
499
- if (format) {
500
- const bytes = Buffer.from(match[2], 'base64');
501
- return { image: { format, source: { bytes } } };
502
- }
503
- }
504
- // URL images are not natively supported by the Converse API
505
- return null;
506
- }
507
403
  /**
508
404
  * Convert @aeye/core tool definitions to AWS Bedrock Converse API tool format.
405
+ *
406
+ * Strict-tool support is best-effort and per-model: the budget's
407
+ * descriptor comes from `buildSchemaBudget` (see `@aeye/ai`). Bedrock
408
+ * surfaces both Anthropic-family Claude models and (in some regions)
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
414
+ * `ToolDefinition.descriptor` so the Prompt loop can apply the matching
415
+ * strictify when validating tool arguments.
416
+ *
417
+ * Anthropic enforces per-request limits (20 strict tools, 24 optional
418
+ * params, 16 union types across the whole request) — those are tracked
419
+ * by the shared `SchemaBudget` so over-budget tools degrade to LENIENT
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).
509
426
  */
510
- convertToolsToConverse(request) {
427
+ convertToolsToConverse(request, budget) {
511
428
  if (!request.tools || request.tools.length === 0)
512
429
  return undefined;
513
- const tools = request.tools.map(tool => ({
514
- toolSpec: {
515
- name: tool.name,
516
- description: tool.description,
517
- inputSchema: {
518
- json: toJSONSchema(tool.parameters, tool.strict ?? true),
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);
434
+ const tools = request.tools.map((tool, i) => {
435
+ const descriptor = descriptors[i];
436
+ const strictifiedSchema = strictify(tool.parameters, descriptor);
437
+ return {
438
+ toolSpec: {
439
+ name: tool.name,
440
+ description: describeTool(tool),
441
+ inputSchema: {
442
+ json: toDocument(JSON.stringify(toJSONSchema(strictifiedSchema, descriptor))),
443
+ },
444
+ strict: descriptor.strict || undefined,
519
445
  },
520
- },
521
- }));
522
- let toolChoice;
523
- if (request.toolChoice === 'auto') {
524
- toolChoice = { auto: {} };
525
- }
526
- else if (request.toolChoice === 'required') {
527
- toolChoice = { any: {} };
528
- }
529
- else if (typeof request.toolChoice === 'object' && request.toolChoice !== null) {
530
- toolChoice = { tool: { name: request.toolChoice.tool } };
531
- }
446
+ };
447
+ });
448
+ const toolChoice = choice === 'auto' ? { auto: {} }
449
+ : choice === 'required' ? { any: {} }
450
+ : typeof choice === 'object' && 'tool' in choice ? { tool: { name: choice.tool } }
451
+ : undefined;
532
452
  return { tools, toolChoice };
533
453
  }
534
454
  /**
535
- * Map a Bedrock Converse API stop reason to the @aeye/core FinishReason type.
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.
536
460
  */
537
- mapStopReason(stopReason) {
538
- switch (stopReason) {
539
- case 'end_turn':
540
- return 'stop';
541
- case 'max_tokens':
542
- case 'model_context_window_exceeded':
543
- return 'length';
544
- case 'stop_sequence':
545
- return 'stop';
546
- case 'tool_use':
547
- return 'tool_calls';
548
- case 'content_filtered':
549
- return 'content_filter';
550
- default:
551
- return 'stop';
552
- }
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
+ };
553
475
  }
476
+ /**
477
+ * The set of strict descriptor families this provider can speak through
478
+ * Bedrock. Defaults to `['openai', 'anthropic', 'google']` — Bedrock
479
+ * surfaces all three. Subclasses can extend to accept custom registered
480
+ * families.
481
+ */
482
+ supportedStrictFamilies = new Set(['openai', 'anthropic', 'google']);
554
483
  // ============================================================================
555
484
  // Image Generation (Stability AI)
556
485
  // ============================================================================
@@ -659,15 +588,15 @@ export class AWSBedrockProvider {
659
588
  // ============================================================================
660
589
  // Error Handling
661
590
  // ============================================================================
662
- handleAWSError(error) {
591
+ handleAWSError(error, request) {
663
592
  const errorName = error.name || '';
664
593
  const errorMessage = error.message || '';
665
594
  // Authentication errors
666
- if (errorName === 'UnrecognizedClientException' || errorName === 'InvalidSignatureException') {
595
+ if (AUTH_ERRORS.has(errorName)) {
667
596
  throw new AWSAuthError(error);
668
597
  }
669
- // Rate limiting
670
- if (errorName === 'ThrottlingException' || errorName === 'TooManyRequestsException') {
598
+ // Rate limiting, and capacity that's busy for now
599
+ if (RATE_LIMIT_ERRORS.has(errorName)) {
671
600
  throw new AWSRateLimitError('Rate limit exceeded', undefined, error);
672
601
  }
673
602
  // Quota errors
@@ -675,9 +604,14 @@ export class AWSBedrockProvider {
675
604
  throw new AWSQuotaError(error);
676
605
  }
677
606
  // Context window errors
678
- if (errorMessage.includes('context length') || errorMessage.includes('token limit')) {
607
+ if (CONTEXT_WINDOW_ERROR.test(errorMessage)) {
679
608
  throw new AWSContextWindowError('Context window exceeded', undefined, error);
680
609
  }
610
+ // A rejected tool schema
611
+ const rejected = errorName === 'ValidationException' && request ? schemaRejection(request, error) : undefined;
612
+ if (rejected) {
613
+ throw rejected;
614
+ }
681
615
  // Re-throw as generic AWS error
682
616
  throw new AWSError(errorMessage || 'Unknown AWS Bedrock error', error);
683
617
  }