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