@effect/ai-amazon-bedrock 0.17.0 → 4.1.4

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 (186) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/README.md +76 -3
  4. package/ai-docs/README.md +44 -0
  5. package/ai-docs/package.json +36 -0
  6. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  7. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  8. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  9. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  10. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  11. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  12. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  13. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  14. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  16. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  17. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  18. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  19. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  20. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  21. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  22. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  23. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  24. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  25. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  26. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  27. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  28. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  29. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  30. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  31. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  32. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  33. package/ai-docs/src/03_stream/index.md +4 -0
  34. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  35. package/ai-docs/src/04_integration/index.md +5 -0
  36. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  37. package/ai-docs/src/05_batching/index.md +3 -0
  38. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  39. package/ai-docs/src/06_schedule/index.md +3 -0
  40. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  41. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  42. package/ai-docs/src/07_datetime/index.md +5 -0
  43. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  44. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  45. package/ai-docs/src/08_observability/index.md +7 -0
  46. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  47. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  48. package/ai-docs/src/09_testing/index.md +1 -0
  49. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  50. package/ai-docs/src/10_predicate/index.md +9 -0
  51. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  52. package/ai-docs/src/40_sql/index.md +6 -0
  53. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  54. package/ai-docs/src/50_http-client/index.md +3 -0
  55. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  56. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  57. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  61. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  63. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  66. package/ai-docs/src/51_http-server/index.md +3 -0
  67. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  68. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  69. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  70. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  71. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  72. package/ai-docs/src/52_graphql/index.md +6 -0
  73. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  74. package/ai-docs/src/60_child-process/index.md +3 -0
  75. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  76. package/ai-docs/src/70_cli/index.md +5 -0
  77. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  78. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  79. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  80. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  81. package/ai-docs/src/71_ai/index.md +5 -0
  82. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  83. package/ai-docs/src/80_cluster/index.md +4 -0
  84. package/ai-docs/src/index.md +10 -0
  85. package/ai-docs/tsconfig.json +28 -0
  86. package/dist/AmazonBedrockClient.d.ts +227 -0
  87. package/dist/AmazonBedrockClient.d.ts.map +1 -0
  88. package/dist/AmazonBedrockClient.js +281 -0
  89. package/dist/AmazonBedrockClient.js.map +1 -0
  90. package/dist/AmazonBedrockConfig.d.ts +76 -0
  91. package/dist/AmazonBedrockConfig.d.ts.map +1 -0
  92. package/dist/AmazonBedrockConfig.js +41 -0
  93. package/dist/AmazonBedrockConfig.js.map +1 -0
  94. package/dist/AmazonBedrockLanguageModel.d.ts +315 -0
  95. package/dist/AmazonBedrockLanguageModel.d.ts.map +1 -0
  96. package/dist/AmazonBedrockLanguageModel.js +991 -0
  97. package/dist/AmazonBedrockLanguageModel.js.map +1 -0
  98. package/dist/AmazonBedrockSchema.d.ts +918 -0
  99. package/dist/AmazonBedrockSchema.d.ts.map +1 -0
  100. package/dist/AmazonBedrockSchema.js +536 -0
  101. package/dist/AmazonBedrockSchema.js.map +1 -0
  102. package/dist/index.d.ts +25 -0
  103. package/dist/index.d.ts.map +1 -0
  104. package/dist/{esm/index.js → index.js} +13 -12
  105. package/dist/index.js.map +1 -0
  106. package/dist/internal/errors.d.ts +2 -0
  107. package/dist/internal/errors.d.ts.map +1 -0
  108. package/dist/internal/errors.js +185 -0
  109. package/dist/internal/errors.js.map +1 -0
  110. package/dist/internal/eventStream.d.ts +2 -0
  111. package/dist/internal/eventStream.d.ts.map +1 -0
  112. package/dist/internal/eventStream.js +180 -0
  113. package/dist/internal/eventStream.js.map +1 -0
  114. package/dist/internal/sigv4.d.ts +2 -0
  115. package/dist/internal/sigv4.d.ts.map +1 -0
  116. package/dist/internal/sigv4.js +115 -0
  117. package/dist/internal/sigv4.js.map +1 -0
  118. package/dist/{dts/internal → internal}/utilities.d.ts.map +1 -1
  119. package/dist/internal/utilities.js +17 -0
  120. package/dist/internal/utilities.js.map +1 -0
  121. package/package.json +45 -84
  122. package/src/AmazonBedrockClient.ts +447 -263
  123. package/src/AmazonBedrockConfig.ts +55 -40
  124. package/src/AmazonBedrockLanguageModel.ts +950 -929
  125. package/src/AmazonBedrockSchema.ts +526 -970
  126. package/src/index.ts +15 -14
  127. package/src/internal/errors.ts +207 -0
  128. package/src/internal/eventStream.ts +208 -0
  129. package/src/internal/sigv4.ts +154 -0
  130. package/src/internal/utilities.ts +15 -17
  131. package/AmazonBedrockClient/package.json +0 -6
  132. package/AmazonBedrockConfig/package.json +0 -6
  133. package/AmazonBedrockLanguageModel/package.json +0 -6
  134. package/AmazonBedrockSchema/package.json +0 -6
  135. package/AmazonBedrockTool/package.json +0 -6
  136. package/EventStreamEncoding/package.json +0 -6
  137. package/dist/cjs/AmazonBedrockClient.js +0 -191
  138. package/dist/cjs/AmazonBedrockClient.js.map +0 -1
  139. package/dist/cjs/AmazonBedrockConfig.js +0 -30
  140. package/dist/cjs/AmazonBedrockConfig.js.map +0 -1
  141. package/dist/cjs/AmazonBedrockLanguageModel.js +0 -1051
  142. package/dist/cjs/AmazonBedrockLanguageModel.js.map +0 -1
  143. package/dist/cjs/AmazonBedrockSchema.js +0 -800
  144. package/dist/cjs/AmazonBedrockSchema.js.map +0 -1
  145. package/dist/cjs/AmazonBedrockTool.js +0 -53
  146. package/dist/cjs/AmazonBedrockTool.js.map +0 -1
  147. package/dist/cjs/EventStreamEncoding.js +0 -86
  148. package/dist/cjs/EventStreamEncoding.js.map +0 -1
  149. package/dist/cjs/index.js +0 -20
  150. package/dist/cjs/index.js.map +0 -1
  151. package/dist/cjs/internal/utilities.js +0 -27
  152. package/dist/cjs/internal/utilities.js.map +0 -1
  153. package/dist/dts/AmazonBedrockClient.d.ts +0 -95
  154. package/dist/dts/AmazonBedrockClient.d.ts.map +0 -1
  155. package/dist/dts/AmazonBedrockConfig.d.ts +0 -47
  156. package/dist/dts/AmazonBedrockConfig.d.ts.map +0 -1
  157. package/dist/dts/AmazonBedrockLanguageModel.d.ts +0 -147
  158. package/dist/dts/AmazonBedrockLanguageModel.d.ts.map +0 -1
  159. package/dist/dts/AmazonBedrockSchema.d.ts +0 -1875
  160. package/dist/dts/AmazonBedrockSchema.d.ts.map +0 -1
  161. package/dist/dts/AmazonBedrockTool.d.ts +0 -206
  162. package/dist/dts/AmazonBedrockTool.d.ts.map +0 -1
  163. package/dist/dts/EventStreamEncoding.d.ts +0 -16
  164. package/dist/dts/EventStreamEncoding.d.ts.map +0 -1
  165. package/dist/dts/index.d.ts +0 -25
  166. package/dist/dts/index.d.ts.map +0 -1
  167. package/dist/esm/AmazonBedrockClient.js +0 -179
  168. package/dist/esm/AmazonBedrockClient.js.map +0 -1
  169. package/dist/esm/AmazonBedrockConfig.js +0 -22
  170. package/dist/esm/AmazonBedrockConfig.js.map +0 -1
  171. package/dist/esm/AmazonBedrockLanguageModel.js +0 -1040
  172. package/dist/esm/AmazonBedrockLanguageModel.js.map +0 -1
  173. package/dist/esm/AmazonBedrockSchema.js +0 -731
  174. package/dist/esm/AmazonBedrockSchema.js.map +0 -1
  175. package/dist/esm/AmazonBedrockTool.js +0 -45
  176. package/dist/esm/AmazonBedrockTool.js.map +0 -1
  177. package/dist/esm/EventStreamEncoding.js +0 -78
  178. package/dist/esm/EventStreamEncoding.js.map +0 -1
  179. package/dist/esm/index.js.map +0 -1
  180. package/dist/esm/internal/utilities.js +0 -19
  181. package/dist/esm/internal/utilities.js.map +0 -1
  182. package/dist/esm/package.json +0 -4
  183. package/index/package.json +0 -6
  184. package/src/AmazonBedrockTool.ts +0 -273
  185. package/src/EventStreamEncoding.ts +0 -118
  186. /package/dist/{dts/internal → internal}/utilities.d.ts +0 -0
@@ -1,351 +1,647 @@
1
1
  /**
2
- * @since 1.0.0
2
+ * The `AmazonBedrockLanguageModel` module maps the Effect AI `LanguageModel`
3
+ * abstraction onto the Amazon Bedrock Converse API.
4
+ *
5
+ * **Scope**
6
+ *
7
+ * Text, tool calling and tool results are supported on both the streaming and
8
+ * the non-streaming path. Structured output asks for the object through a
9
+ * forced tool by default, and through Converse's native
10
+ * `outputConfig.textFormat` when `Config.structuredOutputs` is `true`.
11
+ * Reasoning blocks are surfaced on both paths and round-trip into later turns
12
+ * with their signature. Image and document file parts become Converse `image`
13
+ * and `document` blocks; a media type Converse has no format for fails with
14
+ * `AiError.InvalidUserInputError`. Prompt caching is opt-in per message or
15
+ * part via the `"amazon-bedrock"` provider options.
16
+ *
17
+ * @stability unstable
18
+ * @since 4.0.0
3
19
  */
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"
20
+ import * as AiError from "effect/ai/AiError"
21
+ import { toCodecAnthropic } from "effect/ai/AnthropicStructuredOutput"
22
+ import * as LanguageModel from "effect/ai/LanguageModel"
23
+ import * as AiModel from "effect/ai/Model"
24
+ import type * as Prompt from "effect/ai/Prompt"
25
+ import type * as Response from "effect/ai/Response"
26
+ import { addGenAIAnnotations } from "effect/ai/Telemetry"
27
+ import * as Tool from "effect/ai/Tool"
28
+ import * as Bytes from "effect/Bytes"
14
29
  import * as Context from "effect/Context"
15
30
  import * as DateTime from "effect/DateTime"
16
31
  import * as Effect from "effect/Effect"
17
- import * as Encoding from "effect/Encoding"
32
+ import * as Base64 from "effect/encoding/Base64"
18
33
  import { dual } from "effect/Function"
19
34
  import * as Layer from "effect/Layer"
20
35
  import * as Predicate from "effect/Predicate"
36
+ import * as Result from "effect/Result"
37
+ import * as Schema from "effect/Schema"
38
+ import * as SchemaAST from "effect/SchemaAST"
21
39
  import * as Stream from "effect/Stream"
22
40
  import type { Span } from "effect/Tracer"
