@effect/ai-amazon-bedrock 0.6.2 → 0.7.1

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 +844 -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 +841 -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 +978 -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,19 +1,22 @@
1
1
  /**
2
2
  * @since 1.0.0
3
3
  */
4
- import { AiError } from "@effect/ai/AiError"
5
- import type * as AiInput from "@effect/ai/AiInput"
6
- import * as AiLanguageModel from "@effect/ai/AiLanguageModel"
7
- import * as AiModel from "@effect/ai/AiModel"
8
- import * as AiResponse from "@effect/ai/AiResponse"
9
- import { addGenAIAnnotations } from "@effect/ai/AiTelemetry"
10
- 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 type * as IdGenerator from "@effect/ai/IdGenerator"
8
+ import * as LanguageModel from "@effect/ai/LanguageModel"
9
+ import * as AiModel from "@effect/ai/Model"
10
+ import type * as Prompt from "@effect/ai/Prompt"
11
+ import type * as Response from "@effect/ai/Response"
12
+ import { addGenAIAnnotations } from "@effect/ai/Telemetry"
13
+ import * as Tool from "@effect/ai/Tool"
11
14
  import * as Context from "effect/Context"
15
+ import * as DateTime from "effect/DateTime"
12
16
  import * as Effect from "effect/Effect"
13
17
  import * as Encoding from "effect/Encoding"
14
- import { dual, identity } from "effect/Function"
18
+ import { dual } from "effect/Function"
15
19
  import * as Layer from "effect/Layer"
16
- import * as Option from "effect/Option"
17
20
  import * as Predicate from "effect/Predicate"
18
21
  import * as Stream from "effect/Stream"
19
22
  import type { Span } from "effect/Tracer"
@@ -21,20 +24,25 @@ import type { Mutable, Simplify } from "effect/Types"
21
24
  import { AmazonBedrockClient } from "./AmazonBedrockClient.js"
22
25
  import type {
23
26
  BedrockFoundationModelId,
27
+ CachePointBlock,
24
28
  ContentBlock,
25
- ConverseMetrics,
26
29
  ConverseRequest,
27
30
  ConverseResponse,
31
+ ConverseResponseStreamEvent,
28
32
  ConverseTrace,
29
33
  DocumentFormat,
30
- ImageFormat,
31
34
  Message,
32
- PerformanceConfiguration,
35
+ SystemContentBlock,
36
+ Tool as AmazonBedrockTool,
37
+ ToolChoice,
33
38
  ToolConfiguration
34
39
  } from "./AmazonBedrockSchema.js"
40
+ import { ImageFormat } from "./AmazonBedrockSchema.js"
35
41
  import * as InternalUtilities from "./internal/utilities.js"
36
42
 
37
- const constDisableValidation = { disableValidation: true }
43
+ const BEDROCK_CACHE_POINT: {
44
+ readonly cachePoint: typeof CachePointBlock.Encoded
45
+ } = { cachePoint: { type: "default" } }
38
46
 
39
47
  /**
40
48
  * @since 1.0.0
@@ -83,30 +91,87 @@ export declare namespace Config {
83
91
  }
84
92
 
85
93
  // =============================================================================
86
- // Amazon Bedrock Provider Metadata
94
+ // Amazon Bedrock Provider Options / Metadata
87
95
  // =============================================================================
88
96
 
89
97
  /**
90
98
  * @since 1.0.0
91
- * @category Context
99
+ * @category Provider Options
92
100
  */
