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