23
- import type { Mutable, Simplify } from "effect/Types"
24
- import { AmazonBedrockClient } from "./AmazonBedrockClient.js"
41
+ import type { Simplify } from "effect/Types"
42
+ import { AmazonBedrockClient } from "./AmazonBedrockClient.ts"
25
43
  import type {
26
- BedrockFoundationModelId,
27
44
  CachePointBlock,
28
45
  ContentBlock,
29
46
  ConverseRequest,
30
47
  ConverseResponse,
31
- ConverseResponseStreamEvent,
32
- ConverseTrace,
33
- DocumentFormat,
48
+ ConverseStreamEvent,
49
+ DocumentBlock,
50
+ ImageBlock,
34
51
  Message,
52
+ OutputConfig,
35
53
  SystemContentBlock,
36
- Tool as AmazonBedrockTool,
54
+ TokenUsage,
55
+ Tool as BedrockTool,
37
56
  ToolChoice,
38
- ToolConfiguration
39
- } from "./AmazonBedrockSchema.js"
40
- import { ImageFormat } from "./AmazonBedrockSchema.js"
41
- import * as InternalUtilities from "./internal/utilities.js"
42
-
43
- const BEDROCK_CACHE_POINT: {
44
- readonly cachePoint: typeof CachePointBlock.Encoded
45
- } = { cachePoint: { type: "default" } }
57
+ ToolConfiguration,
58
+ ToolResultContentBlock
59
+ } from "./AmazonBedrockSchema.ts"
60
+ import * as InternalUtilities from "./internal/utilities.ts"
46
61
 
47
62
  /**
48
- * @since 1.0.0
49
- * @category Models
63
+ * A Bedrock model identifier, cross-region inference profile id or ARN, such
64
+ * as `us.anthropic.claude-sonnet-4-5-20250929-v1:0`.
65
+ *
66
+ * @stability unstable
67
+ * @category models
68
+ * @since 4.0.0
50
69
  */
51
- export type Model = typeof BedrockFoundationModelId.Encoded
70
+ export type Model = string
52
71
 
53
72
  // =============================================================================
54
- // Configuration
73
+ // Provider Options
55
74
  // =============================================================================
56
75
 
57
76
  /**
58
- * @since 1.0.0
59
- * @category Context
77
+ * A request to cache everything preceding a message or part.
78
+ *
79
+ * **Details**
80
+ *
81
+ * Converse caches a prefix of the request rather than an individual block, so
82
+ * this becomes a `cachePoint` block appended after the content it covers.
83
+ * Omitting `ttl` leaves the cache lifetime to Bedrock.
84
+ *
85
+ * @stability unstable
86
+ * @category models
87
+ * @since 4.0.0
60
88
  */
61
- export class Config extends Context.Tag(
62
- "@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/Config"
63
- )<Config, Config.Service>() {
64
- /**
65
- * @since 1.0.0
66
- */
67
- static readonly getOrUndefined: Effect.Effect<typeof Config.Service | undefined> = Effect.map(
68
- Effect.context<never>(),
69
- (context) => context.unsafeMap.get(Config.key)
70
- )
89
+ export type CachePoint = typeof CachePointBlock.Encoded
90
+
91
+ /**
92
+ * The provider options through which a cache point is requested.
93
+ */
94
+ interface CachePointOptions {
95
+ readonly "amazon-bedrock"?: {
96
+ /**
97
+ * Marks the end of the reusable prefix of the request. The cache point is
98
+ * emitted after the content this is attached to.
99
+ */
100
+ readonly cachePoint?: CachePoint | null
101
+ } | null
71
102
  }
72
103
 
73
104
  /**
74
- * @since 1.0.0
105
+ * The Bedrock-side identity of a reasoning block.
106
+ *
107
+ * **Details**
108
+ *
109
+ * Converse returns reasoning either as text plus a `signature` that proves the
110
+ * model produced it, or as `redactedContent` (base64) when the model
111
+ * provider's safety systems encrypted it. Either must be echoed back
112
+ * unmodified for the block to be accepted in a later turn, so it is carried
113
+ * on the part's provider metadata and options.
114
+ *
115
+ * @stability unstable
116
+ * @category models
117
+ * @since 4.0.0
75
118
  */
76
- export declare namespace Config {
119
+ export type ReasoningInfo = {
120
+ /** The signature verifying that the model generated the reasoning text. */
121
+ readonly signature?: string
122
+ /** Reasoning encrypted by the model provider, as a base64 string. */
123
+ readonly redactedContent?: string
124
+ }
125
+
126
+ declare module "effect/ai/Prompt" {
77
127
  /**
78
- * @since 1.0.0
79
- * @category Configuration
128
+ * Amazon Bedrock options for system messages.
129
+ *
130
+ * @stability unstable
131
+ * @category models
132
+ * @since 4.0.0
80
133
  */
81
- export interface Service extends
82
- Simplify<
83
- Partial<
84
- Omit<
85
- typeof ConverseRequest.Encoded,
86
- "messages" | "system" | "toolConfig"
87
- >
88
- >
89
- >
90
- {}
91
- }
134
+ export interface SystemMessageOptions extends CachePointOptions {}
92
135
 
93
- // =============================================================================
94
- // Amazon Bedrock Provider Options / Metadata
95
- // =============================================================================
136
+ /**
137
+ * Amazon Bedrock options for user messages.
138
+ *
139
+ * @stability unstable
140
+ * @category models
141
+ * @since 4.0.0
142
+ */
143
+ export interface UserMessageOptions extends CachePointOptions {}
96
144
 
97
- /**
98
- * @since 1.0.0
99
- * @category Provider Options
100
- */
101
- export type AmazonBedrockReasoningInfo = {
102
- readonly type: "thinking"
103
145
  /**
104
- * Thinking content as an encrypted string, which is used to verify
105
- * that thinking content was indeed generated by Amazon Bedrock's API.
146
+ * Amazon Bedrock options for assistant messages.
147
+ *
148
+ * @stability unstable
149
+ * @category models
150
+ * @since 4.0.0
106
151
  */
107
- readonly signature: string
108
- } | {
109
- readonly type: "redacted_thinking"
152
+ export interface AssistantMessageOptions extends CachePointOptions {}
153
+
110
154
  /**
111
- * Thinking content which was flagged by Amazon Bedrock's safety systems, and
112
- * was therefore encrypted.
155
+ * Amazon Bedrock options for tool messages.
156
+ *
157
+ * @stability unstable
158
+ * @category models
159
+ * @since 4.0.0
113
160
  */
114
- readonly redactedData: string
115
- }
161
+ export interface ToolMessageOptions extends CachePointOptions {}
116
162
 
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
- }
163
+ /**
164
+ * Amazon Bedrock options for text prompt parts.
165
+ *
166
+ * @stability unstable
167
+ * @category models
168
+ * @since 4.0.0
169
+ */
170
+ export interface TextPartOptions extends CachePointOptions {}
127
171
 
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
- }
172
+ /**
173
+ * Amazon Bedrock options for file prompt parts.
174
+ *
175
+ * @stability unstable
176
+ * @category models
177
+ * @since 4.0.0
178
+ */
179
+ export interface FilePartOptions extends CachePointOptions {}
137
180
 
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
- }
181
+ /**
182
+ * Amazon Bedrock options for tool call prompt parts.
183
+ *
184
+ * @stability unstable
185
+ * @category models
186
+ * @since 4.0.0
187
+ */
188
+ export interface ToolCallPartOptions extends CachePointOptions {}
147
189
 
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
- }
190
+ /**
191
+ * Amazon Bedrock options for tool result prompt parts.
192
+ *
193
+ * @stability unstable
194
+ * @category models
195
+ * @since 4.0.0
196
+ */
197
+ export interface ToolResultPartOptions extends CachePointOptions {}
157
198
 
199
+ /**
200
+ * Amazon Bedrock options for reasoning prompt parts.
201
+ *
202
+ * **Details**
203
+ *
204
+ * Preserves the Bedrock reasoning payload so the block can be sent back in a
205
+ * later turn. A reasoning part without these options is dropped rather than
206
+ * sent, since Bedrock rejects a reasoning block it cannot verify.
207
+ *
208
+ * @stability unstable
209
+ * @category models
210
+ * @since 4.0.0
211
+ */
158
212
  export interface ReasoningPartOptions extends ProviderOptions {
159
- readonly bedrock?: AmazonBedrockReasoningInfo | undefined
213
+ readonly "amazon-bedrock"?: ReasoningInfo | null
160
214
  }
161
215
  }
162
216
 
