@effect/ai-amazon-bedrock 0.17.0 → 4.1.5

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 +997 -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 +957 -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
@@ -0,0 +1,997 @@
1
+ /**
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
19
+ */
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 * as Prompt from "effect/ai/Prompt";
25
+ import { addGenAIAnnotations } from "effect/ai/Telemetry";
26
+ import * as Tool from "effect/ai/Tool";
27
+ import * as Bytes from "effect/Bytes";
28
+ import * as Context from "effect/Context";
29
+ import * as DateTime from "effect/DateTime";
30
+ import * as Effect from "effect/Effect";
31
+ import * as Base64 from "effect/encoding/Base64";
32
+ import { dual } from "effect/Function";
33
+ import * as Layer from "effect/Layer";
34
+ import * as Predicate from "effect/Predicate";
35
+ import * as Result from "effect/Result";
36
+ import * as Schema from "effect/Schema";
37
+ import * as SchemaAST from "effect/SchemaAST";
38
+ import * as Stream from "effect/Stream";
39
+ import { AmazonBedrockClient } from "./AmazonBedrockClient.js";
40
+ import * as InternalUtilities from "./internal/utilities.js";
41
+ /**
42
+ * Appends the cache point a message or part requests, if any, after the blocks
43
+ * already emitted for it.
44
+ */
45
+ const pushCachePoint = (content, carrier) => {
46
+ const cachePoint = carrier.options["amazon-bedrock"]?.cachePoint;
47
+ if (!Predicate.isNullish(cachePoint)) {
48
+ content.push({
49
+ cachePoint
50
+ });
51
+ }
52
+ };
53
+ // =============================================================================
54
+ // Configuration
55
+ // =============================================================================
56
+ /**
57
+ * Per-request configuration for the Amazon Bedrock language model.
58
+ *
59
+ * **Details**
60
+ *
61
+ * Derived from `ConverseRequest`, minus the fields built from the prompt and
62
+ * the toolkit, so every other Converse request parameter is settable per
63
+ * request. That includes `additionalModelRequestFields`, which carries
64
+ * inference parameters specific to the target model, among them extended
65
+ * thinking on Anthropic models. The thinking budget is drawn from the same
66
+ * ceiling as the visible answer, so `inferenceConfig.maxTokens` must exceed
67
+ * `budget_tokens`.
68
+ *
69
+ * **Example** (Enabling extended thinking for one request)
70
+ *
71
+ * ```ts
72
+ * import { AmazonBedrockLanguageModel } from "@effect/ai-amazon-bedrock"
73
+ * import { LanguageModel } from "effect/ai"
74
+ *
75
+ * const answer = LanguageModel.generateText({
76
+ * prompt: "How many r's are in strawberry?"
77
+ * }).pipe(
78
+ * AmazonBedrockLanguageModel.withConfigOverride({
79
+ * additionalModelRequestFields: {
80
+ * thinking: { type: "enabled", budget_tokens: 1024 }
81
+ * },
82
+ * inferenceConfig: { maxTokens: 4096 }
83
+ * })
84
+ * )
85
+ * ```
86
+ *
87
+ * @stability unstable
88
+ * @category configuration
89
+ * @since 4.0.0
90
+ */
91
+ export class Config extends /*#__PURE__*/Context.Service()("@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/Config") {}
92
+ // =============================================================================
93
+ // Language Model
94
+ // =============================================================================
95
+ /**
96
+ * Creates an Amazon Bedrock model descriptor that can be provided with
97
+ * `Effect.provide`.
98
+ *
99
+ * @stability unstable
100
+ * @category constructors
101
+ * @since 4.0.0
102
+ */
103
+ export const model = (model, config) => AiModel.make("amazon-bedrock", model, layer({
104
+ model,
105
+ config
106
+ }));
107
+ /**
108
+ * Creates an Amazon Bedrock `LanguageModel` service from a model identifier
109
+ * and optional request defaults.
110
+ *
111
+ * @stability unstable
112
+ * @category constructors
113
+ * @since 4.0.0
114
+ */
115
+ export const make = /*#__PURE__*/Effect.fnUntraced(function* ({
116
+ config: providerConfig,
117
+ model
118
+ }) {
119
+ const client = yield* AmazonBedrockClient;
120
+ const makeRequest = Effect.fnUntraced(function* (options) {
121
+ const services = yield* Effect.context();
122
+ const {
123
+ outputConfig: configOutputConfig,
124
+ structuredOutputs,
125
+ ...config
126
+ } = {
127
+ ...providerConfig,
128
+ ...Context.getOrUndefined(services, Config)
129
+ };
130
+ const modelId = config.modelId ?? model;
131
+ const {
132
+ messages,
133
+ system
134
+ } = yield* prepareMessages(options);
135
+ let toolConfig = yield* prepareTools(options);
136
+ const responseFormat = options.responseFormat;
137
+ let outputConfig = configOutputConfig;
138
+ if (responseFormat.type === "json") {
139
+ const json = yield* tryJsonSchema("makeRequest", () => Tool.getJsonSchemaFromSchema(responseFormat.schema, {
140
+ transformer: toCodecAnthropic
141
+ }));
142
+ const description = SchemaAST.resolveDescription(responseFormat.schema.ast);
143
+ if (structuredOutputs === true) {
144
+ // Native structured output. The caller's own tools still go out
145
+ // alongside it.
146
+ outputConfig = {
147
+ ...outputConfig,
148
+ textFormat: {
149
+ type: "json_schema",
150
+ structure: {
151
+ jsonSchema: {
152
+ schema: JSON.stringify(json),
153
+ name: responseFormat.objectName,
154
+ ...(Predicate.isNotUndefined(description) ? {
155
+ description
156
+ } : {})
157
+ }
158
+ }
159
+ }
160
+ };
161
+ } else {
162
+ // The object tool is the only tool, and it is forced.
163
+ toolConfig = {
164
+ tools: [{
165
+ toolSpec: {
166
+ name: responseFormat.objectName,
167
+ description: description ?? "Respond with a JSON object",
168
+ inputSchema: {
169
+ json: json
170
+ }
171
+ }
172
+ }],
173
+ toolChoice: {
174
+ tool: {
175
+ name: responseFormat.objectName
176
+ }
177
+ }
178
+ };
179
+ }
180
+ }
181
+ const request = {
182
+ ...config,
183
+ modelId,
184
+ system,
185
+ messages,
186
+ ...(Predicate.isNotUndefined(outputConfig) ? {
187
+ outputConfig
188
+ } : {}),
189
+ ...(Predicate.isNotUndefined(toolConfig) ? {
190
+ toolConfig
191
+ } : {})
192
+ };
193
+ // Converse rejects `toolUse` and `toolResult` blocks in a request that
194
+ // carries no `toolConfig`, and it has no tool choice that offers tools
195
+ // while forbidding calls to them.
196
+ const hasToolBlocks = messages.some(message => message.content.some(block => Predicate.isNotUndefined(block.toolUse) || Predicate.isNotUndefined(block.toolResult)));
197
+ if (hasToolBlocks && Predicate.isUndefined(request.toolConfig)) {
198
+ return yield* invalidUserInput("makeRequest", "The prompt contains tool calls or tool results, and Converse rejects them in a request that " + "carries no tools. Pass the toolkit that produced the tool calls, with a toolChoice other than \"none\".");
199
+ }
200
+ return request;
201
+ });
202
+ return yield* LanguageModel.make({
203
+ codecTransformer: toCodecAnthropic,
204
+ generateText: Effect.fnUntraced(function* (options) {
205
+ const request = yield* makeRequest(options);
206
+ annotateRequest(options.span, request);
207
+ const response = yield* client.converse(toConverseRequest(request));
208
+ return yield* makeResponse(request, response, options);
209
+ }),
210
+ streamText: Effect.fnUntraced(function* (options) {
211
+ const request = yield* makeRequest(options);
212
+ annotateRequest(options.span, request);
213
+ return makeStreamResponse(request, client.converseStream(request), options.tools, options.span);
214
+ }, (effect, _options) => effect.pipe(Stream.unwrap))
215
+ });
216
+ });
217
+ /**
218
+ * Converse has no `streamProcessingMode`; only ConverseStream does.
219
+ */
220
+ const toConverseRequest = request => {
221
+ if (Predicate.isUndefined(request.guardrailConfig?.streamProcessingMode)) {
222
+ return request;
223
+ }
224
+ const {
225
+ streamProcessingMode: _,
226
+ ...guardrailConfig
227
+ } = request.guardrailConfig;
228
+ return {
229
+ ...request,
230
+ guardrailConfig
231
+ };
232
+ };
233
+ /**
234
+ * Creates a layer for the Amazon Bedrock language model.
235
+ *
236
+ * @stability unstable
237
+ * @category layers
238
+ * @since 4.0.0
239
+ */
240
+ export const layer = options => Layer.effect(LanguageModel.LanguageModel, make(options));
241
+ /**
242
+ * Provides config overrides for Amazon Bedrock language model operations.
243
+ *
244
+ * @stability unstable
245
+ * @category configuration
246
+ * @since 4.0.0
247
+ */
248
+ export const withConfigOverride = /*#__PURE__*/dual(2, (self, overrides) => Effect.flatMap(Effect.serviceOption(Config), config => Effect.provideService(self, Config, {
249
+ ...(config._tag === "Some" ? config.value : {}),
250
+ ...overrides
251
+ })));
252
+ // =============================================================================
253
+ // Prompt Conversion
254
+ // =============================================================================
255
+ /**
256
+ * Converse takes a format enum rather than a media type, so only the media
257
+ * types it has a format for can be sent. `image/*` is resolved to jpeg, which
258
+ * mirrors the other providers.
259
+ */
260
+ const imageFormats = {
261
+ "image/*": "jpeg",
262
+ "image/jpeg": "jpeg",
263
+ "image/png": "png",
264
+ "image/gif": "gif",
265
+ "image/webp": "webp"
266
+ };
267
+ const documentFormats = {
268
+ "application/pdf": "pdf",
269
+ "text/csv": "csv",
270
+ "application/msword": "doc",
271
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
272
+ "application/vnd.ms-excel": "xls",
273
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
274
+ "text/html": "html",
275
+ "text/plain": "txt",
276
+ "text/markdown": "md"
277
+ };
278
+ /** Matches any absolute url, so one is rejected instead of being treated as base64 data. */
279
+ const urlPattern = /^[a-z][a-z0-9+.-]*:\/\//i;
280
+ /** Matches the header of a `data:` url, up to the comma before its payload. */
281
+ const dataUrlPattern = /^data:[^,]*?(;base64)?,/i;
282
+ const fail = (method, reason) => AiError.make({
283
+ module: "AmazonBedrockLanguageModel",
284
+ method,
285
+ reason
286
+ });
287
+ const invalidUserInput = (method, description) => fail(method, new AiError.InvalidUserInputError({
288
+ description
289
+ }));
290
+ /**
291
+ * Resolves file part data into base64 bytes.
292
+ *
293
+ * **Details**
294
+ *
295
+ * String data is already base64 per `Prompt.FilePart`, so it is passed through
296
+ * untouched, and only the payload of a base64 `data:` url is sent. Converse
297
+ * does not fetch remote files, so any other url fails.
298
+ */
299
+ const fileBytes = /*#__PURE__*/Effect.fnUntraced(function* (data) {
300
+ if (data instanceof Uint8Array) {
301
+ return Base64.encode(data);
302
+ }
303
+ const string = data instanceof URL ? data.href : data;
304
+ const dataUrl = dataUrlPattern.exec(string);
305
+ if (dataUrl !== null) {
306
+ if (Predicate.isUndefined(dataUrl[1])) {
307
+ return yield* invalidUserInput("prepareMessages", `Unsupported file url '${dataUrl[0]}...' - a data url must have a base64 payload`);
308
+ }
309
+ return string.slice(dataUrl[0].length);
310
+ }
311
+ if (data instanceof URL || urlPattern.test(string)) {
312
+ return yield* invalidUserInput("prepareMessages", `Unsupported file url '${string}' - Converse does not fetch remote files, so pass the file bytes instead`);
313
+ }
314
+ return string;
315
+ });
316
+ /**
317
+ * Bedrock only accepts alphanumerics, single runs of whitespace, hyphens,
318
+ * parentheses and square brackets in a document name, so anything else is
319
+ * folded into a space. The file extension is dropped because the format is
320
+ * carried separately.
321
+ */
322
+ const documentName = (fileName, position) => {
323
+ if (Predicate.isNotUndefined(fileName)) {
324
+ const name = fileName.replace(/\.[^.]*$/, "").replace(/[^a-zA-Z0-9\s\-()[\]]/g, " ").replace(/\s+/g, " ").trim();
325
+ if (name.length > 0) {
326
+ return name;
327
+ }
328
+ }
329
+ return `document ${position}`;
330
+ };
331
+ const toolResultContent = result => {
332
+ if (typeof result === "string") {
333
+ return [{
334
+ text: result
335
+ }];
336
+ }
337
+ if (Predicate.isUndefined(result)) {
338
+ return [{
339
+ text: ""
340
+ }];
341
+ }
342
+ if (Predicate.isObject(result)) {
343
+ return [{
344
+ json: result
345
+ }];
346
+ }
347
+ return [{
348
+ text: JSON.stringify(result)
349
+ }];
350
+ };
351
+ const prepareMessages = /*#__PURE__*/Effect.fnUntraced(function* (options) {
352
+ const groups = groupMessages(options.prompt);
353
+ const system = [];
354
+ const messages = [];
355
+ // Document names must be present and distinct within a request, so
356
+ // unnamed documents are numbered across the whole conversation.
357
+ let documentCount = 0;
358
+ for (let i = 0; i < groups.length; i++) {
359
+ const group = groups[i];
360
+ const isLastGroup = i === groups.length - 1;
361
+ switch (group.type) {
362
+ case "system":
363
+ {
364
+ if (messages.length > 0) {
365
+ return yield* invalidUserInput("prepareMessages", "Multiple system messages separated by user / assistant messages");
366
+ }
367
+ for (const message of group.messages) {
368
+ system.push({
369
+ text: message.content
370
+ });
371
+ pushCachePoint(system, message);
372
+ }
373
+ break;
374
+ }
375
+ case "user":
376
+ {
377
+ const content = [];
378
+ for (const message of group.messages) {
379
+ switch (message.role) {
380
+ case "user":
381
+ {
382
+ for (const part of message.content) {
383
+ switch (part.type) {
384
+ case "text":
385
+ {
386
+ content.push({
387
+ text: part.text
388
+ });
389
+ pushCachePoint(content, part);
390
+ break;
391
+ }
392
+ case "file":
393
+ {
394
+ const imageFormat = imageFormats[part.mediaType];
395
+ const documentFormat = documentFormats[part.mediaType];
396
+ if (Predicate.isNotUndefined(imageFormat)) {
397
+ content.push({
398
+ image: {
399
+ format: imageFormat,
400
+ source: {
401
+ bytes: yield* fileBytes(part.data)
402
+ }
403
+ }
404
+ });
405
+ } else if (Predicate.isNotUndefined(documentFormat)) {
406
+ documentCount += 1;
407
+ content.push({
408
+ document: {
409
+ format: documentFormat,
410
+ name: documentName(part.fileName, documentCount),
411
+ source: {
412
+ bytes: yield* fileBytes(part.data)
413
+ }
414
+ }
415
+ });
416
+ } else {
417
+ return yield* invalidUserInput("prepareMessages", `Unsupported media type '${part.mediaType}' for file part - this provider supports the images and documents Converse has a format for`);
418
+ }
419
+ pushCachePoint(content, part);
420
+ break;
421
+ }
422
+ }
423
+ }
424
+ break;
425
+ }
426
+ case "tool":
427
+ {
428
+ for (const part of message.content) {
429
+ // Only tool-result parts map to Converse blocks; other tool
430
+ // message parts (e.g. tool-approval responses) are skipped.
431
+ if (part.type !== "tool-result") continue;
432
+ content.push({
433
+ toolResult: {
434
+ toolUseId: part.id,
435
+ content: toolResultContent(Predicate.isNotUndefined(part.modelOutput) ? Prompt.toolModelOutputToText(part.modelOutput) : part.result),
436
+ ...(part.isFailure ? {
437
+ status: "error"
438
+ } : {})
439
+ }
440
+ });
441
+ pushCachePoint(content, part);
442
+ }
443
+ break;
444
+ }
445
+ }
446
+ pushCachePoint(content, message);
447
+ }
448
+ messages.push({
449
+ role: "user",
450
+ content
451
+ });
452
+ break;
453
+ }
454
+ case "assistant":
455
+ {
456
+ const content = [];
457
+ for (let j = 0; j < group.messages.length; j++) {
458
+ const message = group.messages[j];
459
+ const isLastMessage = j === group.messages.length - 1;
460
+ for (let k = 0; k < message.content.length; k++) {
461
+ const part = message.content[k];
462
+ const isLastPart = k === message.content.length - 1;
463
+ switch (part.type) {
464
+ case "text":
465
+ {
466
+ // Skip empty text blocks
467
+ if (part.text.trim().length === 0) {
468
+ continue;
469
+ }
470
+ content.push({
471
+ // Amazon Bedrock does not allow trailing whitespace in a
472
+ // pre-filled assistant response.
473
+ text: isLastGroup && isLastMessage && isLastPart ? part.text.trim() : part.text
474
+ });
475
+ pushCachePoint(content, part);
476
+ break;
477
+ }
478
+ case "reasoning":
479
+ {
480
+ // Bedrock verifies the payload that accompanies a reasoning
481
+ // block, so a reasoning part that did not come from this
482
+ // provider carries nothing it would accept and is dropped
483
+ // rather than sent and rejected.
484
+ const info = part.options["amazon-bedrock"];
485
+ if (Predicate.isNullish(info)) {
486
+ continue;
487
+ }
488
+ if (Predicate.isNotUndefined(info.redactedContent)) {
489
+ content.push({
490
+ reasoningContent: {
491
+ redactedContent: info.redactedContent
492
+ }
493
+ });
494
+ } else {
495
+ content.push({
496
+ reasoningContent: {
497
+ reasoningText: {
498
+ text: part.text,
499
+ ...(Predicate.isNotUndefined(info.signature) ? {
500
+ signature: info.signature
501
+ } : {})
502
+ }
503
+ }
504
+ });
505
+ }
506
+ break;
507
+ }
508
+ case "tool-call":
509
+ {
510
+ if (part.providerExecuted) {
511
+ continue;
512
+ }
513
+ content.push({
514
+ toolUse: {
515
+ toolUseId: part.id,
516
+ name: part.name,
517
+ input: part.params
518
+ }
519
+ });
520
+ pushCachePoint(content, part);
521
+ break;
522
+ }
523
+ default:
524
+ {
525
+ return yield* invalidUserInput("prepareMessages", `Unsupported assistant content part of type '${part.type}' - this provider supports text, reasoning, and tool calls`);
526
+ }
527
+ }
528
+ }
529
+ pushCachePoint(content, message);
530
+ }
531
+ messages.push({
532
+ role: "assistant",
533
+ content
534
+ });
535
+ break;
536
+ }
537
+ }
538
+ }
539
+ return {
540
+ system,
541
+ messages
542
+ };
543
+ });
544
+ // =============================================================================
545
+ // Schema Helpers
546
+ // =============================================================================
547
+ const tryJsonSchema = (method, evaluate) => Effect.try({
548
+ try: evaluate,
549
+ catch: error => fail(method, new AiError.UnsupportedSchemaError({
550
+ description: error instanceof Error ? error.message : String(error)
551
+ }))
552
+ });
553
+ // Bedrock is sent each tool's codec schema, which differs from the tool's own
554
+ // schema wherever the codec rewrites a parameter. Params that follow the codec
555
+ // are re-encoded with the tool's schema for the Toolkit to decode. Any others
556
+ // are left as they are, so that the Toolkit reports the error.
557
+ const decodeToolParams = (tools, toolName, params) => {
558
+ const tool = tools.find(tool => tool.name === toolName);
559
+ if (Predicate.isUndefined(tool)) {
560
+ return Effect.succeed(params);
561
+ }
562
+ return Effect.try(() => toCodecAnthropic(tool.parametersSchema).codec).pipe(Effect.flatMap(codec => Schema.decodeUnknownEffect(codec)(params)), Effect.flatMap(decoded => Schema.encodeUnknownEffect(tool.parametersSchema)(decoded)), Effect.orElseSucceed(() => params));
563
+ };
564
+ // =============================================================================
565
+ // Tool Conversion
566
+ // =============================================================================
567
+ const prepareTools = /*#__PURE__*/Effect.fnUntraced(function* (options) {
568
+ // Converse rejects an empty `tools` array, and it has no tool choice that
569
+ // forbids tool calls.
570
+ if (options.tools.length === 0 || options.toolChoice === "none") {
571
+ return undefined;
572
+ }
573
+ const tools = [];
574
+ for (const tool of options.tools) {
575
+ // Provider-defined tools are rejected, and only they go by another name
576
+ // on the wire, so no `Tool.NameMapper` is needed.
577
+ if (!Tool.isUserDefined(tool)) {
578
+ return yield* invalidUserInput("prepareTools", `Unsupported tool '${tool.name}' - this provider supports user-defined tools only`);
579
+ }
580
+ const description = Tool.getDescription(tool);
581
+ const json = yield* tryJsonSchema("prepareTools", () => Tool.getJsonSchema(tool, {
582
+ transformer: toCodecAnthropic
583
+ }));
584
+ tools.push({
585
+ toolSpec: {
586
+ name: tool.name,
587
+ ...(Predicate.isNotUndefined(description) ? {
588
+ description
589
+ } : {}),
590
+ inputSchema: {
591
+ json: json
592
+ }
593
+ }
594
+ });
595
+ }
596
+ let toolChoice;
597
+ const choice = options.toolChoice;
598
+ if (choice === "auto") {
599
+ toolChoice = {
600
+ auto: {}
601
+ };
602
+ } else if (choice === "required") {
603
+ toolChoice = {
604
+ any: {}
605
+ };
606
+ } else if ("tool" in choice) {
607
+ toolChoice = {
608
+ tool: {
609
+ name: choice.tool
610
+ }
611
+ };
612
+ } else {
613
+ // `LanguageModel` already filters the toolkit by `toolChoice.oneOf`
614
+ // before a provider sees it, so this only picks the mode.
615
+ toolChoice = choice.mode === "required" ? {
616
+ any: {}
617
+ } : {
618
+ auto: {}
619
+ };
620
+ }
621
+ return {
622
+ tools,
623
+ toolChoice
624
+ };
625
+ });
626
+ // =============================================================================
627
+ // Response Conversion
628
+ // =============================================================================
629
+ const makeResponse = /*#__PURE__*/Effect.fnUntraced(function* (request, response, options) {
630
+ const parts = [];
631
+ // Without native structured output the object is asked for through a tool
632
+ // named after it (see `makeRequest`).
633
+ const objectToolName = options.responseFormat.type === "json" && Predicate.isUndefined(request.outputConfig?.textFormat) ? options.responseFormat.objectName : undefined;
634
+ // A model can call the object tool more than once. The first call is the
635
+ // object: joining the inputs of several calls would not be valid JSON.
636
+ const objectToolPart = Predicate.isUndefined(objectToolName) ? undefined : response.output.message.content.find(part => part.toolUse?.name === objectToolName);
637
+ const hasObjectTool = Predicate.isNotUndefined(objectToolPart);
638
+ parts.push(yield* responseMetadataPart(request.modelId));
639
+ for (const part of response.output.message.content) {
640
+ if (Predicate.isNotUndefined(part.text)) {
641
+ // With native structured output the object arrives here, as JSON text
642
+ // the LanguageModel layer decodes. When the object tool was called
643
+ // instead, prose next to it must not be concatenated into the JSON.
644
+ if (!hasObjectTool) {
645
+ parts.push({
646
+ type: "text",
647
+ text: part.text
648
+ });
649
+ }
650
+ } else if (Predicate.isNotUndefined(part.toolUse)) {
651
+ if (part.toolUse.name === objectToolName) {
652
+ // The object tool's input is the object: re-emit it as text for the
653
+ // LanguageModel layer to decode.
654
+ if (part === objectToolPart) {
655
+ parts.push({
656
+ type: "text",
657
+ text: JSON.stringify(part.toolUse.input)
658
+ });
659
+ }
660
+ continue;
661
+ }
662
+ parts.push({
663
+ type: "tool-call",
664
+ id: part.toolUse.toolUseId,
665
+ name: part.toolUse.name,
666
+ params: yield* decodeToolParams(options.tools, part.toolUse.name, part.toolUse.input),
667
+ providerExecuted: false
668
+ });
669
+ } else if (Predicate.isNotUndefined(part.reasoningContent)) {
670
+ const {
671
+ reasoningText,
672
+ redactedContent
673
+ } = part.reasoningContent;
674
+ if (Predicate.isNotUndefined(reasoningText)) {
675
+ parts.push({
676
+ type: "reasoning",
677
+ text: reasoningText.text,
678
+ metadata: {
679
+ "amazon-bedrock": Predicate.isNotUndefined(reasoningText.signature) ? {
680
+ signature: reasoningText.signature
681
+ } : {}
682
+ }
683
+ });
684
+ } else if (Predicate.isNotUndefined(redactedContent)) {
685
+ // Redacted reasoning has no readable text; the encrypted payload
686
+ // rides along in the metadata so the block can be sent back later.
687
+ parts.push({
688
+ type: "reasoning",
689
+ text: "",
690
+ metadata: {
691
+ "amazon-bedrock": {
692
+ redactedContent
693
+ }
694
+ }
695
+ });
696
+ }
697
+ }
698
+ // Blocks this provider does not model decode with every field undefined
699
+ // and are ignored.
700
+ }
701
+ const usage = makeUsage(response.usage);
702
+ annotateResponse(options.span, request.modelId, response.stopReason, usage);
703
+ // Calling the object tool is how the model finishes, not a request to run
704
+ // a tool.
705
+ parts.push(finishPart(InternalUtilities.resolveFinishReason(response.stopReason, hasObjectTool), response.stopReason, usage));
706
+ return parts;
707
+ });
708
+ /**
709
+ * Converse returns no response identifier, and the client service does not
710
+ * surface the raw HTTP request.
711
+ */
712
+ const responseMetadataPart = modelId => Effect.map(DateTime.now, now => ({
713
+ type: "response-metadata",
714
+ id: undefined,
715
+ modelId,
716
+ timestamp: DateTime.formatIso(now),
717
+ request: undefined
718
+ }));
719
+ const finishPart = (reason, stopReason, usage) => ({
720
+ type: "finish",
721
+ reason,
722
+ usage,
723
+ response: undefined,
724
+ metadata: {
725
+ "amazon-bedrock": {
726
+ stopReason
727
+ }
728
+ }
729
+ });
730
+ const makeUsage = usage => {
731
+ const cacheRead = usage.cacheReadInputTokens;
732
+ const cacheWrite = usage.cacheWriteInputTokens;
733
+ return {
734
+ inputTokens: {
735
+ uncached: usage.inputTokens,
736
+ total: usage.inputTokens + (cacheRead ?? 0) + (cacheWrite ?? 0),
737
+ cacheRead,
738
+ cacheWrite
739
+ },
740
+ outputTokens: {
741
+ total: usage.outputTokens,
742
+ text: undefined,
743
+ reasoning: undefined
744
+ }
745
+ };
746
+ };
747
+ const reasoningBlockInfo = block => ({
748
+ ...(Predicate.isNotUndefined(block.signature) ? {
749
+ signature: block.signature
750
+ } : {}),
751
+ ...(block.redactedChunks.length > 0 ? {
752
+ redactedContent: Base64.encode(Bytes.concat(block.redactedChunks))
753
+ } : {})
754
+ });
755
+ const makeStreamResponse = (request, stream, tools, span) => {
756
+ // Text and reasoning blocks have no `contentBlockStart` event, so they are
757
+ // started on their first delta.
758
+ const textBlocks = new Set();
759
+ const reasoningBlocks = new Map();
760
+ // Tool-use blocks in flight. Bedrock streams tool arguments as partial
761
+ // JSON, so the fragments are accumulated here and parsed once the block
762
+ // stops.
763
+ const toolBlocks = new Map();
764
+ // Captured at `messageStop`; the `finish` part is emitted at `metadata`,
765
+ // which Bedrock sends afterwards and which carries the usage.
766
+ let stopReason = null;
767
+ return stream.pipe(Stream.mapEffect(Effect.fnUntraced(function* (event) {
768
+ const parts = [];
769
+ if ("messageStart" in event) {
770
+ parts.push(yield* responseMetadataPart(request.modelId));
771
+ } else if ("contentBlockStart" in event) {
772
+ // Tool-use blocks announce themselves here.
773
+ const start = event.contentBlockStart.start?.toolUse;
774
+ if (Predicate.isNotUndefined(start)) {
775
+ const {
776
+ name,
777
+ toolUseId: id
778
+ } = start;
779
+ toolBlocks.set(event.contentBlockStart.contentBlockIndex, {
780
+ id,
781
+ name,
782
+ params: ""
783
+ });
784
+ parts.push({
785
+ type: "tool-params-start",
786
+ id,
787
+ name
788
+ });
789
+ }
790
+ } else if ("contentBlockDelta" in event) {
791
+ const index = event.contentBlockDelta.contentBlockIndex;
792
+ const id = index.toString();
793
+ const {
794
+ reasoningContent,
795
+ text,
796
+ toolUse
797
+ } = event.contentBlockDelta.delta;
798
+ if (Predicate.isNotUndefined(toolUse)) {
799
+ const block = toolBlocks.get(index);
800
+ // A toolUse delta without a preceding `contentBlockStart` has no
801
+ // call id to attribute it to, so it is dropped.
802
+ if (Predicate.isNotUndefined(block)) {
803
+ block.params += toolUse.input;
804
+ parts.push({
805
+ type: "tool-params-delta",
806
+ id: block.id,
807
+ delta: toolUse.input
808
+ });
809
+ }
810
+ } else if (Predicate.isNotUndefined(reasoningContent)) {
811
+ let block = reasoningBlocks.get(index);
812
+ if (Predicate.isUndefined(block)) {
813
+ block = {
814
+ signature: undefined,
815
+ redactedChunks: []
816
+ };
817
+ reasoningBlocks.set(index, block);
818
+ parts.push({
819
+ type: "reasoning-start",
820
+ id
821
+ });
822
+ }
823
+ if (Predicate.isNotUndefined(reasoningContent.text)) {
824
+ parts.push({
825
+ type: "reasoning-delta",
826
+ id,
827
+ delta: reasoningContent.text
828
+ });
829
+ }
830
+ if (Predicate.isNotUndefined(reasoningContent.signature)) {
831
+ block.signature = reasoningContent.signature;
832
+ }
833
+ if (Predicate.isNotUndefined(reasoningContent.redactedContent)) {
834
+ const chunk = Base64.decode(reasoningContent.redactedContent);
835
+ if (Result.isFailure(chunk)) {
836
+ return yield* fail("makeStreamResponse", new AiError.InvalidResponseError({
837
+ description: `Bedrock streamed redacted reasoning that is not base64: ${truncate(reasoningContent.redactedContent, 100)}`
838
+ }));
839
+ }
840
+ block.redactedChunks.push(chunk.success);
841
+ }
842
+ } else if (Predicate.isNotUndefined(text)) {
843
+ if (!textBlocks.has(index)) {
844
+ textBlocks.add(index);
845
+ parts.push({
846
+ type: "text-start",
847
+ id
848
+ });
849
+ }
850
+ parts.push({
851
+ type: "text-delta",
852
+ id,
853
+ delta: text
854
+ });
855
+ }
856
+ // Deltas this provider does not model decode with every key undefined
857
+ // and are skipped.
858
+ } else if ("contentBlockStop" in event) {
859
+ const index = event.contentBlockStop.contentBlockIndex;
860
+ const id = index.toString();
861
+ if (textBlocks.delete(index)) {
862
+ parts.push({
863
+ type: "text-end",
864
+ id
865
+ });
866
+ }
867
+ const reasoningBlock = reasoningBlocks.get(index);
868
+ if (Predicate.isNotUndefined(reasoningBlock)) {
869
+ reasoningBlocks.delete(index);
870
+ parts.push({
871
+ type: "reasoning-end",
872
+ id,
873
+ metadata: {
874
+ "amazon-bedrock": reasoningBlockInfo(reasoningBlock)
875
+ }
876
+ });
877
+ }
878
+ const block = toolBlocks.get(index);
879
+ if (Predicate.isNotUndefined(block)) {
880
+ toolBlocks.delete(index);
881
+ const params = yield* Effect.try({
882
+ // A tool taking no arguments streams no deltas at all.
883
+ try: () => Tool.unsafeSecureJsonParse(block.params.length === 0 ? "{}" : block.params),
884
+ catch: () => fail("makeStreamResponse", new AiError.InvalidOutputError({
885
+ description: `Bedrock streamed input for the \`${block.name}\` tool that is not valid JSON: ` + truncate(block.params, 500)
886
+ }))
887
+ });
888
+ parts.push({
889
+ type: "tool-params-end",
890
+ id: block.id
891
+ });
892
+ parts.push({
893
+ type: "tool-call",
894
+ id: block.id,
895
+ name: block.name,
896
+ params: yield* decodeToolParams(tools, block.name, params),
897
+ providerExecuted: false
898
+ });
899
+ }
900
+ } else if ("messageStop" in event) {
901
+ stopReason = event.messageStop.stopReason;
902
+ } else if ("metadata" in event) {
903
+ const usage = makeUsage(event.metadata.usage);
904
+ annotateResponse(span, request.modelId, stopReason, usage);
905
+ parts.push(finishPart(stopReason === null ? "unknown" : InternalUtilities.resolveFinishReason(stopReason), stopReason, usage));
906
+ }
907
+ // Events this provider does not model match none of the branches and
908
+ // are ignored.
909
+ return parts;
910
+ })), Stream.flattenIterable);
911
+ };
912
+ // =============================================================================
913
+ // Telemetry
914
+ // =============================================================================
915
+ const annotateRequest = (span, request) => {
916
+ addGenAIAnnotations(span, {
917
+ provider: {
918
+ name: "aws.bedrock"
919
+ },
920
+ operation: {
921
+ name: "chat"
922
+ },
923
+ request: {
924
+ model: request.modelId,
925
+ maxTokens: request.inferenceConfig?.maxTokens,
926
+ temperature: request.inferenceConfig?.temperature,
927
+ topP: request.inferenceConfig?.topP,
928
+ stopSequences: request.inferenceConfig?.stopSequences
929
+ }
930
+ });
931
+ };
932
+ const annotateResponse = (span, modelId, stopReason, usage) => {
933
+ addGenAIAnnotations(span, {
934
+ response: {
935
+ model: modelId,
936
+ finishReasons: stopReason === null ? undefined : [stopReason]
937
+ },
938
+ usage: {
939
+ inputTokens: usage.inputTokens.total,
940
+ outputTokens: usage.outputTokens.total
941
+ }
942
+ });
943
+ span.attribute("gen_ai.usage.cache_read.input_tokens", usage.inputTokens.cacheRead ?? 0);
944
+ span.attribute("gen_ai.usage.cache_write.input_tokens", usage.inputTokens.cacheWrite ?? 0);
945
+ };
946
+ /**
947
+ * Converse alternates user and assistant turns, and tool results travel in a
948
+ * user turn, so consecutive messages of one side are merged.
949
+ */
950
+ const groupMessages = prompt => {
951
+ const messages = [];
952
+ let current = undefined;
953
+ for (const message of prompt.content) {
954
+ switch (message.role) {
955
+ case "system":
956
+ {
957
+ if (current?.type !== "system") {
958
+ current = {
959
+ type: "system",
960
+ messages: []
961
+ };
962
+ messages.push(current);
963
+ }
964
+ current.messages.push(message);
965
+ break;
966
+ }
967
+ case "assistant":
968
+ {
969
+ if (current?.type !== "assistant") {
970
+ current = {
971
+ type: "assistant",
972
+ messages: []
973
+ };
974
+ messages.push(current);
975
+ }
976
+ current.messages.push(message);
977
+ break;
978
+ }
979
+ case "tool":
980
+ case "user":
981
+ {
982
+ if (current?.type !== "user") {
983
+ current = {
984
+ type: "user",
985
+ messages: []
986
+ };
987
+ messages.push(current);
988
+ }
989
+ current.messages.push(message);
990
+ break;
991
+ }
992
+ }
993
+ }
994
+ return messages;
995
+ };
996
+ const truncate = (text, maxLength) => text.length > maxLength ? `${text.slice(0, maxLength)}...` : text;
997
+ //# sourceMappingURL=AmazonBedrockLanguageModel.js.map