93
- export class ProviderMetadata extends Context.Tag(InternalUtilities.ProviderMetadataKey)<
94
- ProviderMetadata,
95
- ProviderMetadata.Service
96
- >() {}
97
-
98
- /**
99
- * @since 1.0.0
100
- */
101
- export declare namespace ProviderMetadata {
101
+ export type AmazonBedrockReasoningInfo = {
102
+ readonly type: "thinking"
102
103
  /**
103
- * @since 1.0.0
104
- * @category Provider Metadata
104
+ * Thinking content as an encrypted string, which is used to verify
105
+ * that thinking content was indeed generated by Amazon Bedrock's API.
106
+ */
107
+ readonly signature: string
108
+ } | {
109
+ readonly type: "redacted_thinking"
110
+ /**
111
+ * Thinking content which was flagged by Amazon Bedrock's safety systems, and
112
+ * was therefore encrypted.
105
113
  */
106
- export interface Service {
107
- readonly metrics: ConverseMetrics
108
- readonly trace?: ConverseTrace
109
- readonly performanceConfig?: PerformanceConfiguration
114
+ readonly redactedData: string
115
+ }
116
+
117
+ declare module "@effect/ai/Prompt" {
118
+ export interface SystemMessageOptions extends ProviderOptions {
119
+ readonly bedrock?: {
120
+ /**
121
+ * Defines a section of content to be cached for reuse in subsequent API
122
+ * calls.
123
+ */
124
+ readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
125
+ } | undefined
126
+ }
127
+
128
+ export interface UserMessageOptions extends ProviderOptions {
129
+ readonly bedrock?: {
130
+ /**
131
+ * Defines a section of content to be cached for reuse in subsequent API
132
+ * calls.
133
+ */
134
+ readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
135
+ } | undefined
136
+ }
137
+
138
+ export interface AssistantMessageOptions extends ProviderOptions {
139
+ readonly bedrock?: {
140
+ /**
141
+ * Defines a section of content to be cached for reuse in subsequent API
142
+ * calls.
143
+ */
144
+ readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
145
+ } | undefined
146
+ }
147
+
148
+ export interface ToolMessageOptions extends ProviderOptions {
149
+ readonly bedrock?: {
150
+ /**
151
+ * Defines a section of content to be cached for reuse in subsequent API
152
+ * calls.
153
+ */
154
+ readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
155
+ } | undefined
156
+ }
157
+
158
+ export interface ReasoningPartOptions extends ProviderOptions {
159
+ readonly bedrock?: AmazonBedrockReasoningInfo | undefined
160
+ }
161
+ }
162
+
163
+ declare module "@effect/ai/Response" {
164
+ export interface ReasoningPartMetadata extends ProviderMetadata {
165
+ readonly bedrock?: AmazonBedrockReasoningInfo | undefined
166
+ }
167
+
168
+ export interface FinishPartMetadata extends ProviderMetadata {
169
+ readonly bedrock?: {
170
+ readonly trace?: ConverseTrace | undefined
171
+ readonly usage: {
172
+ readonly cacheWriteInputTokens?: number | undefined
173
+ }
174
+ } | undefined
110
175
  }
111
176
  }
112
177
 
@@ -121,7 +186,8 @@ export declare namespace ProviderMetadata {
121
186
  export const model = (
122
187
  model: (string & {}) | Model,
123
188
  config?: Omit<Config.Service, "model">
124
- ): AiModel.AiModel<AiLanguageModel.AiLanguageModel, AmazonBedrockClient> => AiModel.make(layer({ model, config }))
189
+ ): AiModel.Model<"amazon-bedrock", LanguageModel.LanguageModel, AmazonBedrockClient> =>
190
+ AiModel.make("amazon-bedrock", layer({ model, config }))
125
191
 
126
192
  /**
127
193
  * @since 1.0.0
@@ -133,101 +199,86 @@ export const make = Effect.fnUntraced(function*(options: {
133
199
  }) {
134
200
  const client = yield* AmazonBedrockClient
135
201
 
136
- const makeToolConfig = (options: {
137
- readonly toolChoice: AiLanguageModel.AiLanguageModelOptions["toolChoice"]
138
- readonly tools: AiLanguageModel.AiLanguageModelOptions["tools"]
139
- }): typeof ToolConfiguration.Encoded | undefined => {
140
- if (options.tools.length === 0) return undefined
141
- const isStructured = options.tools.length === 1 && options.tools[0].structured
142
- const tools = options.tools.map((tool) => ({
143
- toolSpec: {
144
- name: tool.name,
145
- description: tool.description,
146
- inputSchema: { json: tool.parameters }
147
- }
148
- }))
149
- const toolConfig: Mutable<typeof ToolConfiguration.Encoded> = { tools } as any
150
- if (isStructured) {
151
- toolConfig.toolChoice = { tool: { name: options.tools[0].name } }
152
- return toolConfig
153
- }
154
- if (options.toolChoice === "auto") {
155
- toolConfig.toolChoice = { auto: {} }
156
- } else if (options.toolChoice === "none") {
157
- toolConfig.toolChoice = undefined
158
- } else if (options.toolChoice === "required") {
159
- toolConfig.toolChoice = { any: {} }
160
- } else {
161
- toolConfig.toolChoice = { tool: { name: options.toolChoice.tool } }
162
- }
163
- return toolConfig
164
- }
165
-
166
202
  const makeRequest = Effect.fnUntraced(
167
- function*(method: string, { prompt, system, ...rest }: AiLanguageModel.AiLanguageModelOptions) {
203
+ function*(providerOptions: LanguageModel.ProviderOptions) {
168
204
  const context = yield* Effect.context<never>()
169
- const messages = yield* makeMessages(method, prompt)
170
- const toolConfig = makeToolConfig(rest)
171
- return identity<typeof ConverseRequest.Encoded>({
172
- modelId: options.model,
173
- ...options.config,
174
- ...context.unsafeMap.get(Config.key),
175
- // TODO: re-evaluate a better way to do this
176
- system: system.pipe(
177
- Option.map((text) => [{ text }]),
178
- Option.getOrUndefined
179
- ),
205
+ const config = { modelId: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }
206
+ const { messages, system } = yield* prepareMessages(providerOptions)
207
+ const { additionalTools, betas, toolConfig } = yield* prepareTools(providerOptions, config)
208
+ const responseFormat = providerOptions.responseFormat
209
+ const request: typeof ConverseRequest.Encoded = {
210
+ ...config,
211
+ system,
180
212
  messages,
181
- toolConfig
182
- })
213
+ // Handle tool configuration
214
+ ...(responseFormat.type === "json"
215
+ ? {
216
+ toolConfig: {
217
+ tools: [{
218
+ toolSpec: {
219
+ name: responseFormat.objectName,
220
+ description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ??
221
+ "Respond with a JSON object",
222
+ inputSchema: {
223
+ json: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast) as any
224
+ }
225
+ }
226
+ }],
227
+ toolChoice: { tool: { name: responseFormat.objectName } }
228
+ }
229
+ }
230
+ : Predicate.isNotUndefined(toolConfig.tools) && toolConfig.tools.length > 0
231
+ ? { toolConfig }
232
+ : {}),
233
+ // Handle additional model request fields
234
+ ...(Predicate.isNotUndefined(additionalTools)
235
+ ? {
236
+ additionalModelRequestFields: {
237
+ ...config.additionalModelRequestFields,
238
+ ...additionalTools
239
+ }
240
+ }
241
+ : {})
242
+ }
243
+ return { betas, request }
183
244
  }
184
245
  )
185
246
 
186
- return yield* AiLanguageModel.make({
247
+ return yield* LanguageModel.make({
187
248
  generateText: Effect.fnUntraced(
188
- function*(_options) {
189
- const request = yield* makeRequest("generateText", _options)
190
- annotateRequest(_options.span, request)
191
- const rawResponse = yield* client.client.converse(request)
192
- const context = yield* Effect.context<never>()
193
- const model = Option.match(Context.getOption(context, Config), {
194
- onNone: () => options.model,
195
- onSome: ({ modelId }) => modelId ?? options.model
249
+ function*(options) {
250
+ const { betas, request } = yield* makeRequest(options)
251
+ annotateRequest(options.span, request)
252
+ const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined
253
+ const rawResponse = yield* client.converse({
254
+ params: { "anthropic-beta": anthropicBeta },
255
+ payload: request
196
256
  })
197
- annotateChatResponse(_options.span, model, rawResponse)
198
- const response = yield* makeResponse(rawResponse, model)
199
- return response
200
- },
201
- Effect.catchAll((cause) =>
202
- AiError.is(cause) ? cause : new AiError({
203
- module: "AmazonBedrockLanguageModel",
204
- method: "generateText",
205
- description: "An error occurred",
206
- cause
207
- })
208
- )
257
+ annotateResponse(options.span, request, rawResponse)
258
+ return yield* makeResponse(request, rawResponse, options)
259
+ }
209
260
  ),
210
- streamText(_options) {
211
- return makeRequest("streamText", _options).pipe(
212
- Effect.tap((request) => annotateRequest(_options.span, request)),
213
- Effect.map(client.stream),
214
- Stream.unwrap,
215
- Stream.map((response) => {
216
- annotateStreamResponse(_options.span, response)
217
- return response
218
- }),
219
- Stream.catchAll((cause) =>
220
- AiError.is(cause) ? Effect.fail(cause) : Effect.fail(
221
- new AiError({
222
- module: "AmazonBedrockLanguageModel",
223
- method: "streamText",
224
- description: "An error occurred",
225
- cause
226
- })
227
- )
261
+ streamText: Effect.fnUntraced(
262
+ function*(options) {
263
+ const { betas, request } = yield* makeRequest(options)
264
+ annotateRequest(options.span, request)
265
+ const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined
266
+ const stream = client.converseStream({
267
+ params: { "anthropic-beta": anthropicBeta },
268
+ payload: request
269
+ })
270
+ return { request, stream }
271
+ },
272
+ (effect, options) =>
273
+ effect.pipe(
274
+ Effect.flatMap(({ request, stream }) => makeStreamResponse(request, stream, options)),
275
+ Stream.unwrap,
276
+ Stream.map((response) => {
277
+ annotateStreamResponse(options.span, response)
278
+ return response
279
+ })
228
280
  )
229
- )
230
- }
281
+ )
231
282
  })
232
283
  })
233
284
 
@@ -238,8 +289,8 @@ export const make = Effect.fnUntraced(function*(options: {
238
289
  export const layer = (options: {
239
290
  readonly model: (string & {}) | Model
240
291
  readonly config?: Omit<Config.Service, "model">
241
- }): Layer.Layer<AiLanguageModel.AiLanguageModel, never, AmazonBedrockClient> =>
242
- Layer.effect(AiLanguageModel.AiLanguageModel, make({ model: options.model, config: options.config }))
292
+ }): Layer.Layer<LanguageModel.LanguageModel, never, AmazonBedrockClient> =>
293
+ Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))
243
294
 
244
295
  /**
245
296
  * @since 1.0.0
@@ -274,303 +325,726 @@ export const withConfigOverride: {
274
325
  ))
275
326
 
276
327
  // =============================================================================
277
- // Utilities
328
+ // Prompt Conversion
278
329
  // =============================================================================
279
330
 
280
- type MessageGroup = AssistantMessageGroup | UserMessageGroup
281
-
282
- interface AssistantMessageGroup {
283
- readonly type: "assistant"
284
- readonly messages: Array<AiInput.AssistantMessage>
285
- }
286
-
287
- interface UserMessageGroup {
288
- readonly type: "user"
289
- readonly messages: Array<AiInput.ToolMessage | AiInput.UserMessage>
290
- }
331
+ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<{
332
+ readonly system: ReadonlyArray<typeof SystemContentBlock.Encoded>
333
+ readonly messages: ReadonlyArray<typeof Message.Encoded>
334
+ }, AiError.AiError> = Effect.fnUntraced(
335
+ function*(options) {
336
+ const groups = groupMessages(options.prompt)
291
337
 
292
- const groupMessages = (prompt: AiInput.AiInput): Array<MessageGroup> => {
293
- const messages: Array<MessageGroup> = []
294
- let current: MessageGroup | undefined = undefined
295
- for (const message of prompt.messages) {
296
- switch (message._tag) {
297
- case "AssistantMessage": {
298
- if (current?.type !== "assistant") {
299
- current = { type: "assistant", messages: [] }
300
- messages.push(current)
301
- }
302
- current.messages.push(message)
303
- break
304
- }
305
- case "ToolMessage":
306
- case "UserMessage": {
307
- if (current?.type !== "user") {
308
- current = { type: "user", messages: [] }
309
- messages.push(current)
310
- }
311
- current.messages.push(message)
312
- break
313
- }
314
- }
315
- }
316
- return messages
317
- }
338
+ const system: Array<typeof SystemContentBlock.Encoded> = []
339
+ const messages: Array<typeof Message.Encoded> = []
318
340
 
319
- let fileCounter = 0
341
+ let documentCounter = 0
342
+ const nextDocumentName = () => `document-${++documentCounter}`
320
343
 
321
- const makeMessages = Effect.fnUntraced(
322
- function*(method: string, prompt: AiInput.AiInput) {
323
- const messages: Array<typeof Message.Encoded> = []
324
- const groups = groupMessages(prompt)
325
344
  for (let i = 0; i < groups.length; i++) {
326
345
  const group = groups[i]
327
346
  const isLastGroup = i === groups.length - 1
347
+
328
348
  switch (group.type) {
329
- case "assistant": {
349
+ case "system": {
350
+ if (messages.length > 0) {
351
+ return yield* new AiError.MalformedInput({
352
+ module: "AmazonBedrockLanguageModel",
353
+ method: "prepareMessages",
354
+ description: "Multiple system messages separated by user / assistant messages"
355
+ })
356
+ }
357
+ for (const message of group.messages) {
358
+ system.push({ text: message.content })
359
+ if (Predicate.isNotUndefined(getCachePoint(message))) {
360
+ system.push(BEDROCK_CACHE_POINT)
361
+ }
362
+ }
363
+ break
364
+ }
365
+
366
+ case "user": {
330
367
  const content: Array<typeof ContentBlock.Encoded> = []
331
- for (let j = 0; j < group.messages.length; j++) {
332
- const message = group.messages[j]
333
- const isLastMessage = j === group.messages.length - 1
334
- for (let k = 0; k < message.parts.length; k++) {
335
- const part = message.parts[k]
336
- const isLastPart = k === message.parts.length - 1
337
- switch (part._tag) {
338
- case "TextPart": {
339
- content.push({
340
- text: trimIfLast(
341
- isLastGroup,
342
- isLastMessage,
343
- isLastPart,
344
- part.text
345
- )
346
- })
347
- break
348
- }
349
- case "ReasoningPart": {
350
- content.push({
351
- reasoningContent: {
352
- reasoningText: {
353
- text: trimIfLast(
354
- isLastGroup,
355
- isLastMessage,
356
- isLastPart,
357
- part.reasoningText
358
- ),
359
- signature: part.signature
368
+
369
+ for (const message of group.messages) {
370
+ switch (message.role) {
371
+ case "user": {
372
+ for (let j = 0; j < message.content.length; j++) {
373
+ const part = message.content[j]
374
+
375
+ switch (part.type) {
376
+ case "text": {
377
+ content.push({ text: part.text })
378
+ break
379
+ }
380
+
381
+ case "file": {
382
+ if (part.data instanceof URL) {
383
+ // TODO(Max): support this
384
+ return yield* new AiError.MalformedInput({
385
+ module: "AmazonBedrockLanguageModel",
386
+ method: "makeMessages",
387
+ description: "File URL inputs are not supported at this time"
388
+ })
389
+ }
390
+ if (part.mediaType.startsWith("image/")) {
391
+ content.push({
392
+ image: {
393
+ format: yield* getImageFormat(part.mediaType),
394
+ source: { bytes: convertToBase64(part.data) }
395
+ }
396
+ })
397
+ } else {
398
+ content.push({
399
+ document: {
400
+ format: yield* getDocumentFormat(part.mediaType),
401
+ name: nextDocumentName(),
402
+ source: { bytes: convertToBase64(part.data) }
403
+ }
404
+ })
360
405
  }
406
+ break
361
407
  }
362
- })
363
- break
364
- }
365
- case "RedactedReasoningPart": {
366
- const redactedContent = Encoding.encodeBase64(part.redactedText)
367
- content.push({ reasoningContent: { redactedContent } })
368
- break
408
+ }
369
409
  }
370
- case "ToolCallPart": {
410
+ break
411
+ }
412
+
413
+ case "tool": {
414
+ for (const part of message.content) {
371
415
  content.push({
372
- toolUse: {
416
+ toolResult: {
373
417
  toolUseId: part.id,
374
- name: part.name,
375
- input: part.params
418
+ content: [{ text: JSON.stringify(part.result) }]
376
419
  }
377
420
  })
378
- break
379
421
  }
422
+ break
380
423
  }
381
424
  }
382
425
  }
383
- messages.push({ role: "assistant", content })
426
+
427
+ messages.push({ role: "user", content })
428
+
384
429
  break
385
430
  }
386
- case "user": {
431
+
432
+ case "assistant": {
387
433
  const content: Array<typeof ContentBlock.Encoded> = []
434
+
388
435
  for (let j = 0; j < group.messages.length; j++) {
389
436
  const message = group.messages[j]
390
- switch (message._tag) {
391
- case "ToolMessage": {
392
- for (let k = 0; k < message.parts.length; k++) {
393
- const part = message.parts[k]
394
- // TODO: support advanced tool result content parts
437
+ const isLastMessage = j === group.messages.length - 1
438
+
439
+ for (let k = 0; k < message.content.length; k++) {
440
+ const part = message.content[k]
441
+ const isLastPart = k === message.content.length - 1
442
+
443
+ switch (part.type) {
444
+ case "text": {
445
+ // Skip empty text blocks
446
+ if (part.text.trim().length === 0) {
447
+ break
448
+ }
395
449
  content.push({
396
- toolResult: {
397
- toolUseId: part.id,
398
- content: [{ text: JSON.stringify(part.result) }]
399
- }
450
+ // Amazon Bedrock does not allow trailing whitespace in
451
+ // assistant content blocks
452
+ text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text)
400
453
  })
454
+ break
401
455
  }
402
- break
403
- }
404
- case "UserMessage": {
405
- for (let k = 0; k < message.parts.length; k++) {
406
- const part = message.parts[k]
407
- switch (part._tag) {
408
- case "FilePart": {
409
- if (Predicate.isUndefined(part.mediaType)) {
410
- return yield* new AiError({
411
- module: "AmazonBedrockLanguageModel",
412
- method,
413
- description: "No media type specified for image"
414
- })
415
- }
456
+
457
+ case "reasoning": {
458
+ const options = part.options.bedrock
459
+ if (Predicate.isNotUndefined(options)) {
460
+ if (options.type === "thinking") {
416
461
  content.push({
417
- document: {
418
- name: part.name ?? `file-${fileCounter++}`,
419
- format: part.mediaType.split("/")?.[1] as DocumentFormat,
420
- source: {
421
- bytes: Encoding.encodeBase64(part.data)
462
+ reasoningContent: {
463
+ reasoningText: {
464
+ // Amazon Bedrock does not allow trailing whitespace in
465
+ // assistant content blocks
466
+ text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text),
467
+ signature: options.signature
422
468
  }
423
469
  }
424
470
  })
425
- break
426
471
  }
427
- case "FileUrlPart": {
428
- // TODO: maybe auto-download images from URL
429
- return yield* new AiError({
430
- module: "AmazonBedrockLanguageModel",
431
- method,
432
- description: "File URLs are not supported at this time"
433
- })
434
- }
435
- case "ImagePart": {
436
- if (Predicate.isUndefined(part.mediaType)) {
437
- return yield* new AiError({
438
- module: "AmazonBedrockLanguageModel",
439
- method,
440
- description: "No media type specified for image"
441
- })
442
- }
472
+ if (options.type === "redacted_thinking") {
443
473
  content.push({
444
- image: {
445
- format: part.mediaType.split("/")?.[1] as ImageFormat,
446
- source: {
447
- bytes: Encoding.encodeBase64(part.data)
448
- }
474
+ reasoningContent: {
475
+ redactedContent: options.redactedData
449
476
  }
450
477
  })
451
- break
452
- }
453
- case "ImageUrlPart": {
454
- // TODO: maybe auto-download images from URL
455
- return yield* new AiError({
456
- module: "AmazonBedrockLanguageModel",
457
- method,
458
- description: "Image URLs are not supported at this time"
459
- })
460
- }
461
- case "TextPart": {
462
- content.push({
463
- text: part.text
464
- })
465
- break
466
478
  }
467
479
  }
480
+ break
481
+ }
482
+
483
+ case "tool-call": {
484
+ content.push({
485
+ toolUse: {
486
+ toolUseId: part.id,
487
+ name: part.name,
488
+ input: part.params
489
+ }
490
+ })
491
+ break
468
492
  }
469
- break
470
493
  }
471
494
  }
495
+
496
+ if (getCachePoint(message)) {
497
+ content.push(BEDROCK_CACHE_POINT)
498
+ }
472
499
  }
473
- messages.push({ role: "user", content })
500
+
501
+ messages.push({ role: "assistant", content })
502
+
474
503
  break
475
504
  }
476
505
  }
477
506
  }
478
- if (Arr.isNonEmptyReadonlyArray(messages)) {
479
- return messages
480
- }
481
- return yield* new AiError({
482
- module: "AmazonBedrockLanguageModel",
483
- method,
484
- description: "Prompt contained no messages"
485
- })
507
+
508
+ return { system, messages }
486
509
  }
487
510
  )
488
511
 
489
- const makeResponse = Effect.fnUntraced(
490
- function*(response: ConverseResponse, modelId: string) {
491
- const parts: Array<AiResponse.Part> = []
492
- parts.push(
493
- new AiResponse.MetadataPart({
494
- model: modelId
495
- }, constDisableValidation)
496
- )
497
- const finishReason = InternalUtilities.resolveFinishReason(response.stopReason)
498
- const metadata: Mutable<ProviderMetadata.Service> = {
499
- metrics: response.metrics
500
- }
501
- if (Predicate.isNotUndefined(response.trace)) {
502
- metadata.trace = response.trace
503
- }
504
- if (Predicate.isNotUndefined(response.performanceConfig)) {
505
- metadata.performanceConfig = response.performanceConfig
506
- }
507
- parts.push(
508
- new AiResponse.FinishPart({
509
- reason: finishReason,
510
- usage: {
511
- inputTokens: response.usage.inputTokens,
512
- outputTokens: response.usage.outputTokens,
513
- totalTokens: response.usage.totalTokens,
514
- reasoningTokens: 0,
515
- cacheReadInputTokens: response.usage.cacheReadInputTokens ?? 0,
516
- cacheWriteInputTokens: response.usage.cacheWriteInputTokens ?? 0
517
- },
518
- providerMetadata: { [InternalUtilities.ProviderMetadataKey]: metadata }
519
- }, constDisableValidation)
520
- )
521
- for (const part of response.output.message.content) {
522
- if ("text" in part) {
523
- parts.push(
524
- new AiResponse.TextPart({
512
+ // =============================================================================
513
+ // Response Conversion
514
+ // =============================================================================
515
+
516
+ const makeResponse: (
517
+ request: typeof ConverseRequest.Encoded,
518
+ response: ConverseResponse,
519
+ options: LanguageModel.ProviderOptions
520
+ ) => Effect.Effect<
521
+ Array<Response.PartEncoded>,
522
+ never,
523
+ IdGenerator.IdGenerator
524
+ > = Effect.fnUntraced(function*(request, response, options) {
525
+ const parts: Array<Response.PartEncoded> = []
526
+
527
+ parts.push({
528
+ type: "response-metadata",
529
+ modelId: request.modelId,
530
+ timestamp: DateTime.formatIso(yield* DateTime.now)
531
+ })
532
+
533
+ for (const part of response.output.message.content) {
534
+ switch (part.type) {
535
+ case "text": {
536
+ // The text parts should only be added to the response here if the
537
+ // response format is `"text"`. If the response format is `"json"`,
538
+ // then the text parts must instead be added to the response when a
539
+ // tool call is received.
540
+ if (options.responseFormat.type === "text") {
541
+ parts.push({
542
+ type: "text",
525
543
  text: part.text
526
- }, constDisableValidation)
527
- )
544
+ })
545
+ }
546
+ break
528
547
  }
529
- if ("reasoningContent" in part) {
530
- const content = part.reasoningContent
531
- if ("reasoningText" in content) {
532
- parts.push(
533
- new AiResponse.ReasoningPart({
534
- reasoningText: content.reasoningText.text,
535
- signature: content.reasoningText.signature
536
- }, constDisableValidation)
537
- )
548
+
549
+ case "reasoningContent": {
550
+ if (part.reasoningContent.type === "reasoning") {
551
+ const signature = part.reasoningContent.reasoningText.signature
552
+ parts.push({
553
+ type: "reasoning",
554
+ text: part.reasoningContent.reasoningText.text,
555
+ metadata: Predicate.isNotUndefined(signature) ?
556
+ { bedrock: { type: "thinking", signature } }
557
+ : undefined
558
+ })
538
559
  }
539
- if ("redactedContent" in content) {
540
- parts.push(
541
- new AiResponse.RedactedReasoningPart({
542
- redactedText: Encoding.encodeBase64(content.redactedContent)
543
- }, constDisableValidation)
544
- )
560
+ if (part.reasoningContent.type === "redacted-reasoning") {
561
+ parts.push({
562
+ type: "reasoning",
563
+ text: "",
564
+ metadata: {
565
+ bedrock: {
566
+ type: "redacted_thinking",
567
+ redactedData: part.reasoningContent.redactedContent
568
+ }
569
+ }
570
+ })
545
571
  }
572
+ break
546
573
  }
547
- if ("toolUse" in part) {
548
- parts.push(
549
- AiResponse.ToolCallPart.fromUnknown({
574
+
575
+ case "toolUse": {
576
+ // When a `"json"` response format is requested, the JSON that we need
577
+ // will be returned by the tool call injected into the request
578
+ if (options.responseFormat.type === "json") {
579
+ parts.push({
580
+ type: "text",
581
+ text: JSON.stringify(part.toolUse.input)
582
+ })
583
+ } else {
584
+ const providerTool = AnthropicTool.getProviderDefinedToolName(part.toolUse.name)
585
+ const name = Predicate.isNotUndefined(providerTool) ? providerTool : part.toolUse.name
586
+ const providerName = Predicate.isNotUndefined(providerTool) ? part.toolUse.name : undefined
587
+ parts.push({
588
+ type: "tool-call",
550
589
  id: part.toolUse.toolUseId,
551
- name: part.toolUse.name,
552
- params: part.toolUse.input
590
+ name,
591
+ params: part.toolUse.input,
592
+ providerName,
593
+ providerExecuted: false
553
594
  })
554
- )
595
+ }
596
+ break
597
+ }
598
+ }
599
+ }
600
+
601
+ const finishReason = InternalUtilities.resolveFinishReason(response.stopReason)
602
+
603
+ parts.push({
604
+ type: "finish",
605
+ reason: finishReason,
606
+ usage: {
607
+ inputTokens: response.usage.inputTokens,
608
+ outputTokens: response.usage.outputTokens,
609
+ totalTokens: response.usage.totalTokens,
610
+ cachedInputTokens: response.usage.cacheReadInputTokens
611
+ },
612
+ metadata: {
613
+ bedrock: {
614
+ trace: response.trace,
615
+ usage: { cacheWriteInputTokens: response.usage.cacheWriteInputTokens }
616
+ }
617
+ }
618
+ })
619
+
620
+ return parts
621
+ })
622
+
623
+ const makeStreamResponse: (
624
+ request: typeof ConverseRequest.Encoded,
625
+ stream: Stream.Stream<ConverseResponseStreamEvent, AiError.AiError>,
626
+ options: LanguageModel.ProviderOptions
627
+ ) => Effect.Effect<
628
+ Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,
629
+ never,
630
+ IdGenerator.IdGenerator
631
+ > = Effect.fnUntraced(
632
+ function*(request, stream, options) {
633
+ const contentBlocks: Record<
634
+ number,
635
+ | {
636
+ readonly type: "text"
637
+ }
638
+ | {
639
+ readonly type: "reasoning"
640
+ }
641
+ | {
642
+ readonly type: "tool-call"
643
+ readonly id: string
644
+ readonly name: string
645
+ params: string
646
+ readonly providerName?: string | undefined
647
+ readonly providerExecuted: boolean
555
648
  }
649
+ > = {}
650
+
651
+ let trace: ConverseTrace | undefined = undefined
652
+ let cacheWriteInputTokens: number | undefined = undefined
653
+ const usage: Mutable<typeof Response.Usage.Encoded> = {
654
+ inputTokens: undefined,
655
+ outputTokens: undefined,
656
+ totalTokens: undefined
556
657
  }
557
- return new AiResponse.AiResponse({
558
- parts
559
- }, constDisableValidation)
658
+
659
+ return stream.pipe(
660
+ Stream.mapEffect(Effect.fnUntraced(function*(event) {
661
+ const parts: Array<Response.StreamPartEncoded> = []
662
+
663
+ switch (event.type) {
664
+ case "messageStart": {
665
+ parts.push({
666
+ type: "response-metadata",
667
+ modelId: request.modelId,
668
+ timestamp: DateTime.formatIso(yield* DateTime.now)
669
+ })
670
+ break
671
+ }
672
+
673
+ case "messageStop": {
674
+ const reason = InternalUtilities.resolveFinishReason(event.messageStop.stopReason)
675
+ parts.push({
676
+ type: "finish",
677
+ reason,
678
+ usage,
679
+ metadata: {
680
+ bedrock: { trace, usage: { cacheWriteInputTokens } }
681
+ }
682
+ })
683
+
684
+ break
685
+ }
686
+
687
+ case "contentBlockStart": {
688
+ const index = event.contentBlockStart.contentBlockIndex
689
+ const block = event.contentBlockStart
690
+ if (Predicate.isNotUndefined(block.start.toolUse)) {
691
+ const toolUse = block.start.toolUse
692
+ const toolName = toolUse.name
693
+ const providerTool = AnthropicTool.getProviderDefinedToolName(toolName)
694
+ const name = Predicate.isNotUndefined(providerTool) ? providerTool : toolName
695
+ const providerName = Predicate.isNotUndefined(providerTool) ? toolName : undefined
696
+
697
+ contentBlocks[index] = {
698
+ type: "tool-call",
699
+ id: toolUse.toolUseId,
700
+ name,
701
+ params: "",
702
+ providerName,
703
+ providerExecuted: false
704
+ }
705
+ // Only emit tool param delta events for text responses
706
+ if (options.responseFormat.type === "text") {
707
+ parts.push({
708
+ type: "tool-params-start",
709
+ id: toolUse.toolUseId,
710
+ name: toolUse.name,
711
+ providerExecuted: false
712
+ })
713
+ }
714
+ } else {
715
+ contentBlocks[index] = { type: "text" }
716
+ parts.push({
717
+ type: "text-start",
718
+ id: index.toString()
719
+ })
720
+ }
721
+ break
722
+ }
723
+
724
+ case "contentBlockDelta": {
725
+ const index = event.contentBlockDelta.contentBlockIndex
726
+ const delta = event.contentBlockDelta.delta
727
+
728
+ switch (delta.type) {
729
+ case "text": {
730
+ const block = contentBlocks[index]
731
+ if (Predicate.isUndefined(block)) {
732
+ contentBlocks[index] = { type: "text" }
733
+ // Only emit text delta events for text responses
734
+ if (options.responseFormat.type === "text") {
735
+ parts.push({
736
+ type: "text-start",
737
+ id: index.toString()
738
+ })
739
+ }
740
+ }
741
+ // Only emit text delta events for text responses
742
+ if (options.responseFormat.type === "text") {
743
+ parts.push({
744
+ type: "text-delta",
745
+ id: index.toString(),
746
+ delta: delta.text
747
+ })
748
+ }
749
+ break
750
+ }
751
+
752
+ case "reasoningContent": {
753
+ if ("text" in delta.reasoningContent) {
754
+ const block = contentBlocks[index]
755
+ if (Predicate.isUndefined(block)) {
756
+ contentBlocks[index] = { type: "reasoning" }
757
+ parts.push({
758
+ type: "reasoning-start",
759
+ id: index.toString()
760
+ })
761
+ }
762
+ parts.push({
763
+ type: "reasoning-delta",
764
+ id: index.toString(),
765
+ delta: delta.reasoningContent.text
766
+ })
767
+ } else if ("signature" in delta.reasoningContent) {
768
+ parts.push({
769
+ type: "reasoning-delta",
770
+ id: index.toString(),
771
+ delta: "",
772
+ metadata: {
773
+ bedrock: {
774
+ type: "thinking",
775
+ signature: delta.reasoningContent.signature
776
+ }
777
+ }
778
+ })
779
+ } else {
780
+ parts.push({
781
+ type: "reasoning-delta",
782
+ id: index.toString(),
783
+ delta: "",
784
+ metadata: {
785
+ bedrock: {
786
+ type: "redacted_thinking",
787
+ redactedData: delta.reasoningContent.redactedContent
788
+ }
789
+ }
790
+ })
791
+ }
792
+ break
793
+ }
794
+
795
+ case "toolUse": {
796
+ const block = contentBlocks[index]
797
+ if (Predicate.isNotUndefined(block) && block.type === "tool-call") {
798
+ const params = delta.toolUse.input
799
+ // Only emit tool params delta events for text responses
800
+ if (options.responseFormat.type === "text") {
801
+ parts.push({
802
+ type: "tool-params-delta",
803
+ id: block.id,
804
+ delta: params
805
+ })
806
+ }
807
+ block.params += params
808
+ }
809
+ break
810
+ }
811
+ }
812
+ break
813
+ }
814
+
815
+ case "contentBlockStop": {
816
+ const index = event.contentBlockStop.contentBlockIndex
817
+ const block = contentBlocks[index]
818
+ if (Predicate.isNotUndefined(block)) {
819
+ switch (block.type) {
820
+ case "text": {
821
+ // Only emit text end events for text responses
822
+ if (options.responseFormat.type === "text") {
823
+ parts.push({
824
+ type: "text-end",
825
+ id: index.toString()
826
+ })
827
+ }
828
+ break
829
+ }
830
+
831
+ case "reasoning": {
832
+ parts.push({
833
+ type: "reasoning-end",
834
+ id: index.toString()
835
+ })
836
+ break
837
+ }
838
+
839
+ case "tool-call": {
840
+ // Only emit tool param events for text responses - for JSON
841
+ // responses, the structured output will be emitted as text
842
+ if (options.responseFormat.type === "text") {
843
+ parts.push({
844
+ type: "tool-params-end",
845
+ id: block.id
846
+ })
847
+
848
+ const toolName = block.name
849
+ const toolParams = block.params
850
+
851
+ const params = yield* Effect.try({
852
+ try: () => Tool.unsafeSecureJsonParse(toolParams),
853
+ catch: (cause) =>
854
+ new AiError.MalformedOutput({
855
+ module: "AmazonBedrockLanguageModel",
856
+ method: "makeStreamResponse",
857
+ description: "Failed to securely parse tool call parameters " +
858
+ `for tool '${toolName}':\nParameters: ${toolParams}`,
859
+ cause
860
+ })
861
+ })
862
+
863
+ parts.push({
864
+ type: "tool-call",
865
+ id: block.id,
866
+ name: toolName,
867
+ params,
868
+ providerName: block.providerName,
869
+ providerExecuted: block.providerExecuted
870
+ })
871
+ } else {
872
+ parts.push({
873
+ type: "text-start",
874
+ id: index.toString()
875
+ })
876
+ parts.push({
877
+ type: "text-delta",
878
+ id: index.toString(),
879
+ delta: block.params
880
+ })
881
+ parts.push({
882
+ type: "text-end",
883
+ id: index.toString()
884
+ })
885
+ }
886
+ break
887
+ }
888
+ }
889
+ delete contentBlocks[index]
890
+ }
891
+ break
892
+ }
893
+
894
+ case "metadata": {
895
+ usage.inputTokens = event.metadata.usage.inputTokens
896
+ usage.outputTokens = event.metadata.usage.outputTokens
897
+ usage.totalTokens = event.metadata.usage.totalTokens
898
+ usage.cachedInputTokens = event.metadata.usage.cacheReadInputTokens
899
+ if (Predicate.isNotUndefined(event.metadata.usage.cacheWriteInputTokens)) {
900
+ cacheWriteInputTokens = event.metadata.usage.cacheWriteInputTokens
901
+ }
902
+ if (Predicate.isNotUndefined(event.metadata.trace)) {
903
+ trace = event.metadata.trace
904
+ }
905
+ break
906
+ }
907
+
908
+ case "internalServerException": {
909
+ parts.push({ type: "error", error: event.internalServerException })
910
+ break
911
+ }
912
+
913
+ case "modelStreamErrorException": {
914
+ parts.push({ type: "error", error: event.modelStreamErrorException })
915
+ break
916
+ }
917
+
918
+ case "serviceUnavailableException": {
919
+ parts.push({ type: "error", error: event.serviceUnavailableException })
920
+ break
921
+ }
922
+
923
+ case "throttlingException": {
924
+ parts.push({ type: "error", error: event.throttlingException })
925
+ break
926
+ }
927
+
928
+ case "validationException": {
929
+ parts.push({ type: "error", error: event.validationException })
930
+ break
931
+ }
932
+ }
933
+
934
+ return parts
935
+ })),
936
+ Stream.flattenIterables
937
+ )
560
938
  }
561
939
  )
562
940
 
563
- /**
564
- * Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant
565
- * responses, so we trim the final text part here if it's the last message in
566
- * the group.
567
- */
568
- const trimIfLast = (
569
- isLastGroup: boolean,
570
- isLastMessage: boolean,
571
- isLastPart: boolean,
572
- text: string
573
- ) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text
941
+ // =============================================================================
942
+ // Tool Calling
943
+ // =============================================================================
944
+
945
+ const prepareTools: (
946
+ options: LanguageModel.ProviderOptions,
947
+ config: Config.Service
948
+ ) => Effect.Effect<{
949
+ readonly betas: ReadonlySet<string>
950
+ readonly toolConfig: Partial<typeof ToolConfiguration.Encoded>
951
+ readonly additionalTools?: Record<string, unknown> | undefined
952
+ }, AiError.AiError> = Effect.fnUntraced(function*(options, config) {
953
+ const betas = new Set<string>()
954
+
955
+ if (options.tools.length === 0) {
956
+ return { toolConfig: {}, betas }
957
+ }
958
+
959
+ const isAnthropicModel = config.modelId!.includes("anthropic.")
960
+ const userDefinedTools: Array<Tool.Any> = []
961
+ const providerDefinedTools: Array<Tool.AnyProviderDefined> = []
962
+ for (const tool of options.tools) {
963
+ if (Tool.isUserDefined(tool)) {
964
+ userDefinedTools.push(tool)
965
+ } else {
966
+ providerDefinedTools.push(tool as Tool.AnyProviderDefined)
967
+ }
968
+ }
969
+
970
+ const hasAnthropicTools = isAnthropicModel && providerDefinedTools.length > 0
971
+
972
+ let tools: Array<typeof AmazonBedrockTool.Encoded> = []
973
+ let additionalTools: Record<string, unknown> | undefined = undefined
974
+
975
+ // Handle Anthropic provider-defined tools for Anthropic models on Bedrock
976
+ if (hasAnthropicTools) {
977
+ const prepared = yield* prepareAnthropicTools(options, {})
978
+
979
+ prepared.betas.forEach((beta) => betas.add(beta))
980
+
981
+ if (Predicate.isNotUndefined(prepared.toolChoice)) {
982
+ // For Anthropic tools on Bedrock, only the 'tool_choice' goes into
983
+ // the `additionalModelRequestFields` parameter of the request, while
984
+ // the tool definitions themselves are sent in the usual `toolConfig`
985
+ additionalTools = {
986
+ tool_choice: prepared.toolChoice
987
+ }
988
+ }
989
+
990
+ // Handle conversion of provider-defined tools to Amazon Bedrock tool definitions
991
+ for (const providerDefinedTool of providerDefinedTools) {
992
+ tools.push({
993
+ toolSpec: {
994
+ name: providerDefinedTool.providerName,
995
+ description: Tool.getDescription(providerDefinedTool as any),
996
+ inputSchema: {
997
+ json: Tool.getJsonSchema(providerDefinedTool as any) as any
998
+ }
999
+ }
1000
+ })
1001
+ }
1002
+ }
1003
+
1004
+ // Handle conversion of user-defined tools to Amazon Bedrock tool definitions
1005
+ for (const tool of userDefinedTools) {
1006
+ tools.push({
1007
+ toolSpec: {
1008
+ name: tool.name,
1009
+ description: Tool.getDescription(tool as any),
1010
+ inputSchema: {
1011
+ json: Tool.getJsonSchema(tool as any) as any
1012
+ }
1013
+ }
1014
+ })
1015
+ }
1016
+
1017
+ // Handle resolution of tool choice for **Amazon Bedrock** user-defined tools.
1018
+ // The tool choice for Anthropic provider-defined tools is resolved above and
1019
+ // inserted into the additional tool configuration object.
1020
+ let toolChoice: typeof ToolChoice.Encoded | undefined = undefined
1021
+ if (!hasAnthropicTools && tools.length > 0 && Predicate.isNotUndefined(options.toolChoice)) {
1022
+ if (options.toolChoice === "none") {
1023
+ tools.length = 0
1024
+ toolChoice = undefined
1025
+ } else if (options.toolChoice === "auto") {
1026
+ toolChoice = { auto: {} }
1027
+ } else if (options.toolChoice === "required") {
1028
+ toolChoice = { any: {} }
1029
+ } else if ("tool" in options.toolChoice) {
1030
+ toolChoice = { tool: { name: options.toolChoice.tool } }
1031
+ } else {
1032
+ const allowedTools = new Set(options.toolChoice.oneOf)
1033
+ tools = tools.filter((tool) => allowedTools.has(tool.toolSpec?.name))
1034
+ toolChoice = options.toolChoice.mode === "auto" ? { auto: {} } : { any: {} }
1035
+ }
1036
+ }
1037
+
1038
+ const toolConfig: Partial<typeof ToolConfiguration.Encoded> = tools.length > 0
1039
+ ? { tools, toolChoice }
1040
+ : {}
1041
+
1042
+ return { additionalTools, betas, toolConfig }
1043
+ })
1044
+
1045
+ // =============================================================================
1046
+ // Telemetry
1047
+ // =============================================================================
574
1048
 
575
1049
  const annotateRequest = (
576
1050
  span: Span,
@@ -589,14 +1063,14 @@ const annotateRequest = (
589
1063
  })
590
1064
  }
591
1065
 
592
- const annotateChatResponse = (
1066
+ const annotateResponse = (
593
1067
  span: Span,
594
- modelId: string,
1068
+ request: typeof ConverseRequest.Encoded,
595
1069
  response: ConverseResponse
596
1070
  ): void => {
597
1071
  addGenAIAnnotations(span, {
598
1072
  response: {
599
- model: modelId,
1073
+ model: request.modelId,
600
1074
  finishReasons: response.stopReason ? [response.stopReason] : undefined
601
1075
  },
602
1076
  usage: {
@@ -606,21 +1080,153 @@ const annotateChatResponse = (
606
1080
  })
607
1081
  }
608
1082
 
609
- const annotateStreamResponse = (
610
- span: Span,
611
- response: AiResponse.AiResponse
612
- ) => {
613
- const metadataPart = response.parts.find((part) => part._tag === "MetadataPart")
614
- const finishPart = response.parts.find((part) => part._tag === "FinishPart")
615
- addGenAIAnnotations(span, {
616
- response: {
617
- id: metadataPart?.id,
618
- model: metadataPart?.model,
619
- finishReasons: finishPart?.reason ? [finishPart.reason] : undefined
620
- },
621
- usage: {
622
- inputTokens: finishPart?.usage.inputTokens,
623
- outputTokens: finishPart?.usage.outputTokens
1083
+ const annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {
1084
+ if (part.type === "response-metadata") {
1085
+ addGenAIAnnotations(span, {
1086
+ response: {
1087
+ id: part.id,
1088
+ model: part.modelId
1089
+ }
1090
+ })
1091
+ }
1092
+ if (part.type === "finish") {
1093
+ addGenAIAnnotations(span, {
1094
+ response: {
1095
+ finishReasons: [part.reason]
1096
+ },
1097
+ usage: {
1098
+ inputTokens: part.usage.inputTokens,
1099
+ outputTokens: part.usage.outputTokens
1100
+ }
1101
+ })
1102
+ }
1103
+ }
1104
+
1105
+ // =============================================================================
1106
+ // Utilities
1107
+ // =============================================================================
1108
+
1109
+ type ContentGroup = SystemMessageGroup | AssistantMessageGroup | UserMessageGroup
1110
+
1111
+ interface SystemMessageGroup {
1112
+ readonly type: "system"
1113
+ readonly messages: Array<Prompt.SystemMessage>
1114
+ }
1115
+
1116
+ interface AssistantMessageGroup {
1117
+ readonly type: "assistant"
1118
+ readonly messages: Array<Prompt.AssistantMessage>
1119
+ }
1120
+
1121
+ interface UserMessageGroup {
1122
+ readonly type: "user"
1123
+ readonly messages: Array<Prompt.ToolMessage | Prompt.UserMessage>
1124
+ }
1125
+
1126
+ const groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {
1127
+ const messages: Array<ContentGroup> = []
1128
+ let current: ContentGroup | undefined = undefined
1129
+ for (const message of prompt.content) {
1130
+ switch (message.role) {
1131
+ case "system": {
1132
+ if (current?.type !== "system") {
1133
+ current = { type: "system", messages: [] }
1134
+ messages.push(current)
1135
+ }
1136
+ current.messages.push(message)
1137
+ break
1138
+ }
1139
+ case "assistant": {
1140
+ if (current?.type !== "assistant") {
1141
+ current = { type: "assistant", messages: [] }
1142
+ messages.push(current)
1143
+ }
1144
+ current.messages.push(message)
1145
+ break
1146
+ }
1147
+ case "tool":
1148
+ case "user": {
1149
+ if (current?.type !== "user") {
1150
+ current = { type: "user", messages: [] }
1151
+ messages.push(current)
1152
+ }
1153
+ current.messages.push(message)
1154
+ break
1155
+ }
624
1156
  }
625
- })
1157
+ }
1158
+ return messages
626
1159
  }
1160
+
1161
+ /**
1162
+ * Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant
1163
+ * responses, so we trim the final text part here if it's the last message in
1164
+ * the group.
1165
+ */
1166
+ const trimIfLast = (
1167
+ isLastGroup: boolean,
1168
+ isLastMessage: boolean,
1169
+ isLastPart: boolean,
1170
+ text: string
1171
+ ) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text
1172
+
1173
+ const getCachePoint = (
1174
+ part:
1175
+ | Prompt.SystemMessage
1176
+ | Prompt.UserMessage
1177
+ | Prompt.AssistantMessage
1178
+ | Prompt.ToolMessage
1179
+ ): typeof CachePointBlock.Encoded | undefined => part.options.bedrock?.cachePoint
1180
+
1181
+ const convertToBase64 = (data: string | Uint8Array): string =>
1182
+ typeof data === "string" ? data : Encoding.encodeBase64(data)
1183
+
1184
+ const DOCUMENT_MIME_TYPES: Record<string, typeof DocumentFormat.Encoded> = {
1185
+ "application/pdf": "pdf",
1186
+ "text/csv": "csv",
1187
+ "application/msword": "doc",
1188
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
1189
+ "application/vnd.ms-excel": "xls",
1190
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
1191
+ "text/html": "html",
1192
+ "text/plain": "txt",
1193
+ "text/markdown": "md"
1194
+ }
1195
+
1196
+ const getDocumentFormat: (
1197
+ mediaType: string
1198
+ ) => Effect.Effect<typeof DocumentFormat.Encoded, AiError.AiError> = Effect.fnUntraced(
1199
+ function*(mediaType) {
1200
+ const format = DOCUMENT_MIME_TYPES[mediaType]
1201
+
1202
+ if (Predicate.isUndefined(format)) {
1203
+ return yield* new AiError.MalformedInput({
1204
+ module: "AmazonBedrockLanguageModel",
1205
+ method: "getDocumentFormat",
1206
+ description: `Unsupported document MIME type: ${mediaType} - expected ` +
1207
+ `one of: ${Object.keys(DOCUMENT_MIME_TYPES)}`
1208
+ })
1209
+ }
1210
+
1211
+ return format
1212
+ }
1213
+ )
1214
+
1215
+ const getImageFormat: (
1216
+ mediaType: string
1217
+ ) => Effect.Effect<typeof ImageFormat.Encoded, AiError.AiError> = Effect.fnUntraced(
1218
+ function*(mediaType) {
1219
+ const format = ImageFormat.literals.find((format) => mediaType === `image/${format}`)
1220
+
1221
+ if (Predicate.isUndefined(format)) {
1222
+ return yield* new AiError.MalformedInput({
1223
+ module: "AmazonBedrockLanguageModel",
1224
+ method: "getImageFormat",
1225
+ description: `Unsupported image MIME type: ${mediaType} - expected ` +
1226
+ `one of: ${ImageFormat.literals.map((format) => `image/${format}`).join(",")}`
1227
+ })
1228
+ }
1229
+
1230
+ return format
1231
+ }
1232
+ )