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