@effect/ai-amazon-bedrock 0.6.2 → 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.
Files changed (48) hide show
  1. package/AmazonBedrockTool/package.json +6 -0
  2. package/dist/cjs/AmazonBedrockClient.js +71 -145
  3. package/dist/cjs/AmazonBedrockClient.js.map +1 -1
  4. package/dist/cjs/AmazonBedrockLanguageModel.js +833 -337
  5. package/dist/cjs/AmazonBedrockLanguageModel.js.map +1 -1
  6. package/dist/cjs/AmazonBedrockSchema.js +94 -39
  7. package/dist/cjs/AmazonBedrockSchema.js.map +1 -1
  8. package/dist/cjs/AmazonBedrockTool.js +53 -0
  9. package/dist/cjs/AmazonBedrockTool.js.map +1 -0
  10. package/dist/cjs/EventStreamEncoding.js +5 -4
  11. package/dist/cjs/EventStreamEncoding.js.map +1 -1
  12. package/dist/cjs/index.js +3 -1
  13. package/dist/cjs/internal/utilities.js +3 -1
  14. package/dist/cjs/internal/utilities.js.map +1 -1
  15. package/dist/dts/AmazonBedrockClient.d.ts +34 -34
  16. package/dist/dts/AmazonBedrockClient.d.ts.map +1 -1
  17. package/dist/dts/AmazonBedrockLanguageModel.d.ts +72 -20
  18. package/dist/dts/AmazonBedrockLanguageModel.d.ts.map +1 -1
  19. package/dist/dts/AmazonBedrockSchema.d.ts +543 -102
  20. package/dist/dts/AmazonBedrockSchema.d.ts.map +1 -1
  21. package/dist/dts/AmazonBedrockTool.d.ts +184 -0
  22. package/dist/dts/AmazonBedrockTool.d.ts.map +1 -0
  23. package/dist/dts/EventStreamEncoding.d.ts +2 -2
  24. package/dist/dts/EventStreamEncoding.d.ts.map +1 -1
  25. package/dist/dts/index.d.ts +4 -0
  26. package/dist/dts/index.d.ts.map +1 -1
  27. package/dist/esm/AmazonBedrockClient.js +71 -144
  28. package/dist/esm/AmazonBedrockClient.js.map +1 -1
  29. package/dist/esm/AmazonBedrockLanguageModel.js +830 -333
  30. package/dist/esm/AmazonBedrockLanguageModel.js.map +1 -1
  31. package/dist/esm/AmazonBedrockSchema.js +93 -37
  32. package/dist/esm/AmazonBedrockSchema.js.map +1 -1
  33. package/dist/esm/AmazonBedrockTool.js +45 -0
  34. package/dist/esm/AmazonBedrockTool.js.map +1 -0
  35. package/dist/esm/EventStreamEncoding.js +5 -3
  36. package/dist/esm/EventStreamEncoding.js.map +1 -1
  37. package/dist/esm/index.js +4 -0
  38. package/dist/esm/index.js.map +1 -1
  39. package/dist/esm/internal/utilities.js +2 -0
  40. package/dist/esm/internal/utilities.js.map +1 -1
  41. package/package.json +13 -4
  42. package/src/AmazonBedrockClient.ts +144 -241
  43. package/src/AmazonBedrockLanguageModel.ts +962 -372
  44. package/src/AmazonBedrockSchema.ts +134 -46
  45. package/src/AmazonBedrockTool.ts +251 -0
  46. package/src/EventStreamEncoding.ts +80 -73
  47. package/src/index.ts +5 -0
  48. package/src/internal/utilities.ts +6 -3
@@ -1,24 +1,28 @@
1
1
  /**
2
2
  * @since 1.0.0
3
3
  */
4
- import { AiError } from "@effect/ai/AiError";
5
- import * as AiLanguageModel from "@effect/ai/AiLanguageModel";
6
- import * as AiModel from "@effect/ai/AiModel";
7
- import * as AiResponse from "@effect/ai/AiResponse";
8
- import { addGenAIAnnotations } from "@effect/ai/AiTelemetry";
9
- import * as Arr from "effect/Array";
4
+ import { prepareTools as prepareAnthropicTools } from "@effect/ai-anthropic/AnthropicLanguageModel";
5
+ import * as AnthropicTool from "@effect/ai-anthropic/AnthropicTool";
6
+ import * as AiError from "@effect/ai/AiError";
7
+ import * as LanguageModel from "@effect/ai/LanguageModel";
8
+ import * as AiModel from "@effect/ai/Model";
9
+ import { addGenAIAnnotations } from "@effect/ai/Telemetry";
10
+ import * as Tool from "@effect/ai/Tool";
10
11
  import * as Context from "effect/Context";
12
+ import * as DateTime from "effect/DateTime";
11
13
  import * as Effect from "effect/Effect";
12
14
  import * as Encoding from "effect/Encoding";
13
- import { dual, identity } from "effect/Function";
15
+ import { dual } from "effect/Function";
14
16
  import * as Layer from "effect/Layer";
15
- import * as Option from "effect/Option";
16
17
  import * as Predicate from "effect/Predicate";
17
18
  import * as Stream from "effect/Stream";
18
19
  import { AmazonBedrockClient } from "./AmazonBedrockClient.js";
20
+ import { ImageFormat } from "./AmazonBedrockSchema.js";
19
21
  import * as InternalUtilities from "./internal/utilities.js";