163
- declare module "@effect/ai/Response" {
217
+ declare module "effect/ai/Response" {
218
+ /**
219
+ * Amazon Bedrock metadata attached to completed reasoning parts.
220
+ *
221
+ * @stability unstable
222
+ * @category models
223
+ * @since 4.0.0
224
+ */
164
225
  export interface ReasoningPartMetadata extends ProviderMetadata {
165
- readonly bedrock?: AmazonBedrockReasoningInfo | undefined
226
+ readonly "amazon-bedrock"?: ReasoningInfo | null
166
227
  }
167
228
 
229
+ /**
230
+ * Amazon Bedrock metadata attached to the end of a streamed reasoning
231
+ * block. Converse streams the signature, or the redacted payload, after the
232
+ * reasoning text, so it is attached once the block is complete.
233
+ *
234
+ * @stability unstable
235
+ * @category models
236
+ * @since 4.0.0
237
+ */
238
+ export interface ReasoningEndPartMetadata extends ProviderMetadata {
239
+ readonly "amazon-bedrock"?: ReasoningInfo | null
240
+ }
241
+
242
+ /**
243
+ * Amazon Bedrock metadata on the finish part.
244
+ *
245
+ * **Details**
246
+ *
247
+ * `stopReason` is the raw Converse stop reason. It tells
248
+ * `guardrail_intervened` from `content_filtered`, which both finish with
249
+ * `"content-filter"`, and `max_tokens` from `model_context_window_exceeded`,
250
+ * which both finish with `"length"`. It is `null` only when a stream ended
251
+ * without a `messageStop` event.
252
+ *
253
+ * @stability unstable
254
+ * @category models
255
+ * @since 4.0.0
256
+ */
168
257
  export interface FinishPartMetadata extends ProviderMetadata {
169
- readonly bedrock?: {
170
- readonly trace?: ConverseTrace | undefined
171
- readonly usage: {
172
- readonly cacheWriteInputTokens?: number | undefined
173
- }
174
- } | undefined
258
+ readonly "amazon-bedrock"?: {
259
+ readonly stopReason: string | null
260
+ } | null
175
261
  }
176
262
  }
177
263
 
264
+ /**
265
+ * Appends the cache point a message or part requests, if any, after the blocks
266
+ * already emitted for it.
267
+ */
268
+ const pushCachePoint = (
269
+ content: Array<typeof ContentBlock.Encoded> | Array<typeof SystemContentBlock.Encoded>,
270
+ carrier: { readonly options: CachePointOptions }
271
+ ): void => {
272
+ const cachePoint = carrier.options["amazon-bedrock"]?.cachePoint
273
+ if (!Predicate.isNullish(cachePoint)) {
274
+ content.push({ cachePoint })
275
+ }
276
+ }
277
+
278
+ // =============================================================================
279
+ // Configuration
280
+ // =============================================================================
281
+
282
+ /**
283
+ * Per-request configuration for the Amazon Bedrock language model.
284
+ *
285
+ * **Details**
286
+ *
287
+ * Derived from `ConverseRequest`, minus the fields built from the prompt and
288
+ * the toolkit, so every other Converse request parameter is settable per
289
+ * request. That includes `additionalModelRequestFields`, which carries
290
+ * inference parameters specific to the target model, among them extended
291
+ * thinking on Anthropic models. The thinking budget is drawn from the same
292
+ * ceiling as the visible answer, so `inferenceConfig.maxTokens` must exceed
293
+ * `budget_tokens`.
294
+ *
295
+ * **Example** (Enabling extended thinking for one request)
296
+ *
297
+ * ```ts
298
+ * import { AmazonBedrockLanguageModel } from "@effect/ai-amazon-bedrock"
299
+ * import { LanguageModel } from "effect/ai"
300
+ *
301
+ * const answer = LanguageModel.generateText({
302
+ * prompt: "How many r's are in strawberry?"
303
+ * }).pipe(
304
+ * AmazonBedrockLanguageModel.withConfigOverride({
305
+ * additionalModelRequestFields: {
306
+ * thinking: { type: "enabled", budget_tokens: 1024 }
307
+ * },
308
+ * inferenceConfig: { maxTokens: 4096 }
309
+ * })
310
+ * )
311
+ * ```
312
+ *
313
+ * @stability unstable
314
+ * @category configuration
315
+ * @since 4.0.0
316
+ */
317
+ export class Config extends Context.Service<
318
+ Config,
319
+ Simplify<
320
+ & Partial<
321
+ Omit<
322
+ typeof ConverseRequest.Encoded,
323
+ "messages" | "system" | "toolConfig" | "outputConfig"
324
+ >
325
+ >
326
+ & {
327
+ /**
328
+ * Output configuration for the request. Only `effort` is exposed:
329
+ * `textFormat` is derived from the response format.
330
+ */
331
+ readonly outputConfig?: {
332
+ readonly effort?: string
333
+ } | undefined
334
+ /**
335
+ * Whether `generateObject` uses Converse's native structured output
336
+ * (`outputConfig.textFormat`).
337
+ *
338
+ * **Details**
339
+ *
340
+ * By default the object is asked for through a tool named after it,
341
+ * forced with `toolChoice`, which every model that supports tool use
342
+ * accepts. Set this to `true` on a model that supports native structured
343
+ * output, such as recent Claude models, to send the JSON schema as
344
+ * `outputConfig.textFormat` instead and keep the caller's own tools
345
+ * available alongside it. Never sent to Bedrock.
346
+ */
347
+ readonly structuredOutputs?: boolean | undefined
348
+ }
349
+ >
350
+ >()("@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/Config") {}
351
+
178
352
  // =============================================================================
179
- // Amazon Bedrock Language Model
353
+ // Language Model
180
354
  // =============================================================================
181
355
 
182
356
  /**
183
- * @since 1.0.0
184
- * @category AiModels
357
+ * Creates an Amazon Bedrock model descriptor that can be provided with
358
+ * `Effect.provide`.
359
+ *
360
+ * @stability unstable
361
+ * @category constructors
362
+ * @since 4.0.0
185
363
  */
186
364
  export const model = (
187
- model: (string & {}) | Model,
188
- config?: Omit<Config.Service, "model">
365
+ model: Model,
366
+ config?: Omit<typeof Config.Service, "modelId">
189
367
  ): AiModel.Model<"amazon-bedrock", LanguageModel.LanguageModel, AmazonBedrockClient> =>
190
- AiModel.make("amazon-bedrock", layer({ model, config }))
368
+ AiModel.make("amazon-bedrock", model, layer({ model, config }))
191
369
 
192
370
  /**
193
- * @since 1.0.0
194
- * @category Constructors
371
+ * Creates an Amazon Bedrock `LanguageModel` service from a model identifier
372
+ * and optional request defaults.
373
+ *
374
+ * @stability unstable
375
+ * @category constructors
376
+ * @since 4.0.0
195
377
  */
196
- export const make = Effect.fnUntraced(function*(options: {
197
- readonly model: (string & {}) | Model
198
- readonly config?: Omit<Config.Service, "model">
199
- }) {
378
+ export const make = Effect.fnUntraced(function*({ config: providerConfig, model }: {
379
+ readonly model: Model
380
+ readonly config?: Omit<typeof Config.Service, "modelId"> | undefined
381
+ }): Effect.fn.Return<LanguageModel.LanguageModel, never, AmazonBedrockClient> {
200
382
  const client = yield* AmazonBedrockClient
201
383
 
202
384
  const makeRequest = Effect.fnUntraced(
203
- function*(providerOptions: LanguageModel.ProviderOptions) {
204
- const context = yield* Effect.context<never>()
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
-
210
- // Anthropic rejects requests that combine extended thinking with forced tool use.
211
- // generateObject always forces toolChoice, so strip "thinking" from the merged
212
- // fields on the json path to prevent a 400 from the Bedrock Converse API.
213
- let requestAdditionalFields: Record<string, unknown> | undefined
385
+ function*(
386
+ options: LanguageModel.ProviderOptions
387
+ ): Effect.fn.Return<typeof ConverseRequest.Encoded, AiError.AiError> {
388
+ const services = yield* Effect.context<never>()
389
+ const { outputConfig: configOutputConfig, structuredOutputs, ...config } = {
390
+ ...providerConfig,
391
+ ...Context.getOrUndefined(services, Config)
392
+ }
393
+ const modelId = config.modelId ?? model
394
+ const { messages, system } = yield* prepareMessages(options)
395
+ let toolConfig = yield* prepareTools(options)
396
+ const responseFormat = options.responseFormat
397
+
398
+ let outputConfig: typeof OutputConfig.Encoded | undefined = configOutputConfig
214
399
  if (responseFormat.type === "json") {
215
- if (
216
- Predicate.isNotUndefined(config.additionalModelRequestFields) ||
217
- Predicate.isNotUndefined(additionalTools)
218
- ) {
219
- const { thinking: _thinking, ...rest } = {
220
- ...config.additionalModelRequestFields,
221
- ...additionalTools
400
+ const json = yield* tryJsonSchema(
401
+ "makeRequest",
402
+ () => Tool.getJsonSchemaFromSchema(responseFormat.schema, { transformer: toCodecAnthropic })
403
+ )
404
+ const description = SchemaAST.resolveDescription(responseFormat.schema.ast)
405
+ if (structuredOutputs === true) {
406
+ // Native structured output. The caller's own tools still go out
407
+ // alongside it.
408
+ outputConfig = {
409
+ ...outputConfig,
410
+ textFormat: {
411
+ type: "json_schema",
412
+ structure: {
413
+ jsonSchema: {
414
+ schema: JSON.stringify(json),
415
+ name: responseFormat.objectName,
416
+ ...(Predicate.isNotUndefined(description) ? { description } : {})
417
+ }
418
+ }
419
+ }
420
+ }
421
+ } else {
422
+ // The object tool is the only tool, and it is forced.
423
+ toolConfig = {
424
+ tools: [{
425
+ toolSpec: {
426
+ name: responseFormat.objectName,
427
+ description: description ?? "Respond with a JSON object",
428
+ inputSchema: { json: json as Record<string, unknown> }
429
+ }
430
+ }],
431
+ toolChoice: { tool: { name: responseFormat.objectName } }
222
432
  }
223
- requestAdditionalFields = rest
224
- }
225
- } else if (Predicate.isNotUndefined(additionalTools)) {
226
- requestAdditionalFields = {
227
- ...config.additionalModelRequestFields,
228
- ...additionalTools
229
433
  }
230
434
  }
231
435
 
232
436
  const request: typeof ConverseRequest.Encoded = {
233
437
  ...config,
438
+ modelId,
234
439
  system,
235
440
  messages,
236
- // Handle tool configuration
237
- ...(responseFormat.type === "json"
238
- ? {
239
- toolConfig: {
240
- tools: [{
241
- toolSpec: {
242
- name: responseFormat.objectName,
243
- description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ??
244
- "Respond with a JSON object",
245
- inputSchema: {
246
- json: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast) as any
247
- }
248
- }
249
- }],
250
- toolChoice: { tool: { name: responseFormat.objectName } }
251
- }
252
- }
253
- : Predicate.isNotUndefined(toolConfig.tools) && toolConfig.tools.length > 0
254
- ? { toolConfig }
255
- : {}),
256
- // Handle additional model request fields
257
- ...(Predicate.isNotUndefined(requestAdditionalFields)
258
- ? { additionalModelRequestFields: requestAdditionalFields }
259
- : {})
441
+ ...(Predicate.isNotUndefined(outputConfig) ? { outputConfig } : {}),
442
+ ...(Predicate.isNotUndefined(toolConfig) ? { toolConfig } : {})
443
+ }
444
+
445
+ // Converse rejects `toolUse` and `toolResult` blocks in a request that
446
+ // carries no `toolConfig`, and it has no tool choice that offers tools
447
+ // while forbidding calls to them.
448
+ const hasToolBlocks = messages.some((message) =>
449
+ message.content.some((block) =>
450
+ Predicate.isNotUndefined(block.toolUse) || Predicate.isNotUndefined(block.toolResult)
451
+ )
452
+ )
453
+ if (hasToolBlocks && Predicate.isUndefined(request.toolConfig)) {
454
+ return yield* invalidUserInput(
455
+ "makeRequest",
456
+ "The prompt contains tool calls or tool results, and Converse rejects them in a request that " +
457
+ "carries no tools. Pass the toolkit that produced the tool calls, with a toolChoice other than \"none\"."
458
+ )
260
459
  }
261
- return { betas, request }
460
+ return request
262
461
  }
263
462
  )
264
463
 
265
464
  return yield* LanguageModel.make({
266
- generateText: Effect.fnUntraced(
267
- function*(options) {
268
- const { betas, request } = yield* makeRequest(options)
269
- annotateRequest(options.span, request)
270
- const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined
271
- const rawResponse = yield* client.converse({
272
- params: { "anthropic-beta": anthropicBeta },
273
- payload: request
274
- })
275
- annotateResponse(options.span, request, rawResponse)
276
- return yield* makeResponse(request, rawResponse, options)
277
- }
278
- ),
279
- streamText: Effect.fnUntraced(
280
- function*(options) {
281
- const { betas, request } = yield* makeRequest(options)
282
- annotateRequest(options.span, request)
283
- const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined
284
- const stream = client.converseStream({
285
- params: { "anthropic-beta": anthropicBeta },
286
- payload: request
287
- })
288
- return { request, stream }
289
- },
290
- (effect, options) =>
291
- effect.pipe(
292
- Effect.flatMap(({ request, stream }) => makeStreamResponse(request, stream, options)),
293
- Stream.unwrap,
294
- Stream.map((response) => {
295
- annotateStreamResponse(options.span, response)
296
- return response
297
- })
298
- )
299
- )
465
+ codecTransformer: toCodecAnthropic,
466
+ generateText: Effect.fnUntraced(function*(options) {
467
+ const request = yield* makeRequest(options)
468
+ annotateRequest(options.span, request)
469
+ const response = yield* client.converse(toConverseRequest(request))
470
+ return yield* makeResponse(request, response, options)
471
+ }),
472
+ streamText: Effect.fnUntraced(function*(options) {
473
+ const request = yield* makeRequest(options)
474
+ annotateRequest(options.span, request)
475
+ return makeStreamResponse(request, client.converseStream(request), options.tools, options.span)
476
+ }, (effect, _options) => effect.pipe(Stream.unwrap))
300
477
  })
301
478
  })
302
479
 
303
480
  /**
304
- * @since 1.0.0
305
- * @category Layers
481
+ * Converse has no `streamProcessingMode`; only ConverseStream does.
482
+ */
483
+ const toConverseRequest = (request: typeof ConverseRequest.Encoded): typeof ConverseRequest.Encoded => {
484
+ if (Predicate.isUndefined(request.guardrailConfig?.streamProcessingMode)) {
485
+ return request
486
+ }
487
+ const { streamProcessingMode: _, ...guardrailConfig } = request.guardrailConfig
488
+ return { ...request, guardrailConfig }
489
+ }
490
+
491
+ /**
492
+ * Creates a layer for the Amazon Bedrock language model.
493
+ *
494
+ * @stability unstable
495
+ * @category layers
496
+ * @since 4.0.0
306
497
  */
307
498
  export const layer = (options: {
308
- readonly model: (string & {}) | Model
309
- readonly config?: Omit<Config.Service, "model">
499
+ readonly model: Model
500
+ readonly config?: Omit<typeof Config.Service, "modelId"> | undefined
310
501
  }): Layer.Layer<LanguageModel.LanguageModel, never, AmazonBedrockClient> =>
311
- Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))
502
+ Layer.effect(LanguageModel.LanguageModel, make(options))
312
503
 
313
504
  /**
314
- * @since 1.0.0
315
- * @category Configuration
505
+ * Provides config overrides for Amazon Bedrock language model operations.
506
+ *
507
+ * @stability unstable
508
+ * @category configuration
509
+ * @since 4.0.0
316
510
  */
317
511
  export const withConfigOverride: {
318
512
  /**
319
- * @since 1.0.0
320
- * @category Configuration
513
+ * Provides config overrides for Amazon Bedrock language model operations.
514
+ *
515
+ * @stability unstable
516
+ * @category configuration
517
+ * @since 4.0.0
321
518
  */
322
- (config: Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
519
+ (overrides: typeof Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Config>>
323
520
  /**
324
- * @since 1.0.0
325
- * @category Configuration
521
+ * Provides config overrides for Amazon Bedrock language model operations.
522
+ *
523
+ * @stability unstable
524
+ * @category configuration
525
+ * @since 4.0.0
326
526
  */
327
- <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service): Effect.Effect<A, E, R>
527
+ <A, E, R>(self: Effect.Effect<A, E, R>, overrides: typeof Config.Service): Effect.Effect<A, E, Exclude<R, Config>>
328
528
  } = dual<
329
- /**
330
- * @since 1.0.0
331
- * @category Configuration
332
- */
333
- (config: Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,
334
- /**
335
- * @since 1.0.0
336
- * @category Configuration
337
- */
338
- <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service) => Effect.Effect<A, E, R>
529
+ (
530
+ overrides: typeof Config.Service
531
+ ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Config>>,
532
+ <A, E, R>(self: Effect.Effect<A, E, R>, overrides: typeof Config.Service) => Effect.Effect<A, E, Exclude<R, Config>>
339
533
  >(2, (self, overrides) =>
340
534
  Effect.flatMap(
341
- Config.getOrUndefined,
342
- (config) => Effect.provideService(self, Config, { ...config, ...overrides })
535
+ Effect.serviceOption(Config),
536
+ (config) =>
537
+ Effect.provideService(self, Config, {
538
+ ...(config._tag === "Some" ? config.value : {}),
539
+ ...overrides
540
+ })
343
541
  ))
344
542
 
345
543
  // =============================================================================
346
544
  // Prompt Conversion
347
545
  // =============================================================================
348
546
 
547
+ /**
548
+ * Converse takes a format enum rather than a media type, so only the media
549
+ * types it has a format for can be sent. `image/*` is resolved to jpeg, which
550
+ * mirrors the other providers.
551
+ */
552
+ const imageFormats: Record<string, typeof ImageBlock.Encoded["format"]> = {
553
+ "image/*": "jpeg",
554
+ "image/jpeg": "jpeg",
555
+ "image/png": "png",
556
+ "image/gif": "gif",
557
+ "image/webp": "webp"
558
+ }
559
+
560
+ const documentFormats: Record<string, typeof DocumentBlock.Encoded["format"]> = {
561
+ "application/pdf": "pdf",
562
+ "text/csv": "csv",
563
+ "application/msword": "doc",
564
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
565
+ "application/vnd.ms-excel": "xls",
566
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
567
+ "text/html": "html",
568
+ "text/plain": "txt",
569
+ "text/markdown": "md"
570
+ }
571
+
572
+ /** Matches any absolute url, so one is rejected instead of being treated as base64 data. */
573
+ const urlPattern = /^[a-z][a-z0-9+.-]*:\/\//i
574
+
575
+ /** Matches the header of a `data:` url, up to the comma before its payload. */
576
+ const dataUrlPattern = /^data:[^,]*?(;base64)?,/i
577
+
578
+ const fail = (method: string, reason: AiError.AiErrorReason): AiError.AiError =>
579
+ AiError.make({ module: "AmazonBedrockLanguageModel", method, reason })
580
+
581
+ const invalidUserInput = (method: string, description: string) =>
582
+ fail(method, new AiError.InvalidUserInputError({ description }))
583
+
584
+ /**
585
+ * Resolves file part data into base64 bytes.
586
+ *
587
+ * **Details**
588
+ *
589
+ * String data is already base64 per `Prompt.FilePart`, so it is passed through
590
+ * untouched, and only the payload of a base64 `data:` url is sent. Converse
591
+ * does not fetch remote files, so any other url fails.
592
+ */
593
+ const fileBytes: (
594
+ data: typeof Prompt.FilePart.Type["data"]
595
+ ) => Effect.Effect<string, AiError.AiError> = Effect.fnUntraced(function*(data) {
596
+ if (data instanceof Uint8Array) {
597
+ return Base64.encode(data)
598
+ }
599
+ const string = data instanceof URL ? data.href : data
600
+ const dataUrl = dataUrlPattern.exec(string)
601
+ if (dataUrl !== null) {
602
+ if (Predicate.isUndefined(dataUrl[1])) {
603
+ return yield* invalidUserInput(
604
+ "prepareMessages",
605
+ `Unsupported file url '${dataUrl[0]}...' - a data url must have a base64 payload`
606
+ )
607
+ }
608
+ return string.slice(dataUrl[0].length)
609
+ }
610
+ if (data instanceof URL || urlPattern.test(string)) {
611
+ return yield* invalidUserInput(
612
+ "prepareMessages",
613
+ `Unsupported file url '${string}' - Converse does not fetch remote files, so pass the file bytes instead`
614
+ )
615
+ }
616
+ return string
617
+ })
618
+
619
+ /**
620
+ * Bedrock only accepts alphanumerics, single runs of whitespace, hyphens,
621
+ * parentheses and square brackets in a document name, so anything else is
622
+ * folded into a space. The file extension is dropped because the format is
623
+ * carried separately.
624
+ */
625
+ const documentName = (fileName: string | undefined, position: number): string => {
626
+ if (Predicate.isNotUndefined(fileName)) {
627
+ const name = fileName.replace(/\.[^.]*$/, "").replace(/[^a-zA-Z0-9\s\-()[\]]/g, " ").replace(/\s+/g, " ").trim()
628
+ if (name.length > 0) {
629
+ return name
630
+ }
631
+ }
632
+ return `document ${position}`
633
+ }
634
+
635
+ const toolResultContent = (result: unknown): Array<typeof ToolResultContentBlock.Encoded> => {
636
+ if (typeof result === "string") {
637
+ return [{ text: result }]
638
+ }
639
+ if (Predicate.isUndefined(result)) {
640
+ return [{ text: "" }]
641
+ }
642
+ return [{ json: result }]
643
+ }
644
+
349
645
  const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<{
350
646
  readonly system: ReadonlyArray<typeof SystemContentBlock.Encoded>
351
647
  readonly messages: ReadonlyArray<typeof Message.Encoded>
@@ -355,28 +651,25 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
355
651
 
356
652
  const system: Array<typeof SystemContentBlock.Encoded> = []
357
653
  const messages: Array<typeof Message.Encoded> = []
358
-
359
- let documentCounter = 0
360
- const nextDocumentName = () => `document-${++documentCounter}`
654
+ // Document names must be present and distinct within a request, so
655
+ // unnamed documents are numbered across the whole conversation.
656
+ let documentCount = 0
361
657
 
362
658
  for (let i = 0; i < groups.length; i++) {
363
- const group = groups[i]
659
+ const group = groups[i]!
364
660
  const isLastGroup = i === groups.length - 1
365
661
 
366
662
  switch (group.type) {
367
663
  case "system": {
368
664
  if (messages.length > 0) {
369
- return yield* new AiError.MalformedInput({
370
- module: "AmazonBedrockLanguageModel",
371
- method: "prepareMessages",
372
- description: "Multiple system messages separated by user / assistant messages"
373
- })
665
+ return yield* invalidUserInput(
666
+ "prepareMessages",
667
+ "Multiple system messages separated by user / assistant messages"
668
+ )
374
669
  }
375
670
  for (const message of group.messages) {
376
671
  system.push({ text: message.content })
377
- if (Predicate.isNotUndefined(getCachePoint(message))) {
378
- system.push(BEDROCK_CACHE_POINT)
379
- }
672
+ pushCachePoint(system, message)
380
673
  }
381
674
  break
382
675
  }
@@ -387,40 +680,36 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
387
680
  for (const message of group.messages) {
388
681
  switch (message.role) {
389
682
  case "user": {
390
- for (let j = 0; j < message.content.length; j++) {
391
- const part = message.content[j]
392
-
683
+ for (const part of message.content) {
393
684
  switch (part.type) {
394
685
  case "text": {
395
686
  content.push({ text: part.text })
687
+ pushCachePoint(content, part)
396
688
  break
397
689
  }
398
-
399
690
  case "file": {
400
- if (part.data instanceof URL) {
401
- // TODO(Max): support this
402
- return yield* new AiError.MalformedInput({
403
- module: "AmazonBedrockLanguageModel",
404
- method: "prepareMessages",
405
- description: "File URL inputs are not supported at this time"
406
- })
407
- }
408
- if (part.mediaType.startsWith("image/")) {
691
+ const imageFormat = imageFormats[part.mediaType]
692
+ const documentFormat = documentFormats[part.mediaType]
693
+ if (Predicate.isNotUndefined(imageFormat)) {
409
694
  content.push({
410
- image: {
411
- format: yield* getImageFormat(part.mediaType),
412
- source: { bytes: convertToBase64(part.data) }
413
- }
695
+ image: { format: imageFormat, source: { bytes: yield* fileBytes(part.data) } }
414
696
  })
415
- } else {
697
+ } else if (Predicate.isNotUndefined(documentFormat)) {
698
+ documentCount += 1
416
699
  content.push({
417
700
  document: {
418
- format: yield* getDocumentFormat(part.mediaType),
419
- name: nextDocumentName(),
420
- source: { bytes: convertToBase64(part.data) }
701
+ format: documentFormat,
702
+ name: documentName(part.fileName, documentCount),
703
+ source: { bytes: yield* fileBytes(part.data) }
421
704
  }
422
705
  })
706
+ } else {
707
+ return yield* invalidUserInput(
708
+ "prepareMessages",
709
+ `Unsupported media type '${part.mediaType}' for file part - this provider supports the images and documents Converse has a format for`
710
+ )
423
711
  }
712
+ pushCachePoint(content, part)
424
713
  break
425
714
  }
426
715
  }
@@ -430,24 +719,25 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
430
719
 
431
720
  case "tool": {
432
721
  for (const part of message.content) {
722
+ // Only tool-result parts map to Converse blocks; other tool
723
+ // message parts (e.g. tool-approval responses) are skipped.
724
+ if (part.type !== "tool-result") continue
433
725
  content.push({
434
726
  toolResult: {
435
727
  toolUseId: part.id,
436
- content: [{ text: JSON.stringify(part.result) }]
728
+ content: toolResultContent(part.result),
729
+ ...(part.isFailure ? { status: "error" } : {})
437
730
  }
438
731
  })
732
+ pushCachePoint(content, part)
439
733
  }
440
734
  break
441
735
  }
442
736
  }
443
-
444
- if (getCachePoint(message)) {
445
- content.push(BEDROCK_CACHE_POINT)
446
- }
737
+ pushCachePoint(content, message)
447
738
  }
448
739
 
449
740
  messages.push({ role: "user", content })
450
-
451
741
  break
452
742
  }
453
743
 
@@ -455,54 +745,54 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
455
745
  const content: Array<typeof ContentBlock.Encoded> = []
456
746
 
457
747
  for (let j = 0; j < group.messages.length; j++) {
458
- const message = group.messages[j]
748
+ const message = group.messages[j]!
459
749
  const isLastMessage = j === group.messages.length - 1
460
750
 
461
751
  for (let k = 0; k < message.content.length; k++) {
462
- const part = message.content[k]
752
+ const part = message.content[k]!
463
753
  const isLastPart = k === message.content.length - 1
464
754
 
465
755
  switch (part.type) {
466
756
  case "text": {
467
757
  // Skip empty text blocks
468
758
  if (part.text.trim().length === 0) {
469
- break
759
+ continue
470
760
  }
471
761
  content.push({
472
- // Amazon Bedrock does not allow trailing whitespace in
473
- // assistant content blocks
474
- text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text)
762
+ // Amazon Bedrock does not allow trailing whitespace in a
763
+ // pre-filled assistant response.
764
+ text: isLastGroup && isLastMessage && isLastPart ? part.text.trim() : part.text
475
765
  })
766
+ pushCachePoint(content, part)
476
767
  break
477
768
  }
478
-
479
769
  case "reasoning": {
480
- const options = part.options.bedrock
481
- if (Predicate.isNotUndefined(options)) {
482
- if (options.type === "thinking") {
483
- content.push({
484
- reasoningContent: {
485
- reasoningText: {
486
- // Amazon Bedrock does not allow trailing whitespace in
487
- // assistant content blocks
488
- text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text),
489
- signature: options.signature
490
- }
491
- }
492
- })
493
- }
494
- if (options.type === "redacted_thinking") {
495
- content.push({
496
- reasoningContent: {
497
- redactedContent: options.redactedData
770
+ // Bedrock verifies the payload that accompanies a reasoning
771
+ // block, so a reasoning part that did not come from this
772
+ // provider carries nothing it would accept and is dropped
773
+ // rather than sent and rejected.
774
+ const info = part.options["amazon-bedrock"]
775
+ if (Predicate.isNullish(info)) {
776
+ continue
777
+ }
778
+ if (Predicate.isNotUndefined(info.redactedContent)) {
779
+ content.push({ reasoningContent: { redactedContent: info.redactedContent } })
780
+ } else {
781
+ content.push({
782
+ reasoningContent: {
783
+ reasoningText: {
784
+ text: part.text,
785
+ ...(Predicate.isNotUndefined(info.signature) ? { signature: info.signature } : {})
498
786
  }
499
- })
500
- }
787
+ }
788
+ })
501
789
  }
502
790
  break
503
791
  }
504
-
505
792
  case "tool-call": {
793
+ if (part.providerExecuted) {
794
+ continue
795
+ }
506
796
  content.push({
507
797
  toolUse: {
508
798
  toolUseId: part.id,
@@ -510,18 +800,21 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
510
800
  input: part.params
511
801
  }
512
802
  })
803
+ pushCachePoint(content, part)
513
804
  break
514
805
  }
806
+ default: {
807
+ return yield* invalidUserInput(
808
+ "prepareMessages",
809
+ `Unsupported assistant content part of type '${part.type}' - this provider supports text, reasoning, and tool calls`
810
+ )
811
+ }
515
812
  }
516
813
  }
517
-
518
- if (getCachePoint(message)) {
519
- content.push(BEDROCK_CACHE_POINT)
520
- }
814
+ pushCachePoint(content, message)
521
815
  }
522
816
 
523
817
  messages.push({ role: "assistant", content })
524
-
525
818
  break
526
819
  }
527
820
  }
@@ -531,6 +824,94 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
531
824
  }
532
825
  )
533
826
 
827
+ // =============================================================================
828
+ // Schema Helpers
829
+ // =============================================================================
830
+
831
+ const tryJsonSchema = <A>(method: string, evaluate: () => A): Effect.Effect<A, AiError.AiError> =>
832
+ Effect.try({
833
+ try: evaluate,
834
+ catch: (error) =>
835
+ fail(
836
+ method,
837
+ new AiError.UnsupportedSchemaError({ description: error instanceof Error ? error.message : String(error) })
838
+ )
839
+ })
840
+
841
+ // Bedrock is sent each tool's codec schema, which differs from the tool's own
842
+ // schema wherever the codec rewrites a parameter. Params that follow the codec
843
+ // are re-encoded with the tool's schema for the Toolkit to decode. Any others
844
+ // are left as they are, so that the Toolkit reports the error.
845
+ const decodeToolParams = (
846
+ tools: ReadonlyArray<Tool.Any>,
847
+ toolName: string,
848
+ params: unknown
849
+ ): Effect.Effect<unknown> => {
850
+ const tool = tools.find((tool) => tool.name === toolName)
851
+ if (Predicate.isUndefined(tool)) {
852
+ return Effect.succeed(params)
853
+ }
854
+ return Effect.try(() => toCodecAnthropic(tool.parametersSchema).codec).pipe(
855
+ Effect.flatMap((codec) => Schema.decodeUnknownEffect(codec)(params)),
856
+ Effect.flatMap((decoded) => Schema.encodeUnknownEffect(tool.parametersSchema)(decoded)),
857
+ Effect.orElseSucceed(() => params)
858
+ ) as Effect.Effect<unknown>
859
+ }
860
+
861
+ // =============================================================================
862
+ // Tool Conversion
863
+ // =============================================================================
864
+
865
+ const prepareTools: (
866
+ options: LanguageModel.ProviderOptions
867
+ ) => Effect.Effect<
868
+ typeof ToolConfiguration.Encoded | undefined,
869
+ AiError.AiError
870
+ > = Effect.fnUntraced(function*(options) {
871
+ // Converse rejects an empty `tools` array, and it has no tool choice that
872
+ // forbids tool calls.
873
+ if (options.tools.length === 0 || options.toolChoice === "none") {
874
+ return undefined
875
+ }
876
+
877
+ const tools: Array<typeof BedrockTool.Encoded> = []
878
+ for (const tool of options.tools) {
879
+ // Provider-defined tools are rejected, and only they go by another name
880
+ // on the wire, so no `Tool.NameMapper` is needed.
881
+ if (!Tool.isUserDefined(tool)) {
882
+ return yield* invalidUserInput(
883
+ "prepareTools",
884
+ `Unsupported tool '${(tool as { name: string }).name}' - this provider supports user-defined tools only`
885
+ )
886
+ }
887
+ const description = Tool.getDescription(tool)
888
+ const json = yield* tryJsonSchema("prepareTools", () => Tool.getJsonSchema(tool, { transformer: toCodecAnthropic }))
889
+ tools.push({
890
+ toolSpec: {
891
+ name: tool.name,
892
+ ...(Predicate.isNotUndefined(description) ? { description } : {}),
893
+ inputSchema: { json: json as Record<string, unknown> }
894
+ }
895
+ })
896
+ }
897
+
898
+ let toolChoice: typeof ToolChoice.Encoded
899
+ const choice = options.toolChoice
900
+ if (choice === "auto") {
901
+ toolChoice = { auto: {} }
902
+ } else if (choice === "required") {
903
+ toolChoice = { any: {} }
904
+ } else if ("tool" in choice) {
905
+ toolChoice = { tool: { name: choice.tool } }
906
+ } else {
907
+ // `LanguageModel` already filters the toolkit by `toolChoice.oneOf`
908
+ // before a provider sees it, so this only picks the mode.
909
+ toolChoice = choice.mode === "required" ? { any: {} } : { auto: {} }
910
+ }
911
+
912
+ return { tools, toolChoice }
913
+ })
914
+
534
915
  // =============================================================================
535
916
  // Response Conversion
536
917
  // =============================================================================
@@ -539,602 +920,308 @@ const makeResponse: (
539
920
  request: typeof ConverseRequest.Encoded,
540
921
  response: ConverseResponse,
541
922
  options: LanguageModel.ProviderOptions
542
- ) => Effect.Effect<
543
- Array<Response.PartEncoded>,
544
- never,
545
- IdGenerator.IdGenerator
546
- > = Effect.fnUntraced(function*(request, response, options) {
547
- const parts: Array<Response.PartEncoded> = []
548
-
549
- parts.push({
550
- type: "response-metadata",
551
- modelId: request.modelId,
552
- timestamp: DateTime.formatIso(yield* DateTime.now)
553
- })
554
-
555
- for (const part of response.output.message.content) {
556
- switch (part.type) {
557
- case "text": {
558
- // The text parts should only be added to the response here if the
559
- // response format is `"text"`. If the response format is `"json"`,
560
- // then the text parts must instead be added to the response when a
561
- // tool call is received.
562
- if (options.responseFormat.type === "text") {
563
- parts.push({
564
- type: "text",
565
- text: part.text
566
- })
923
+ ) => Effect.Effect<Array<Response.PartEncoded>, AiError.AiError> = Effect.fnUntraced(
924
+ function*(request, response, options) {
925
+ const parts: Array<Response.PartEncoded> = []
926
+ // Without native structured output the object is asked for through a tool
927
+ // named after it (see `makeRequest`).
928
+ const objectToolName = options.responseFormat.type === "json" &&
929
+ Predicate.isUndefined(request.outputConfig?.textFormat)
930
+ ? options.responseFormat.objectName
931
+ : undefined
932
+ // A model can call the object tool more than once. The first call is the
933
+ // object: joining the inputs of several calls would not be valid JSON.
934
+ const objectToolPart = Predicate.isUndefined(objectToolName)
935
+ ? undefined
936
+ : response.output.message.content.find((part) => part.toolUse?.name === objectToolName)
937
+ const hasObjectTool = Predicate.isNotUndefined(objectToolPart)
938
+
939
+ parts.push(yield* responseMetadataPart(request.modelId))
940
+
941
+ for (const part of response.output.message.content) {
942
+ if (Predicate.isNotUndefined(part.text)) {
943
+ // With native structured output the object arrives here, as JSON text
944
+ // the LanguageModel layer decodes. When the object tool was called
945
+ // instead, prose next to it must not be concatenated into the JSON.
946
+ if (!hasObjectTool) {
947
+ parts.push({ type: "text", text: part.text })
567
948
  }
568
- break
569
- }
570
-
571
- case "reasoningContent": {
572
- if (part.reasoningContent.type === "reasoning") {
573
- const signature = part.reasoningContent.reasoningText.signature
574
- parts.push({
575
- type: "reasoning",
576
- text: part.reasoningContent.reasoningText.text,
577
- metadata: Predicate.isNotUndefined(signature) ?
578
- { bedrock: { type: "thinking", signature } }
579
- : undefined
580
- })
949
+ } else if (Predicate.isNotUndefined(part.toolUse)) {
950
+ if (part.toolUse.name === objectToolName) {
951
+ // The object tool's input is the object: re-emit it as text for the
952
+ // LanguageModel layer to decode.
953
+ if (part === objectToolPart) {
954
+ parts.push({ type: "text", text: JSON.stringify(part.toolUse.input) })
955
+ }
956
+ continue
581
957
  }
582
- if (part.reasoningContent.type === "redacted-reasoning") {
958
+ parts.push({
959
+ type: "tool-call",
960
+ id: part.toolUse.toolUseId,
961
+ name: part.toolUse.name,
962
+ params: yield* decodeToolParams(options.tools, part.toolUse.name, part.toolUse.input),
963
+ providerExecuted: false
964
+ })
965
+ } else if (Predicate.isNotUndefined(part.reasoningContent)) {
966
+ const { reasoningText, redactedContent } = part.reasoningContent
967
+ if (Predicate.isNotUndefined(reasoningText)) {
583
968
  parts.push({
584
969
  type: "reasoning",
585
- text: "",
970
+ text: reasoningText.text,
586
971
  metadata: {
587
- bedrock: {
588
- type: "redacted_thinking",
589
- redactedData: part.reasoningContent.redactedContent
590
- }
972
+ "amazon-bedrock": Predicate.isNotUndefined(reasoningText.signature)
973
+ ? { signature: reasoningText.signature }
974
+ : {}
591
975
  }
592
976
  })
593
- }
594
- break
595
- }
596
-
597
- case "toolUse": {
598
- // When a `"json"` response format is requested, the JSON that we need
599
- // will be returned by the tool call injected into the request
600
- if (options.responseFormat.type === "json") {
977
+ } else if (Predicate.isNotUndefined(redactedContent)) {
978
+ // Redacted reasoning has no readable text; the encrypted payload
979
+ // rides along in the metadata so the block can be sent back later.
601
980
  parts.push({
602
- type: "text",
603
- text: JSON.stringify(part.toolUse.input)
604
- })
605
- } else {
606
- const providerTool = AnthropicTool.getProviderDefinedToolName(part.toolUse.name)
607
- const name = Predicate.isNotUndefined(providerTool) ? providerTool : part.toolUse.name
608
- const providerName = Predicate.isNotUndefined(providerTool) ? part.toolUse.name : undefined
609
- parts.push({
610
- type: "tool-call",
611
- id: part.toolUse.toolUseId,
612
- name,
613
- params: part.toolUse.input,
614
- providerName,
615
- providerExecuted: false
981
+ type: "reasoning",
982
+ text: "",
983
+ metadata: { "amazon-bedrock": { redactedContent } }
616
984
  })
617
985
  }
618
- break
619
986
  }
987
+ // Blocks this provider does not model decode with every field undefined
988
+ // and are ignored.
620
989
  }
621
- }
622
990
 
623
- const finishReason = InternalUtilities.resolveFinishReason(response.stopReason)
991
+ const usage = makeUsage(response.usage)
992
+ annotateResponse(options.span, request.modelId, response.stopReason, usage)
993
+ // Calling the object tool is how the model finishes, not a request to run
994
+ // a tool.
995
+ parts.push(
996
+ finishPart(InternalUtilities.resolveFinishReason(response.stopReason, hasObjectTool), response.stopReason, usage)
997
+ )
624
998
 
625
- parts.push({
626
- type: "finish",
627
- reason: finishReason,
628
- usage: {
629
- inputTokens: response.usage.inputTokens,
630
- outputTokens: response.usage.outputTokens,
631
- totalTokens: response.usage.totalTokens,
632
- cachedInputTokens: response.usage.cacheReadInputTokens
999
+ return parts
1000
+ }
1001
+ )
1002
+
1003
+ /**
1004
+ * Converse returns no response identifier, and the client service does not
1005
+ * surface the raw HTTP request.
1006
+ */
1007
+ const responseMetadataPart = (modelId: string) =>
1008
+ Effect.map(DateTime.now, (now) => ({
1009
+ type: "response-metadata",
1010
+ id: undefined,
1011
+ modelId,
1012
+ timestamp: DateTime.formatIso(now),
1013
+ request: undefined
1014
+ } as const))
1015
+
1016
+ const finishPart = (reason: Response.FinishReason, stopReason: string | null, usage: Response.Usage) => ({
1017
+ type: "finish",
1018
+ reason,
1019
+ usage,
1020
+ response: undefined,
1021
+ metadata: { "amazon-bedrock": { stopReason } }
1022
+ } as const)
1023
+
1024
+ const makeUsage = (usage: TokenUsage): Response.Usage => {
1025
+ const cacheRead = usage.cacheReadInputTokens
1026
+ const cacheWrite = usage.cacheWriteInputTokens
1027
+ return {
1028
+ inputTokens: {
1029
+ uncached: usage.inputTokens,
1030
+ total: usage.inputTokens + (cacheRead ?? 0) + (cacheWrite ?? 0),
1031
+ cacheRead,
1032
+ cacheWrite
633
1033
  },
634
- metadata: {
635
- bedrock: {
636
- trace: response.trace,
637
- usage: { cacheWriteInputTokens: response.usage.cacheWriteInputTokens }
638
- }
1034
+ outputTokens: {
1035
+ total: usage.outputTokens,
1036
+ text: undefined,
1037
+ reasoning: undefined
639
1038
  }
640
- })
1039
+ }
1040
+ }
1041
+
1042
+ /**
1043
+ * A streamed reasoning block in flight. Converse streams the signature after
1044
+ * the text, and redacted reasoning as several base64 chunks of one byte
1045
+ * sequence, each encoded on its own, so the chunks are decoded and joined
1046
+ * before the block's metadata is emitted.
1047
+ */
1048
+ interface ReasoningBlock {
1049
+ signature: string | undefined
1050
+ readonly redactedChunks: Array<Uint8Array>
1051
+ }
641
1052
 
642
- return parts
1053
+ const reasoningBlockInfo = (block: ReasoningBlock): ReasoningInfo => ({
1054
+ ...(Predicate.isNotUndefined(block.signature) ? { signature: block.signature } : {}),
1055
+ ...(block.redactedChunks.length > 0 ? { redactedContent: Base64.encode(Bytes.concat(block.redactedChunks)) } : {})
643
1056
  })
644
1057
 
645
- const makeStreamResponse: (
1058
+ const makeStreamResponse = (
646
1059
  request: typeof ConverseRequest.Encoded,
647
- stream: Stream.Stream<ConverseResponseStreamEvent, AiError.AiError>,
648
- options: LanguageModel.ProviderOptions
649
- ) => Effect.Effect<
650
- Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,
651
- never,
652
- IdGenerator.IdGenerator
653
- > = Effect.fnUntraced(
654
- function*(request, stream, options) {
655
- const contentBlocks: Record<
656
- number,
657
- | {
658
- readonly type: "text"
659
- }
660
- | {
661
- readonly type: "reasoning"
662
- }
663
- | {
664
- readonly type: "tool-call"
665
- readonly id: string
666
- readonly name: string
667
- params: string
668
- readonly providerName?: string | undefined
669
- readonly providerExecuted: boolean
670
- }
671
- > = {}
672
-
673
- let trace: ConverseTrace | undefined = undefined
674
- let cacheWriteInputTokens: number | undefined = undefined
675
- let finishReason: Response.FinishReason | undefined = undefined
676
- const usage: Mutable<typeof Response.Usage.Encoded> = {
677
- inputTokens: undefined,
678
- outputTokens: undefined,
679
- totalTokens: undefined
680
- }
681
-
682
- return stream.pipe(
683
- Stream.mapEffect(Effect.fnUntraced(function*(event) {
684
- const parts: Array<Response.StreamPartEncoded> = []
685
-
686
- switch (event.type) {
687
- case "messageStart": {
688
- parts.push({
689
- type: "response-metadata",
690
- modelId: request.modelId,
691
- timestamp: DateTime.formatIso(yield* DateTime.now)
692
- })
693
- break
1060
+ stream: Stream.Stream<ConverseStreamEvent, AiError.AiError>,
1061
+ tools: ReadonlyArray<Tool.Any>,
1062
+ span: Span
1063
+ ): Stream.Stream<Response.StreamPartEncoded, AiError.AiError> => {
1064
+ // Text and reasoning blocks have no `contentBlockStart` event, so they are
1065
+ // started on their first delta.
1066
+ const textBlocks = new Set<number>()
1067
+ const reasoningBlocks = new Map<number, ReasoningBlock>()
1068
+ // Tool-use blocks in flight. Bedrock streams tool arguments as partial
1069
+ // JSON, so the fragments are accumulated here and parsed once the block
1070
+ // stops.
1071
+ const toolBlocks = new Map<number, { readonly id: string; readonly name: string; params: string }>()
1072
+
1073
+ // Captured at `messageStop`; the `finish` part is emitted at `metadata`,
1074
+ // which Bedrock sends afterwards and which carries the usage.
1075
+ let stopReason: string | null = null
1076
+
1077
+ return stream.pipe(
1078
+ Stream.mapEffect(Effect.fnUntraced(function*(event) {
1079
+ const parts: Array<Response.StreamPartEncoded> = []
1080
+
1081
+ if ("messageStart" in event) {
1082
+ parts.push(yield* responseMetadataPart(request.modelId))
1083
+ } else if ("contentBlockStart" in event) {
1084
+ // Tool-use blocks announce themselves here.
1085
+ const start = event.contentBlockStart.start?.toolUse
1086
+ if (Predicate.isNotUndefined(start)) {
1087
+ const { name, toolUseId: id } = start
1088
+ toolBlocks.set(event.contentBlockStart.contentBlockIndex, { id, name, params: "" })
1089
+ parts.push({ type: "tool-params-start", id, name })
1090
+ }
1091
+ } else if ("contentBlockDelta" in event) {
1092
+ const index = event.contentBlockDelta.contentBlockIndex
1093
+ const id = index.toString()
1094
+ const { reasoningContent, text, toolUse } = event.contentBlockDelta.delta
1095
+ if (Predicate.isNotUndefined(toolUse)) {
1096
+ const block = toolBlocks.get(index)
1097
+ // A toolUse delta without a preceding `contentBlockStart` has no
1098
+ // call id to attribute it to, so it is dropped.
1099
+ if (Predicate.isNotUndefined(block)) {
1100
+ block.params += toolUse.input
1101
+ parts.push({ type: "tool-params-delta", id: block.id, delta: toolUse.input })
694
1102
  }
695
-
696
- case "messageStop": {
697
- // Buffer the finish reason — the Bedrock Converse stream sends
698
- // `metadata` (with usage / cache / trace) AFTER `messageStop`,
699
- // so emitting the `"finish"` part here would leak the empty
700
- // `usage` defaults from the case below to the caller. Wait for
701
- // `metadata` to land and emit `"finish"` there.
702
- finishReason = InternalUtilities.resolveFinishReason(event.messageStop.stopReason)
703
- break
1103
+ } else if (Predicate.isNotUndefined(reasoningContent)) {
1104
+ let block = reasoningBlocks.get(index)
1105
+ if (Predicate.isUndefined(block)) {
1106
+ block = { signature: undefined, redactedChunks: [] }
1107
+ reasoningBlocks.set(index, block)
1108
+ parts.push({ type: "reasoning-start", id })
704
1109
  }
705
-
706
- case "contentBlockStart": {
707
- const index = event.contentBlockStart.contentBlockIndex
708
- const block = event.contentBlockStart
709
- if (Predicate.isNotUndefined(block.start.toolUse)) {
710
- const toolUse = block.start.toolUse
711
- const toolName = toolUse.name
712
- const providerTool = AnthropicTool.getProviderDefinedToolName(toolName)
713
- const name = Predicate.isNotUndefined(providerTool) ? providerTool : toolName
714
- const providerName = Predicate.isNotUndefined(providerTool) ? toolName : undefined
715
-
716
- contentBlocks[index] = {
717
- type: "tool-call",
718
- id: toolUse.toolUseId,
719
- name,
720
- params: "",
721
- providerName,
722
- providerExecuted: false
723
- }
724
- // Only emit tool param delta events for text responses
725
- if (options.responseFormat.type === "text") {
726
- parts.push({
727
- type: "tool-params-start",
728
- id: toolUse.toolUseId,
729
- name: toolUse.name,
730
- providerExecuted: false
731
- })
732
- }
733
- } else {
734
- contentBlocks[index] = { type: "text" }
735
- parts.push({
736
- type: "text-start",
737
- id: index.toString()
738
- })
739
- }
740
- break
1110
+ if (Predicate.isNotUndefined(reasoningContent.text)) {
1111
+ parts.push({ type: "reasoning-delta", id, delta: reasoningContent.text })
741
1112
  }
742
-
743
- case "contentBlockDelta": {
744
- const index = event.contentBlockDelta.contentBlockIndex
745
- const delta = event.contentBlockDelta.delta
746
-
747
- switch (delta.type) {
748
- case "text": {
749
- const block = contentBlocks[index]
750
- if (Predicate.isUndefined(block)) {
751
- contentBlocks[index] = { type: "text" }
752
- // Only emit text delta events for text responses
753
- if (options.responseFormat.type === "text") {
754
- parts.push({
755
- type: "text-start",
756
- id: index.toString()
757
- })
758
- }
759
- }
760
- // Only emit text delta events for text responses
761
- if (options.responseFormat.type === "text") {
762
- parts.push({
763
- type: "text-delta",
764
- id: index.toString(),
765
- delta: delta.text
766
- })
767
- }
768
- break
769
- }
770
-
771
- case "reasoningContent": {
772
- if ("text" in delta.reasoningContent) {
773
- const block = contentBlocks[index]
774
- if (Predicate.isUndefined(block)) {
775
- contentBlocks[index] = { type: "reasoning" }
776
- parts.push({
777
- type: "reasoning-start",
778
- id: index.toString()
779
- })
780
- }
781
- parts.push({
782
- type: "reasoning-delta",
783
- id: index.toString(),
784
- delta: delta.reasoningContent.text
785
- })
786
- } else if ("signature" in delta.reasoningContent) {
787
- parts.push({
788
- type: "reasoning-delta",
789
- id: index.toString(),
790
- delta: "",
791
- metadata: {
792
- bedrock: {
793
- type: "thinking",
794
- signature: delta.reasoningContent.signature
795
- }
796
- }
797
- })
798
- } else {
799
- parts.push({
800
- type: "reasoning-delta",
801
- id: index.toString(),
802
- delta: "",
803
- metadata: {
804
- bedrock: {
805
- type: "redacted_thinking",
806
- redactedData: delta.reasoningContent.redactedContent
807
- }
808
- }
809
- })
810
- }
811
- break
812
- }
813
-
814
- case "toolUse": {
815
- const block = contentBlocks[index]
816
- if (Predicate.isNotUndefined(block) && block.type === "tool-call") {
817
- const params = delta.toolUse.input
818
- // Only emit tool params delta events for text responses
819
- if (options.responseFormat.type === "text") {
820
- parts.push({
821
- type: "tool-params-delta",
822
- id: block.id,
823
- delta: params
824
- })
825
- }
826
- block.params += params
827
- }
828
- break
829
- }
830
- }
831
- break
832
- }
833
-
834
- case "contentBlockStop": {
835
- const index = event.contentBlockStop.contentBlockIndex
836
- const block = contentBlocks[index]
837
- if (Predicate.isNotUndefined(block)) {
838
- switch (block.type) {
839
- case "text": {
840
- // Only emit text end events for text responses
841
- if (options.responseFormat.type === "text") {
842
- parts.push({
843
- type: "text-end",
844
- id: index.toString()
845
- })
846
- }
847
- break
848
- }
849
-
850
- case "reasoning": {
851
- parts.push({
852
- type: "reasoning-end",
853
- id: index.toString()
854
- })
855
- break
856
- }
857
-
858
- case "tool-call": {
859
- // Only emit tool param events for text responses - for JSON
860
- // responses, the structured output will be emitted as text
861
- if (options.responseFormat.type === "text") {
862
- parts.push({
863
- type: "tool-params-end",
864
- id: block.id
865
- })
866
-
867
- const toolName = block.name
868
- const toolParams = block.params
869
-
870
- const params = yield* Effect.try({
871
- try: () => Tool.unsafeSecureJsonParse(toolParams),
872
- catch: (cause) =>
873
- new AiError.MalformedOutput({
874
- module: "AmazonBedrockLanguageModel",
875
- method: "makeStreamResponse",
876
- description: "Failed to securely parse tool call parameters " +
877
- `for tool '${toolName}':\nParameters: ${toolParams}`,
878
- cause
879
- })
880
- })
881
-
882
- parts.push({
883
- type: "tool-call",
884
- id: block.id,
885
- name: toolName,
886
- params,
887
- providerName: block.providerName,
888
- providerExecuted: block.providerExecuted
889
- })
890
- } else {
891
- parts.push({
892
- type: "text-start",
893
- id: index.toString()
894
- })
895
- parts.push({
896
- type: "text-delta",
897
- id: index.toString(),
898
- delta: block.params
899
- })
900
- parts.push({
901
- type: "text-end",
902
- id: index.toString()
903
- })
904
- }
905
- break
906
- }
907
- }
908
- delete contentBlocks[index]
909
- }
910
- break
1113
+ if (Predicate.isNotUndefined(reasoningContent.signature)) {
1114
+ block.signature = reasoningContent.signature
911
1115
  }
912
-
913
- case "metadata": {
914
- usage.inputTokens = event.metadata.usage.inputTokens
915
- usage.outputTokens = event.metadata.usage.outputTokens
916
- usage.totalTokens = event.metadata.usage.totalTokens
917
- usage.cachedInputTokens = event.metadata.usage.cacheReadInputTokens
918
- if (Predicate.isNotUndefined(event.metadata.usage.cacheWriteInputTokens)) {
919
- cacheWriteInputTokens = event.metadata.usage.cacheWriteInputTokens
920
- }
921
- if (Predicate.isNotUndefined(event.metadata.trace)) {
922
- trace = event.metadata.trace
923
- }
924
- // Bedrock sends `metadata` after `messageStop`, so by the time
925
- // we land here we have both the finish reason (buffered above)
926
- // and the populated usage / cache / trace. Emit the `"finish"`
927
- // part now so the caller sees real token counts on the
928
- // terminal stream event.
929
- if (Predicate.isNotUndefined(finishReason)) {
930
- parts.push({
931
- type: "finish",
932
- reason: finishReason,
933
- usage,
934
- metadata: {
935
- bedrock: { trace, usage: { cacheWriteInputTokens } }
936
- }
937
- })
938
- finishReason = undefined
1116
+ if (Predicate.isNotUndefined(reasoningContent.redactedContent)) {
1117
+ const chunk = Base64.decode(reasoningContent.redactedContent)
1118
+ if (Result.isFailure(chunk)) {
1119
+ return yield* fail(
1120
+ "makeStreamResponse",
1121
+ new AiError.InvalidResponseError({
1122
+ description: `Bedrock streamed redacted reasoning that is not base64: ${
1123
+ truncate(reasoningContent.redactedContent, 100)
1124
+ }`
1125
+ })
1126
+ )
939
1127
  }
940
- break
1128
+ block.redactedChunks.push(chunk.success)
941
1129
  }
942
-
943
- case "internalServerException": {
944
- parts.push({ type: "error", error: event.internalServerException })
945
- break
946
- }
947
-
948
- case "modelStreamErrorException": {
949
- parts.push({ type: "error", error: event.modelStreamErrorException })
950
- break
951
- }
952
-
953
- case "serviceUnavailableException": {
954
- parts.push({ type: "error", error: event.serviceUnavailableException })
955
- break
956
- }
957
-
958
- case "throttlingException": {
959
- parts.push({ type: "error", error: event.throttlingException })
960
- break
961
- }
962
-
963
- case "validationException": {
964
- parts.push({ type: "error", error: event.validationException })
965
- break
1130
+ } else if (Predicate.isNotUndefined(text)) {
1131
+ if (!textBlocks.has(index)) {
1132
+ textBlocks.add(index)
1133
+ parts.push({ type: "text-start", id })
966
1134
  }
1135
+ parts.push({ type: "text-delta", id, delta: text })
967
1136
  }
968
-
969
- return parts
970
- })),
971
- Stream.flattenIterables
972
- )
973
- }
974
- )
975
-
976
- // =============================================================================
977
- // Tool Calling
978
- // =============================================================================
979
-
980
- const prepareTools: (
981
- options: LanguageModel.ProviderOptions,
982
- config: Config.Service
983
- ) => Effect.Effect<{
984
- readonly betas: ReadonlySet<string>
985
- readonly toolConfig: Partial<typeof ToolConfiguration.Encoded>
986
- readonly additionalTools?: Record<string, unknown> | undefined
987
- }, AiError.AiError> = Effect.fnUntraced(function*(options, config) {
988
- const betas = new Set<string>()
989
-
990
- if (options.tools.length === 0) {
991
- return { toolConfig: {}, betas }
992
- }
993
-
994
- const isAnthropicModel = config.modelId!.includes("anthropic.")
995
- const userDefinedTools: Array<Tool.Any> = []
996
- const providerDefinedTools: Array<Tool.AnyProviderDefined> = []
997
- for (const tool of options.tools) {
998
- if (Tool.isUserDefined(tool)) {
999
- userDefinedTools.push(tool)
1000
- } else {
1001
- providerDefinedTools.push(tool as Tool.AnyProviderDefined)
1002
- }
1003
- }
1004
-
1005
- const hasAnthropicTools = isAnthropicModel && providerDefinedTools.length > 0
1006
-
1007
- let tools: Array<typeof AmazonBedrockTool.Encoded> = []
1008
- let additionalTools: Record<string, unknown> | undefined = undefined
1009
-
1010
- // Handle Anthropic provider-defined tools for Anthropic models on Bedrock
1011
- if (hasAnthropicTools) {
1012
- const prepared = yield* prepareAnthropicTools(options, {})
1013
-
1014
- prepared.betas.forEach((beta) => betas.add(beta))
1015
-
1016
- if (Predicate.isNotUndefined(prepared.toolChoice)) {
1017
- // For Anthropic tools on Bedrock, only the 'tool_choice' goes into
1018
- // the `additionalModelRequestFields` parameter of the request, while
1019
- // the tool definitions themselves are sent in the usual `toolConfig`
1020
- additionalTools = {
1021
- tool_choice: prepared.toolChoice
1022
- }
1023
- }
1024
-
1025
- // Handle conversion of provider-defined tools to Amazon Bedrock tool definitions
1026
- for (const providerDefinedTool of providerDefinedTools) {
1027
- tools.push({
1028
- toolSpec: {
1029
- name: providerDefinedTool.providerName,
1030
- description: Tool.getDescription(providerDefinedTool as any),
1031
- inputSchema: {
1032
- json: Tool.getJsonSchema(providerDefinedTool as any) as any
1033
- }
1137
+ // Deltas this provider does not model decode with every key undefined
1138
+ // and are skipped.
1139
+ } else if ("contentBlockStop" in event) {
1140
+ const index = event.contentBlockStop.contentBlockIndex
1141
+ const id = index.toString()
1142
+ if (textBlocks.delete(index)) {
1143
+ parts.push({ type: "text-end", id })
1034
1144
  }
1035
- })
1036
- }
1037
- }
1038
-
1039
- // Handle conversion of user-defined tools to Amazon Bedrock tool definitions
1040
- for (const tool of userDefinedTools) {
1041
- tools.push({
1042
- toolSpec: {
1043
- name: tool.name,
1044
- description: Tool.getDescription(tool as any),
1045
- inputSchema: {
1046
- json: Tool.getJsonSchema(tool as any) as any
1145
+ const reasoningBlock = reasoningBlocks.get(index)
1146
+ if (Predicate.isNotUndefined(reasoningBlock)) {
1147
+ reasoningBlocks.delete(index)
1148
+ parts.push({ type: "reasoning-end", id, metadata: { "amazon-bedrock": reasoningBlockInfo(reasoningBlock) } })
1047
1149
  }
1150
+ const block = toolBlocks.get(index)
1151
+ if (Predicate.isNotUndefined(block)) {
1152
+ toolBlocks.delete(index)
1153
+ const params = yield* Effect.try({
1154
+ // A tool taking no arguments streams no deltas at all.
1155
+ try: () => Tool.unsafeSecureJsonParse(block.params.length === 0 ? "{}" : block.params),
1156
+ catch: () =>
1157
+ fail(
1158
+ "makeStreamResponse",
1159
+ new AiError.InvalidOutputError({
1160
+ description: `Bedrock streamed input for the \`${block.name}\` tool that is not valid JSON: ` +
1161
+ truncate(block.params, 500)
1162
+ })
1163
+ )
1164
+ })
1165
+ parts.push({ type: "tool-params-end", id: block.id })
1166
+ parts.push({
1167
+ type: "tool-call",
1168
+ id: block.id,
1169
+ name: block.name,
1170
+ params: yield* decodeToolParams(tools, block.name, params),
1171
+ providerExecuted: false
1172
+ })
1173
+ }
1174
+ } else if ("messageStop" in event) {
1175
+ stopReason = event.messageStop.stopReason
1176
+ } else if ("metadata" in event) {
1177
+ const usage = makeUsage(event.metadata.usage)
1178
+ annotateResponse(span, request.modelId, stopReason, usage)
1179
+ parts.push(finishPart(
1180
+ stopReason === null ? "unknown" : InternalUtilities.resolveFinishReason(stopReason),
1181
+ stopReason,
1182
+ usage
1183
+ ))
1048
1184
  }
1049
- })
1050
- }
1185
+ // Events this provider does not model match none of the branches and
1186
+ // are ignored.
1051
1187
 
1052
- // Handle resolution of tool choice for **Amazon Bedrock** user-defined tools.
1053
- // The tool choice for Anthropic provider-defined tools is resolved above and
1054
- // inserted into the additional tool configuration object.
1055
- let toolChoice: typeof ToolChoice.Encoded | undefined = undefined
1056
- if (!hasAnthropicTools && tools.length > 0 && Predicate.isNotUndefined(options.toolChoice)) {
1057
- if (options.toolChoice === "none") {
1058
- tools.length = 0
1059
- toolChoice = undefined
1060
- } else if (options.toolChoice === "auto") {
1061
- toolChoice = { auto: {} }
1062
- } else if (options.toolChoice === "required") {
1063
- toolChoice = { any: {} }
1064
- } else if ("tool" in options.toolChoice) {
1065
- toolChoice = { tool: { name: options.toolChoice.tool } }
1066
- } else {
1067
- const allowedTools = new Set(options.toolChoice.oneOf)
1068
- tools = tools.filter((tool) => allowedTools.has(tool.toolSpec?.name))
1069
- toolChoice = options.toolChoice.mode === "auto" ? { auto: {} } : { any: {} }
1070
- }
1071
- }
1072
-
1073
- const toolConfig: Partial<typeof ToolConfiguration.Encoded> = tools.length > 0
1074
- ? { tools, toolChoice }
1075
- : {}
1076
-
1077
- return { additionalTools, betas, toolConfig }
1078
- })
1188
+ return parts
1189
+ })),
1190
+ Stream.flattenIterable
1191
+ )
1192
+ }
1079
1193
 
1080
1194
  // =============================================================================
1081
1195
  // Telemetry
1082
1196
  // =============================================================================
1083
1197
 
1084
- const annotateRequest = (
1085
- span: Span,
1086
- request: typeof ConverseRequest.Encoded
1087
- ): void => {
1198
+ const annotateRequest = (span: Span, request: typeof ConverseRequest.Encoded): void => {
1088
1199
  addGenAIAnnotations(span, {
1089
- system: "anthropic",
1200
+ provider: { name: "aws.bedrock" },
1090
1201
  operation: { name: "chat" },
1091
1202
  request: {
1092
1203
  model: request.modelId,
1204
+ maxTokens: request.inferenceConfig?.maxTokens,
1093
1205
  temperature: request.inferenceConfig?.temperature,
1094
1206
  topP: request.inferenceConfig?.topP,
1095
- maxTokens: request.inferenceConfig?.maxTokens,
1096
- stopSequences: request.inferenceConfig?.stopSequences ?? []
1207
+ stopSequences: request.inferenceConfig?.stopSequences
1097
1208
  }
1098
1209
  })
1099
1210
  }
1100
1211
 
1101
- const annotateResponse = (
1102
- span: Span,
1103
- request: typeof ConverseRequest.Encoded,
1104
- response: ConverseResponse
1105
- ): void => {
1212
+ const annotateResponse = (span: Span, modelId: string, stopReason: string | null, usage: Response.Usage): void => {
1106
1213
  addGenAIAnnotations(span, {
1107
1214
  response: {
1108
- model: request.modelId,
1109
- finishReasons: response.stopReason ? [response.stopReason] : undefined
1215
+ model: modelId,
1216
+ finishReasons: stopReason === null ? undefined : [stopReason]
1110
1217
  },
1111
1218
  usage: {
1112
- inputTokens: response.usage.inputTokens,
1113
- outputTokens: response.usage.outputTokens
1219
+ inputTokens: usage.inputTokens.total,
1220
+ outputTokens: usage.outputTokens.total
1114
1221
  }
1115
1222
  })
1116
- }
1117
-
1118
- const annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {
1119
- if (part.type === "response-metadata") {
1120
- addGenAIAnnotations(span, {
1121
- response: {
1122
- id: part.id,
1123
- model: part.modelId
1124
- }
1125
- })
1126
- }
1127
- if (part.type === "finish") {
1128
- addGenAIAnnotations(span, {
1129
- response: {
1130
- finishReasons: [part.reason]
1131
- },
1132
- usage: {
1133
- inputTokens: part.usage.inputTokens,
1134
- outputTokens: part.usage.outputTokens
1135
- }
1136
- })
1137
- }
1223
+ span.attribute("gen_ai.usage.cache_read.input_tokens", usage.inputTokens.cacheRead ?? 0)
1224
+ span.attribute("gen_ai.usage.cache_write.input_tokens", usage.inputTokens.cacheWrite ?? 0)
1138
1225
  }
1139
1226
 
1140
1227
  // =============================================================================
@@ -1158,6 +1245,10 @@ interface UserMessageGroup {
1158
1245
  readonly messages: Array<Prompt.ToolMessage | Prompt.UserMessage>
1159
1246
  }
1160
1247
 
1248
+ /**
1249
+ * Converse alternates user and assistant turns, and tool results travel in a
1250
+ * user turn, so consecutive messages of one side are merged.
1251
+ */
1161
1252
  const groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {
1162
1253
  const messages: Array<ContentGroup> = []
1163
1254
  let current: ContentGroup | undefined = undefined
@@ -1193,75 +1284,5 @@ const groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {
1193
1284
  return messages
1194
1285
  }
1195
1286
 
1196
- /**
1197
- * Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant
1198
- * responses, so we trim the final text part here if it's the last message in
1199
- * the group.
1200
- */
1201
- const trimIfLast = (
1202
- isLastGroup: boolean,
1203
- isLastMessage: boolean,
1204
- isLastPart: boolean,
1205
- text: string
1206
- ) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text
1207
-
1208
- const getCachePoint = (
1209
- part:
1210
- | Prompt.SystemMessage
1211
- | Prompt.UserMessage
1212
- | Prompt.AssistantMessage
1213
- | Prompt.ToolMessage
1214
- ): typeof CachePointBlock.Encoded | undefined => part.options.bedrock?.cachePoint
1215
-
1216
- const convertToBase64 = (data: string | Uint8Array): string =>
1217
- typeof data === "string" ? data : Encoding.encodeBase64(data)
1218
-
1219
- const DOCUMENT_MIME_TYPES: Record<string, typeof DocumentFormat.Encoded> = {
1220
- "application/pdf": "pdf",
1221
- "text/csv": "csv",
1222
- "application/msword": "doc",
1223
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
1224
- "application/vnd.ms-excel": "xls",
1225
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
1226
- "text/html": "html",
1227
- "text/plain": "txt",
1228
- "text/markdown": "md"
1229
- }
1230
-
1231
- const getDocumentFormat: (
1232
- mediaType: string
1233
- ) => Effect.Effect<typeof DocumentFormat.Encoded, AiError.AiError> = Effect.fnUntraced(
1234
- function*(mediaType) {
1235
- const format = DOCUMENT_MIME_TYPES[mediaType]
1236
-
1237
- if (Predicate.isUndefined(format)) {
1238
- return yield* new AiError.MalformedInput({
1239
- module: "AmazonBedrockLanguageModel",
1240
- method: "getDocumentFormat",
1241
- description: `Unsupported document MIME type: ${mediaType} - expected ` +
1242
- `one of: ${Object.keys(DOCUMENT_MIME_TYPES)}`
1243
- })
1244
- }
1245
-
1246
- return format
1247
- }
1248
- )
1249
-
1250
- const getImageFormat: (
1251
- mediaType: string
1252
- ) => Effect.Effect<typeof ImageFormat.Encoded, AiError.AiError> = Effect.fnUntraced(
1253
- function*(mediaType) {
1254
- const format = ImageFormat.literals.find((format) => mediaType === `image/${format}`)
1255
-
1256
- if (Predicate.isUndefined(format)) {
1257
- return yield* new AiError.MalformedInput({
1258
- module: "AmazonBedrockLanguageModel",
1259
- method: "getImageFormat",
1260
- description: `Unsupported image MIME type: ${mediaType} - expected ` +
1261
- `one of: ${ImageFormat.literals.map((format) => `image/${format}`).join(",")}`
1262
- })
1263
- }
1264
-
1265
- return format
1266
- }
1267
- )
1287
+ const truncate = (text: string, maxLength: number): string =>
1288
+ text.length > maxLength ? `${text.slice(0, maxLength)}...` : text