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