20
- const constDisableValidation = {
21
- disableValidation: true
22
+ const BEDROCK_CACHE_POINT = {
23
+ cachePoint: {
24
+ type: "default"
25
+ }
22
26
  };
23
27
  // =============================================================================
24
28
  // Configuration
@@ -34,21 +38,13 @@ export class Config extends /*#__PURE__*/Context.Tag("@effect/ai-amazon-bedrock/
34
38
  static getOrUndefined = /*#__PURE__*/Effect.map(/*#__PURE__*/Effect.context(), context => context.unsafeMap.get(Config.key));
35
39
  }
36
40
  // =============================================================================
37
- // Amazon Bedrock Provider Metadata
38
- // =============================================================================
39
- /**
40
- * @since 1.0.0
41
- * @category Context
42
- */
43
- export class ProviderMetadata extends /*#__PURE__*/Context.Tag(InternalUtilities.ProviderMetadataKey)() {}
44
- // =============================================================================
45
41
  // Amazon Bedrock Language Model
46
42
  // =============================================================================
47
43
  /**
48
44
  * @since 1.0.0
49
45
  * @category AiModels
50
46
  */
51
- export const model = (model, config) => AiModel.make(layer({
47
+ export const model = (model, config) => AiModel.make("amazon-bedrock", layer({
52
48
  model,
53
49
  config
54
50
  }));
@@ -58,107 +54,109 @@ export const model = (model, config) => AiModel.make(layer({
58
54
  */
59
55
  export const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {
60
56
  const client = yield* AmazonBedrockClient;
61
- const makeToolConfig = options => {
62
- if (options.tools.length === 0) return undefined;
63
- const isStructured = options.tools.length === 1 && options.tools[0].structured;
64
- const tools = options.tools.map(tool => ({
65
- toolSpec: {
66
- name: tool.name,
67
- description: tool.description,
68
- inputSchema: {
69
- json: tool.parameters
70
- }
71
- }
72
- }));
73
- const toolConfig = {
74
- tools
75
- };
76
- if (isStructured) {
77
- toolConfig.toolChoice = {
78
- tool: {
79
- name: options.tools[0].name
80
- }
81
- };
82
- return toolConfig;
83
- }
84
- if (options.toolChoice === "auto") {
85
- toolConfig.toolChoice = {
86
- auto: {}
87
- };
88
- } else if (options.toolChoice === "none") {
89
- toolConfig.toolChoice = undefined;
90
- } else if (options.toolChoice === "required") {
91
- toolConfig.toolChoice = {
92
- any: {}
93
- };
94
- } else {
95
- toolConfig.toolChoice = {
96
- tool: {
97
- name: options.toolChoice.tool
98
- }
99
- };
100
- }
101
- return toolConfig;
102
- };
103
- const makeRequest = Effect.fnUntraced(function* (method, {
104
- prompt,
105
- system,
106
- ...rest
107
- }) {
57
+ const makeRequest = Effect.fnUntraced(function* (providerOptions) {
108
58
  const context = yield* Effect.context();
109
- const messages = yield* makeMessages(method, prompt);
110
- const toolConfig = makeToolConfig(rest);
111
- return identity({
59
+ const config = {
112
60
  modelId: options.model,
113
61
  ...options.config,
114
- ...context.unsafeMap.get(Config.key),
115
- // TODO: re-evaluate a better way to do this
116
- system: system.pipe(Option.map(text => [{
117
- text
118
- }]), Option.getOrUndefined),
62
+ ...context.unsafeMap.get(Config.key)
63
+ };
64
+ const {
119
65
  messages,
66
+ system
67
+ } = yield* prepareMessages(providerOptions);
68
+ const {
69
+ additionalTools,
70
+ betas,
120
71
  toolConfig
121
- });
72
+ } = yield* prepareTools(providerOptions, config);
73
+ const responseFormat = providerOptions.responseFormat;
74
+ const request = {
75
+ ...config,
76
+ system,
77
+ messages,
78
+ // Handle tool configuration
79
+ ...(responseFormat.type === "json" ? {
80
+ toolConfig: {
81
+ tools: [{
82
+ toolSpec: {
83
+ name: responseFormat.objectName,
84
+ description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ?? "Respond with a JSON object",
85
+ inputSchema: {
86
+ json: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast)
87
+ }
88
+ }
89
+ }],
90
+ toolChoice: {
91
+ tool: {
92
+ name: responseFormat.objectName
93
+ }
94
+ }
95
+ }
96
+ } : Predicate.isNotUndefined(toolConfig.tools) && toolConfig.tools.length > 0 ? {
97
+ toolConfig
98
+ } : {}),
99
+ // Handle additional model request fields
100
+ ...(Predicate.isNotUndefined(additionalTools) ? {
101
+ additionalModelRequestFields: {
102
+ ...config.additionalModelRequestFields,
103
+ ...additionalTools
104
+ }
105
+ } : {})
106
+ };
107
+ return {
108
+ betas,
109
+ request
110
+ };
122
111
  });
123
- return yield* AiLanguageModel.make({
124
- generateText: Effect.fnUntraced(function* (_options) {
125
- const request = yield* makeRequest("generateText", _options);
126
- annotateRequest(_options.span, request);
127
- const rawResponse = yield* client.client.converse(request);
128
- const context = yield* Effect.context();
129
- const model = Option.match(Context.getOption(context, Config), {
130
- onNone: () => options.model,
131
- onSome: ({
132
- modelId
133
- }) => modelId ?? options.model
112
+ return yield* LanguageModel.make({
113
+ generateText: Effect.fnUntraced(function* (options) {
114
+ const {
115
+ betas,
116
+ request
117
+ } = yield* makeRequest(options);
118
+ annotateRequest(options.span, request);
119
+ const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined;
120
+ const rawResponse = yield* client.converse({
121
+ params: {
122
+ "anthropic-beta": anthropicBeta
123
+ },
124
+ payload: request
134
125
  });
135
- annotateChatResponse(_options.span, model, rawResponse);
136
- const response = yield* makeResponse(rawResponse, model);
126
+ annotateResponse(options.span, request, rawResponse);
127
+ return yield* makeResponse(request, rawResponse, options);
128
+ }),
129
+ streamText: Effect.fnUntraced(function* (options) {
130
+ const {
131
+ betas,
132
+ request
133
+ } = yield* makeRequest(options);
134
+ annotateRequest(options.span, request);
135
+ const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined;
136
+ const stream = client.converseStream({
137
+ params: {
138
+ "anthropic-beta": anthropicBeta
139
+ },
140
+ payload: request
141
+ });
142
+ return {
143
+ request,
144
+ stream
145
+ };
146
+ }, (effect, options) => effect.pipe(Effect.flatMap(({
147
+ request,
148
+ stream
149
+ }) => makeStreamResponse(request, stream, options)), Stream.unwrap, Stream.map(response => {
150
+ annotateStreamResponse(options.span, response);
137
151
  return response;
138
- }, Effect.catchAll(cause => AiError.is(cause) ? cause : new AiError({
139
- module: "AmazonBedrockLanguageModel",
140
- method: "generateText",
141
- description: "An error occurred",
142
- cause
143
- }))),
144
- streamText(_options) {
145
- return makeRequest("streamText", _options).pipe(Effect.tap(request => annotateRequest(_options.span, request)), Effect.map(client.stream), Stream.unwrap, Stream.map(response => {
146
- annotateStreamResponse(_options.span, response);
147
- return response;
148
- }), Stream.catchAll(cause => AiError.is(cause) ? Effect.fail(cause) : Effect.fail(new AiError({
149
- module: "AmazonBedrockLanguageModel",
150
- method: "streamText",
151
- description: "An error occurred",
152
- cause
153
- }))));
154
- }
152
+ })))
155
153
  });
156
154
  });
157
155
  /**
158
156
  * @since 1.0.0
159
157
  * @category Layers
160
158
  */
161
- export const layer = options => Layer.effect(AiLanguageModel.AiLanguageModel, make({
159
+ export const layer = options => Layer.effect(LanguageModel.LanguageModel, make({
162
160
  model: options.model,
163
161
  config: options.config
164
162
  }));
@@ -170,88 +168,163 @@ export const withConfigOverride = /*#__PURE__*/dual(2, (self, overrides) => Effe
170
168
  ...config,
171
169
  ...overrides
172
170
  })));
173
- const groupMessages = prompt => {
171
+ // =============================================================================
172
+ // Prompt Conversion
173
+ // =============================================================================
174
+ const prepareMessages = /*#__PURE__*/Effect.fnUntraced(function* (options) {
175
+ const groups = groupMessages(options.prompt);
176
+ const system = [];
174
177
  const messages = [];
175
- let current = undefined;
176
- for (const message of prompt.messages) {
177
- switch (message._tag) {
178
- case "AssistantMessage":
178
+ let documentCounter = 0;
179
+ const nextDocumentName = () => `document-${++documentCounter}`;
180
+ for (let i = 0; i < groups.length; i++) {
181
+ const group = groups[i];
182
+ const isLastGroup = i === groups.length - 1;
183
+ switch (group.type) {
184
+ case "system":
179
185
  {
180
- if (current?.type !== "assistant") {
181
- current = {
182
- type: "assistant",
183
- messages: []
184
- };
185
- messages.push(current);
186
+ if (messages.length > 0) {
187
+ return yield* new AiError.MalformedInput({
188
+ module: "AmazonBedrockLanguageModel",
189
+ method: "prepareMessages",
190
+ description: "Multiple system messages separated by user / assistant messages"
191
+ });
192
+ }
193
+ for (const message of group.messages) {
194
+ system.push({
195
+ text: message.content
196
+ });
197
+ if (Predicate.isNotUndefined(getCachePoint(message))) {
198
+ system.push(BEDROCK_CACHE_POINT);
199
+ }
186
200
  }
187
- current.messages.push(message);
188
201
  break;
189
202
  }
190
- case "ToolMessage":
191
- case "UserMessage":
203
+ case "user":
192
204
  {
193
- if (current?.type !== "user") {
194
- current = {
195
- type: "user",
196
- messages: []
197
- };
198
- messages.push(current);
205
+ const content = [];
206
+ for (const message of group.messages) {
207
+ switch (message.role) {
208
+ case "user":
209
+ {
210
+ for (let j = 0; j < message.content.length; j++) {
211
+ const part = message.content[j];
212
+ switch (part.type) {
213
+ case "text":
214
+ {
215
+ content.push({
216
+ text: part.text
217
+ });
218
+ break;
219
+ }
220
+ case "file":
221
+ {
222
+ if (part.data instanceof URL) {
223
+ // TODO(Max): support this
224
+ return yield* new AiError.MalformedInput({
225
+ module: "AmazonBedrockLanguageModel",
226
+ method: "makeMessages",
227
+ description: "File URL inputs are not supported at this time"
228
+ });
229
+ }
230
+ if (part.mediaType.startsWith("image/")) {
231
+ content.push({
232
+ image: {
233
+ format: yield* getImageFormat(part.mediaType),
234
+ source: {
235
+ bytes: convertToBase64(part.data)
236
+ }
237
+ }
238
+ });
239
+ } else {
240
+ content.push({
241
+ document: {
242
+ format: yield* getDocumentFormat(part.mediaType),
243
+ name: nextDocumentName(),
244
+ source: {
245
+ bytes: convertToBase64(part.data)
246
+ }
247
+ }
248
+ });
249
+ }
250
+ break;
251
+ }
252
+ }
253
+ }
254
+ break;
255
+ }
256
+ case "tool":
257
+ {
258
+ for (const part of message.content) {
259
+ content.push({
260
+ toolResult: {
261
+ toolUseId: part.id,
262
+ content: [{
263
+ text: JSON.stringify(part.result)
264
+ }]
265
+ }
266
+ });
267
+ }
268
+ break;
269
+ }
270
+ }
199
271
  }
200
- current.messages.push(message);
272
+ messages.push({
273
+ role: "user",
274
+ content
275
+ });
201
276
  break;
202
277
  }
203
- }
204
- }
205
- return messages;
206
- };
207
- let fileCounter = 0;
208
- const makeMessages = /*#__PURE__*/Effect.fnUntraced(function* (method, prompt) {
209
- const messages = [];
210
- const groups = groupMessages(prompt);
211
- for (let i = 0; i < groups.length; i++) {
212
- const group = groups[i];
213
- const isLastGroup = i === groups.length - 1;
214
- switch (group.type) {
215
278
  case "assistant":
216
279
  {
217
280
  const content = [];
218
281
  for (let j = 0; j < group.messages.length; j++) {
219
282
  const message = group.messages[j];
220
283
  const isLastMessage = j === group.messages.length - 1;
221
- for (let k = 0; k < message.parts.length; k++) {
222
- const part = message.parts[k];
223
- const isLastPart = k === message.parts.length - 1;
224
- switch (part._tag) {
225
- case "TextPart":
284
+ for (let k = 0; k < message.content.length; k++) {
285
+ const part = message.content[k];
286
+ const isLastPart = k === message.content.length - 1;
287
+ switch (part.type) {
288
+ case "text":
226
289
  {
290
+ // Skip empty text blocks
291
+ if (part.text.trim().length === 0) {
292
+ break;
293
+ }
227
294
  content.push({
295
+ // Amazon Bedrock does not allow trailing whitespace in
296
+ // assistant content blocks
228
297
  text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text)
229
298
  });
230
299
  break;
231
300
  }
232
- case "ReasoningPart":
301
+ case "reasoning":
233
302
  {
234
- content.push({
235
- reasoningContent: {
236
- reasoningText: {
237
- text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.reasoningText),
238
- signature: part.signature
239
- }
303
+ const options = part.options.bedrock;
304
+ if (Predicate.isNotUndefined(options)) {
305
+ if (options.type === "thinking") {
306
+ content.push({
307
+ reasoningContent: {
308
+ reasoningText: {
309
+ // Amazon Bedrock does not allow trailing whitespace in
310
+ // assistant content blocks
311
+ text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text),
312
+ signature: options.signature
313
+ }
314
+ }
315
+ });
240
316
  }
241
- });
242
- break;
243
- }
244
- case "RedactedReasoningPart":
245
- {
246
- const redactedContent = Encoding.encodeBase64(part.redactedText);
247
- content.push({
248
- reasoningContent: {
249
- redactedContent
317
+ if (options.type === "redacted_thinking") {
318
+ content.push({
319
+ reasoningContent: {
320
+ redactedContent: options.redactedData
321
+ }
322
+ });
250
323
  }
251
- });
324
+ }
252
325
  break;
253
326
  }
254
- case "ToolCallPart":
327
+ case "tool-call":
255
328
  {
256
329
  content.push({
257
330
  toolUse: {
@@ -264,6 +337,9 @@ const makeMessages = /*#__PURE__*/Effect.fnUntraced(function* (method, prompt) {
264
337
  }
265
338
  }
266
339
  }
340
+ if (getCachePoint(message)) {
341
+ content.push(BEDROCK_CACHE_POINT);
342
+ }
267
343
  }
268
344
  messages.push({
269
345
  role: "assistant",
@@ -271,187 +347,515 @@ const makeMessages = /*#__PURE__*/Effect.fnUntraced(function* (method, prompt) {
271
347
  });
272
348
  break;
273
349
  }
274
- case "user":
350
+ }
351
+ }
352
+ return {
353
+ system,
354
+ messages
355
+ };
356
+ });
357
+ // =============================================================================
358
+ // Response Conversion
359
+ // =============================================================================
360
+ const makeResponse = /*#__PURE__*/Effect.fnUntraced(function* (request, response, options) {
361
+ const parts = [];
362
+ parts.push({
363
+ type: "response-metadata",
364
+ modelId: request.modelId,
365
+ timestamp: DateTime.formatIso(yield* DateTime.now)
366
+ });
367
+ for (const part of response.output.message.content) {
368
+ switch (part.type) {
369
+ case "text":
275
370
  {
276
- const content = [];
277
- for (let j = 0; j < group.messages.length; j++) {
278
- const message = group.messages[j];
279
- switch (message._tag) {
280
- case "ToolMessage":
281
- {
282
- for (let k = 0; k < message.parts.length; k++) {
283
- const part = message.parts[k];
284
- // TODO: support advanced tool result content parts
285
- content.push({
286
- toolResult: {
287
- toolUseId: part.id,
288
- content: [{
289
- text: JSON.stringify(part.result)
290
- }]
371
+ // The text parts should only be added to the response here if the
372
+ // response format is `"text"`. If the response format is `"json"`,
373
+ // then the text parts must instead be added to the response when a
374
+ // tool call is received.
375
+ if (options.responseFormat.type === "text") {
376
+ parts.push({
377
+ type: "text",
378
+ text: part.text
379
+ });
380
+ }
381
+ break;
382
+ }
383
+ case "reasoningContent":
384
+ {
385
+ if (part.reasoningContent.type === "reasoning") {
386
+ const signature = part.reasoningContent.reasoningText.signature;
387
+ parts.push({
388
+ type: "reasoning",
389
+ text: part.reasoningContent.reasoningText.text,
390
+ metadata: Predicate.isNotUndefined(signature) ? {
391
+ bedrock: {
392
+ type: "thinking",
393
+ signature
394
+ }
395
+ } : undefined
396
+ });
397
+ }
398
+ if (part.reasoningContent.type === "redacted-reasoning") {
399
+ parts.push({
400
+ type: "reasoning",
401
+ text: "",
402
+ metadata: {
403
+ bedrock: {
404
+ type: "redacted_thinking",
405
+ redactedData: part.reasoningContent.redactedContent
406
+ }
407
+ }
408
+ });
409
+ }
410
+ break;
411
+ }
412
+ case "toolUse":
413
+ {
414
+ // When a `"json"` response format is requested, the JSON that we need
415
+ // will be returned by the tool call injected into the request
416
+ if (options.responseFormat.type === "json") {
417
+ parts.push({
418
+ type: "text",
419
+ text: JSON.stringify(part.toolUse.input)
420
+ });
421
+ } else {
422
+ const providerTool = AnthropicTool.getProviderDefinedToolName(part.toolUse.name);
423
+ const name = Predicate.isNotUndefined(providerTool) ? providerTool : part.toolUse.name;
424
+ const providerName = Predicate.isNotUndefined(providerTool) ? part.toolUse.name : undefined;
425
+ parts.push({
426
+ type: "tool-call",
427
+ id: part.toolUse.toolUseId,
428
+ name,
429
+ params: part.toolUse.input,
430
+ providerName,
431
+ providerExecuted: false
432
+ });
433
+ }
434
+ break;
435
+ }
436
+ }
437
+ }
438
+ const finishReason = InternalUtilities.resolveFinishReason(response.stopReason);
439
+ parts.push({
440
+ type: "finish",
441
+ reason: finishReason,
442
+ usage: {
443
+ inputTokens: response.usage.inputTokens,
444
+ outputTokens: response.usage.outputTokens,
445
+ totalTokens: response.usage.totalTokens,
446
+ cachedInputTokens: response.usage.cacheReadInputTokens
447
+ },
448
+ metadata: {
449
+ bedrock: {
450
+ trace: response.trace,
451
+ usage: {
452
+ cacheWriteInputTokens: response.usage.cacheWriteInputTokens
453
+ }
454
+ }
455
+ }
456
+ });
457
+ return parts;
458
+ });
459
+ const makeStreamResponse = /*#__PURE__*/Effect.fnUntraced(function* (request, stream, options) {
460
+ const contentBlocks = {};
461
+ let trace = undefined;
462
+ let cacheWriteInputTokens = undefined;
463
+ const usage = {
464
+ inputTokens: undefined,
465
+ outputTokens: undefined,
466
+ totalTokens: undefined
467
+ };
468
+ return stream.pipe(Stream.mapEffect(Effect.fnUntraced(function* (event) {
469
+ const parts = [];
470
+ switch (event.type) {
471
+ case "messageStart":
472
+ {
473
+ parts.push({
474
+ type: "response-metadata",
475
+ modelId: request.modelId,
476
+ timestamp: DateTime.formatIso(yield* DateTime.now)
477
+ });
478
+ break;
479
+ }
480
+ case "messageStop":
481
+ {
482
+ const reason = InternalUtilities.resolveFinishReason(event.messageStop.stopReason);
483
+ parts.push({
484
+ type: "finish",
485
+ reason,
486
+ usage,
487
+ metadata: {
488
+ bedrock: {
489
+ trace,
490
+ usage: {
491
+ cacheWriteInputTokens
492
+ }
493
+ }
494
+ }
495
+ });
496
+ break;
497
+ }
498
+ case "contentBlockStart":
499
+ {
500
+ const index = event.contentBlockStart.contentBlockIndex;
501
+ const block = event.contentBlockStart;
502
+ if (Predicate.isNotUndefined(block.start.toolUse)) {
503
+ const toolUse = block.start.toolUse;
504
+ const toolName = toolUse.name;
505
+ const providerTool = AnthropicTool.getProviderDefinedToolName(toolName);
506
+ const name = Predicate.isNotUndefined(providerTool) ? providerTool : toolName;
507
+ const providerName = Predicate.isNotUndefined(providerTool) ? toolName : undefined;
508
+ contentBlocks[index] = {
509
+ type: "tool-call",
510
+ id: toolUse.toolUseId,
511
+ name,
512
+ params: "",
513
+ providerName,
514
+ providerExecuted: false
515
+ };
516
+ // Only emit tool param delta events for text responses
517
+ if (options.responseFormat.type === "text") {
518
+ parts.push({
519
+ type: "tool-params-start",
520
+ id: toolUse.toolUseId,
521
+ name: toolUse.name,
522
+ providerExecuted: false
523
+ });
524
+ }
525
+ } else {
526
+ contentBlocks[index] = {
527
+ type: "text"
528
+ };
529
+ parts.push({
530
+ type: "text-start",
531
+ id: index.toString()
532
+ });
533
+ }
534
+ break;
535
+ }
536
+ case "contentBlockDelta":
537
+ {
538
+ const index = event.contentBlockDelta.contentBlockIndex;
539
+ const delta = event.contentBlockDelta.delta;
540
+ switch (delta.type) {
541
+ case "text":
542
+ {
543
+ const block = contentBlocks[index];
544
+ if (Predicate.isUndefined(block)) {
545
+ contentBlocks[index] = {
546
+ type: "text"
547
+ };
548
+ // Only emit text delta events for text responses
549
+ if (options.responseFormat.type === "text") {
550
+ parts.push({
551
+ type: "text-start",
552
+ id: index.toString()
553
+ });
554
+ }
555
+ }
556
+ // Only emit text delta events for text responses
557
+ if (options.responseFormat.type === "text") {
558
+ parts.push({
559
+ type: "text-delta",
560
+ id: index.toString(),
561
+ delta: delta.text
562
+ });
563
+ }
564
+ break;
565
+ }
566
+ case "reasoningContent":
567
+ {
568
+ if ("text" in delta.reasoningContent) {
569
+ const block = contentBlocks[index];
570
+ if (Predicate.isUndefined(block)) {
571
+ contentBlocks[index] = {
572
+ type: "reasoning"
573
+ };
574
+ parts.push({
575
+ type: "reasoning-start",
576
+ id: index.toString()
577
+ });
578
+ }
579
+ parts.push({
580
+ type: "reasoning-delta",
581
+ id: index.toString(),
582
+ delta: delta.reasoningContent.text
583
+ });
584
+ } else if ("signature" in delta.reasoningContent) {
585
+ parts.push({
586
+ type: "reasoning-delta",
587
+ id: index.toString(),
588
+ delta: "",
589
+ metadata: {
590
+ bedrock: {
591
+ type: "thinking",
592
+ signature: delta.reasoningContent.signature
291
593
  }
594
+ }
595
+ });
596
+ } else {
597
+ parts.push({
598
+ type: "reasoning-delta",
599
+ id: index.toString(),
600
+ delta: "",
601
+ metadata: {
602
+ bedrock: {
603
+ type: "redacted_thinking",
604
+ redactedData: delta.reasoningContent.redactedContent
605
+ }
606
+ }
607
+ });
608
+ }
609
+ break;
610
+ }
611
+ case "toolUse":
612
+ {
613
+ const block = contentBlocks[index];
614
+ if (Predicate.isNotUndefined(block) && block.type === "tool-call") {
615
+ const params = delta.toolUse.input;
616
+ // Only emit tool params delta events for text responses
617
+ if (options.responseFormat.type === "text") {
618
+ parts.push({
619
+ type: "tool-params-delta",
620
+ id: block.id,
621
+ delta: params
622
+ });
623
+ }
624
+ block.params += params;
625
+ }
626
+ break;
627
+ }
628
+ }
629
+ break;
630
+ }
631
+ case "contentBlockStop":
632
+ {
633
+ const index = event.contentBlockStop.contentBlockIndex;
634
+ const block = contentBlocks[index];
635
+ if (Predicate.isNotUndefined(block)) {
636
+ switch (block.type) {
637
+ case "text":
638
+ {
639
+ // Only emit text end events for text responses
640
+ if (options.responseFormat.type === "text") {
641
+ parts.push({
642
+ type: "text-end",
643
+ id: index.toString()
292
644
  });
293
645
  }
294
646
  break;
295
647
  }
296
- case "UserMessage":
648
+ case "reasoning":
297
649
  {
298
- for (let k = 0; k < message.parts.length; k++) {
299
- const part = message.parts[k];
300
- switch (part._tag) {
301
- case "FilePart":
302
- {
303
- if (Predicate.isUndefined(part.mediaType)) {
304
- return yield* new AiError({
305
- module: "AmazonBedrockLanguageModel",
306
- method,
307
- description: "No media type specified for image"
308
- });
309
- }
310
- content.push({
311
- document: {
312
- name: part.name ?? `file-${fileCounter++}`,
313
- format: part.mediaType.split("/")?.[1],
314
- source: {
315
- bytes: Encoding.encodeBase64(part.data)
316
- }
317
- }
318
- });
319
- break;
320
- }
321
- case "FileUrlPart":
322
- {
323
- // TODO: maybe auto-download images from URL
324
- return yield* new AiError({
325
- module: "AmazonBedrockLanguageModel",
326
- method,
327
- description: "File URLs are not supported at this time"
328
- });
329
- }
330
- case "ImagePart":
331
- {
332
- if (Predicate.isUndefined(part.mediaType)) {
333
- return yield* new AiError({
334
- module: "AmazonBedrockLanguageModel",
335
- method,
336
- description: "No media type specified for image"
337
- });
338
- }
339
- content.push({
340
- image: {
341
- format: part.mediaType.split("/")?.[1],
342
- source: {
343
- bytes: Encoding.encodeBase64(part.data)
344
- }
345
- }
346
- });
347
- break;
348
- }
349
- case "ImageUrlPart":
350
- {
351
- // TODO: maybe auto-download images from URL
352
- return yield* new AiError({
353
- module: "AmazonBedrockLanguageModel",
354
- method,
355
- description: "Image URLs are not supported at this time"
356
- });
357
- }
358
- case "TextPart":
359
- {
360
- content.push({
361
- text: part.text
362
- });
363
- break;
364
- }
365
- }
650
+ parts.push({
651
+ type: "reasoning-end",
652
+ id: index.toString()
653
+ });
654
+ break;
655
+ }
656
+ case "tool-call":
657
+ {
658
+ // Only emit tool param events for text responses - for JSON
659
+ // responses, the structured output will be emitted as text
660
+ if (options.responseFormat.type === "text") {
661
+ parts.push({
662
+ type: "tool-params-end",
663
+ id: block.id
664
+ });
665
+ parts.push({
666
+ type: "tool-call",
667
+ id: block.id,
668
+ name: block.name,
669
+ params: JSON.parse(block.params),
670
+ providerName: block.providerName,
671
+ providerExecuted: block.providerExecuted
672
+ });
673
+ } else {
674
+ parts.push({
675
+ type: "text-start",
676
+ id: index.toString()
677
+ });
678
+ parts.push({
679
+ type: "text-delta",
680
+ id: index.toString(),
681
+ delta: block.params
682
+ });
683
+ parts.push({
684
+ type: "text-end",
685
+ id: index.toString()
686
+ });
366
687
  }
367
688
  break;
368
689
  }
369
690
  }
691
+ delete contentBlocks[index];
370
692
  }
371
- messages.push({
372
- role: "user",
373
- content
693
+ break;
694
+ }
695
+ case "metadata":
696
+ {
697
+ usage.inputTokens = event.metadata.usage.inputTokens;
698
+ usage.outputTokens = event.metadata.usage.outputTokens;
699
+ usage.totalTokens = event.metadata.usage.totalTokens;
700
+ usage.cachedInputTokens = event.metadata.usage.cacheReadInputTokens;
701
+ if (Predicate.isNotUndefined(event.metadata.usage.cacheWriteInputTokens)) {
702
+ cacheWriteInputTokens = event.metadata.usage.cacheWriteInputTokens;
703
+ }
704
+ if (Predicate.isNotUndefined(event.metadata.trace)) {
705
+ trace = event.metadata.trace;
706
+ }
707
+ break;
708
+ }
709
+ case "internalServerException":
710
+ {
711
+ parts.push({
712
+ type: "error",
713
+ error: event.internalServerException
714
+ });
715
+ break;
716
+ }
717
+ case "modelStreamErrorException":
718
+ {
719
+ parts.push({
720
+ type: "error",
721
+ error: event.modelStreamErrorException
722
+ });
723
+ break;
724
+ }
725
+ case "serviceUnavailableException":
726
+ {
727
+ parts.push({
728
+ type: "error",
729
+ error: event.serviceUnavailableException
730
+ });
731
+ break;
732
+ }
733
+ case "throttlingException":
734
+ {
735
+ parts.push({
736
+ type: "error",
737
+ error: event.throttlingException
738
+ });
739
+ break;
740
+ }
741
+ case "validationException":
742
+ {
743
+ parts.push({
744
+ type: "error",
745
+ error: event.validationException
374
746
  });
375
747
  break;
376
748
  }
377
749
  }
378
- }
379
- if (Arr.isNonEmptyReadonlyArray(messages)) {
380
- return messages;
381
- }
382
- return yield* new AiError({
383
- module: "AmazonBedrockLanguageModel",
384
- method,
385
- description: "Prompt contained no messages"
386
- });
750
+ return parts;
751
+ })), Stream.flattenIterables);
387
752
  });
388
- const makeResponse = /*#__PURE__*/Effect.fnUntraced(function* (response, modelId) {
389
- const parts = [];
390
- parts.push(new AiResponse.MetadataPart({
391
- model: modelId
392
- }, constDisableValidation));
393
- const finishReason = InternalUtilities.resolveFinishReason(response.stopReason);
394
- const metadata = {
395
- metrics: response.metrics
396
- };
397
- if (Predicate.isNotUndefined(response.trace)) {
398
- metadata.trace = response.trace;
753
+ // =============================================================================
754
+ // Tool Calling
755
+ // =============================================================================
756
+ const prepareTools = /*#__PURE__*/Effect.fnUntraced(function* (options, config) {
757
+ const betas = new Set();
758
+ if (options.tools.length === 0) {
759
+ return {
760
+ toolConfig: {},
761
+ betas
762
+ };
399
763
  }
400
- if (Predicate.isNotUndefined(response.performanceConfig)) {
401
- metadata.performanceConfig = response.performanceConfig;
764
+ const isAnthropicModel = config.modelId.includes("anthropic.");
765
+ const userDefinedTools = [];
766
+ const providerDefinedTools = [];
767
+ for (const tool of options.tools) {
768
+ if (Tool.isUserDefined(tool)) {
769
+ userDefinedTools.push(tool);
770
+ } else {
771
+ providerDefinedTools.push(tool);
772
+ }
402
773
  }
403
- parts.push(new AiResponse.FinishPart({
404
- reason: finishReason,
405
- usage: {
406
- inputTokens: response.usage.inputTokens,
407
- outputTokens: response.usage.outputTokens,
408
- totalTokens: response.usage.totalTokens,
409
- reasoningTokens: 0,
410
- cacheReadInputTokens: response.usage.cacheReadInputTokens ?? 0,
411
- cacheWriteInputTokens: response.usage.cacheWriteInputTokens ?? 0
412
- },
413
- providerMetadata: {
414
- [InternalUtilities.ProviderMetadataKey]: metadata
774
+ const hasAnthropicTools = isAnthropicModel && providerDefinedTools.length > 0;
775
+ let tools = [];
776
+ let additionalTools = undefined;
777
+ // Handle Anthropic provider-defined tools for Anthropic models on Bedrock
778
+ if (hasAnthropicTools) {
779
+ const prepared = yield* prepareAnthropicTools(options, {});
780
+ prepared.betas.forEach(beta => betas.add(beta));
781
+ if (Predicate.isNotUndefined(prepared.toolChoice)) {
782
+ // For Anthropic tools on Bedrock, only the 'tool_choice' goes into
783
+ // the `additionalModelRequestFields` parameter of the request, while
784
+ // the tool definitions themselves are sent in the usual `toolConfig`
785
+ additionalTools = {
786
+ tool_choice: prepared.toolChoice
787
+ };
415
788
  }
416
- }, constDisableValidation));
417
- for (const part of response.output.message.content) {
418
- if ("text" in part) {
419
- parts.push(new AiResponse.TextPart({
420
- text: part.text
421
- }, constDisableValidation));
789
+ // Handle conversion of provider-defined tools to Amazon Bedrock tool definitions
790
+ for (const providerDefinedTool of providerDefinedTools) {
791
+ tools.push({
792
+ toolSpec: {
793
+ name: providerDefinedTool.providerName,
794
+ description: Tool.getDescription(providerDefinedTool),
795
+ inputSchema: {
796
+ json: Tool.getJsonSchema(providerDefinedTool)
797
+ }
798
+ }
799
+ });
422
800
  }
423
- if ("reasoningContent" in part) {
424
- const content = part.reasoningContent;
425
- if ("reasoningText" in content) {
426
- parts.push(new AiResponse.ReasoningPart({
427
- reasoningText: content.reasoningText.text,
428
- signature: content.reasoningText.signature
429
- }, constDisableValidation));
430
- }
431
- if ("redactedContent" in content) {
432
- parts.push(new AiResponse.RedactedReasoningPart({
433
- redactedText: Encoding.encodeBase64(content.redactedContent)
434
- }, constDisableValidation));
801
+ }
802
+ // Handle conversion of user-defined tools to Amazon Bedrock tool definitions
803
+ for (const tool of userDefinedTools) {
804
+ tools.push({
805
+ toolSpec: {
806
+ name: tool.name,
807
+ description: Tool.getDescription(tool),
808
+ inputSchema: {
809
+ json: Tool.getJsonSchema(tool)
810
+ }
435
811
  }
436
- }
437
- if ("toolUse" in part) {
438
- parts.push(AiResponse.ToolCallPart.fromUnknown({
439
- id: part.toolUse.toolUseId,
440
- name: part.toolUse.name,
441
- params: part.toolUse.input
442
- }));
812
+ });
813
+ }
814
+ // Handle resolution of tool choice for **Amazon Bedrock** user-defined tools.
815
+ // The tool choice for Anthropic provider-defined tools is resolved above and
816
+ // inserted into the additional tool configuration object.
817
+ let toolChoice = undefined;
818
+ if (!hasAnthropicTools && tools.length > 0 && Predicate.isNotUndefined(options.toolChoice)) {
819
+ if (options.toolChoice === "none") {
820
+ tools.length = 0;
821
+ toolChoice = undefined;
822
+ } else if (options.toolChoice === "auto") {
823
+ toolChoice = {
824
+ auto: {}
825
+ };
826
+ } else if (options.toolChoice === "required") {
827
+ toolChoice = {
828
+ any: {}
829
+ };
830
+ } else if ("tool" in options.toolChoice) {
831
+ toolChoice = {
832
+ tool: {
833
+ name: options.toolChoice.tool
834
+ }
835
+ };
836
+ } else {
837
+ const allowedTools = new Set(options.toolChoice.oneOf);
838
+ tools = tools.filter(tool => allowedTools.has(tool.toolSpec?.name));
839
+ toolChoice = options.toolChoice.mode === "auto" ? {
840
+ auto: {}
841
+ } : {
842
+ any: {}
843
+ };
443
844
  }
444
845
  }
445
- return new AiResponse.AiResponse({
446
- parts
447
- }, constDisableValidation);
846
+ const toolConfig = tools.length > 0 ? {
847
+ tools,
848
+ toolChoice
849
+ } : {};
850
+ return {
851
+ additionalTools,
852
+ betas,
853
+ toolConfig
854
+ };
448
855
  });
449
- /**
450
- * Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant
451
- * responses, so we trim the final text part here if it's the last message in
452
- * the group.
453
- */
454
- const trimIfLast = (isLastGroup, isLastMessage, isLastPart, text) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text;
856
+ // =============================================================================
857
+ // Telemetry
858
+ // =============================================================================
455
859
  const annotateRequest = (span, request) => {
456
860
  addGenAIAnnotations(span, {
457
861
  system: "anthropic",
@@ -467,10 +871,10 @@ const annotateRequest = (span, request) => {
467
871
  }
468
872
  });
469
873
  };
470
- const annotateChatResponse = (span, modelId, response) => {
874
+ const annotateResponse = (span, request, response) => {
471
875
  addGenAIAnnotations(span, {
472
876
  response: {
473
- model: modelId,
877
+ model: request.modelId,
474
878
  finishReasons: response.stopReason ? [response.stopReason] : undefined
475
879
  },
476
880
  usage: {
@@ -479,19 +883,112 @@ const annotateChatResponse = (span, modelId, response) => {
479
883
  }
480
884
  });
481
885
  };
482
- const annotateStreamResponse = (span, response) => {
483
- const metadataPart = response.parts.find(part => part._tag === "MetadataPart");
484
- const finishPart = response.parts.find(part => part._tag === "FinishPart");
485
- addGenAIAnnotations(span, {
486
- response: {
487
- id: metadataPart?.id,
488
- model: metadataPart?.model,
489
- finishReasons: finishPart?.reason ? [finishPart.reason] : undefined
490
- },
491
- usage: {
492
- inputTokens: finishPart?.usage.inputTokens,
493
- outputTokens: finishPart?.usage.outputTokens
886
+ const annotateStreamResponse = (span, part) => {
887
+ if (part.type === "response-metadata") {
888
+ addGenAIAnnotations(span, {
889
+ response: {
890
+ id: part.id,
891
+ model: part.modelId
892
+ }
893
+ });
894
+ }
895
+ if (part.type === "finish") {
896
+ addGenAIAnnotations(span, {
897
+ response: {
898
+ finishReasons: [part.reason]
899
+ },
900
+ usage: {
901
+ inputTokens: part.usage.inputTokens,
902
+ outputTokens: part.usage.outputTokens
903
+ }
904
+ });
905
+ }
906
+ };
907
+ const groupMessages = prompt => {
908
+ const messages = [];
909
+ let current = undefined;
910
+ for (const message of prompt.content) {
911
+ switch (message.role) {
912
+ case "system":
913
+ {
914
+ if (current?.type !== "system") {
915
+ current = {
916
+ type: "system",
917
+ messages: []
918
+ };
919
+ messages.push(current);
920
+ }
921
+ current.messages.push(message);
922
+ break;
923
+ }
924
+ case "assistant":
925
+ {
926
+ if (current?.type !== "assistant") {
927
+ current = {
928
+ type: "assistant",
929
+ messages: []
930
+ };
931
+ messages.push(current);
932
+ }
933
+ current.messages.push(message);
934
+ break;
935
+ }
936
+ case "tool":
937
+ case "user":
938
+ {
939
+ if (current?.type !== "user") {
940
+ current = {
941
+ type: "user",
942
+ messages: []
943
+ };
944
+ messages.push(current);
945
+ }
946
+ current.messages.push(message);
947
+ break;
948
+ }
494
949
  }
495
- });
950
+ }
951
+ return messages;
496
952
  };
953
+ /**
954
+ * Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant
955
+ * responses, so we trim the final text part here if it's the last message in
956
+ * the group.
957
+ */
958
+ const trimIfLast = (isLastGroup, isLastMessage, isLastPart, text) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text;
959
+ const getCachePoint = part => part.options.bedrock?.cachePoint;
960
+ const convertToBase64 = data => typeof data === "string" ? data : Encoding.encodeBase64(data);
961
+ const DOCUMENT_MIME_TYPES = {
962
+ "application/pdf": "pdf",
963
+ "text/csv": "csv",
964
+ "application/msword": "doc",
965
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
966
+ "application/vnd.ms-excel": "xls",
967
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
968
+ "text/html": "html",
969
+ "text/plain": "txt",
970
+ "text/markdown": "md"
971
+ };
972
+ const getDocumentFormat = /*#__PURE__*/Effect.fnUntraced(function* (mediaType) {
973
+ const format = DOCUMENT_MIME_TYPES[mediaType];
974
+ if (Predicate.isUndefined(format)) {
975
+ return yield* new AiError.MalformedInput({
976
+ module: "AmazonBedrockLanguageModel",
977
+ method: "getDocumentFormat",
978
+ description: `Unsupported document MIME type: ${mediaType} - expected ` + `one of: ${Object.keys(DOCUMENT_MIME_TYPES)}`
979
+ });
980
+ }
981
+ return format;
982
+ });
983
+ const getImageFormat = /*#__PURE__*/Effect.fnUntraced(function* (mediaType) {
984
+ const format = ImageFormat.literals.find(format => mediaType === `image/${format}`);
985
+ if (Predicate.isUndefined(format)) {
986
+ return yield* new AiError.MalformedInput({
987
+ module: "AmazonBedrockLanguageModel",
988
+ method: "getImageFormat",
989
+ description: `Unsupported image MIME type: ${mediaType} - expected ` + `one of: ${ImageFormat.literals.map(format => `image/${format}`).join(",")}`
990
+ });
991
+ }
992
+ return format;
993
+ });
497
994
  //# sourceMappingURL=AmazonBedrockLanguageModel.js.map