@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
|
@@ -1,351 +1,647 @@
|
|
|
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 type * 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
|
-
readonly cacheWriteInputTokens?: number | undefined
|
|
173
|
-
}
|
|
174
|
-
} | undefined
|
|
258
|
+
readonly "amazon-bedrock"?: {
|
|
259
|
+
readonly stopReason: string | null
|
|
260
|
+
} | null
|
|
175
261
|
}
|
|
176
262
|
}
|
|
177
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 })
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// =============================================================================
|
|
279
|
+
// Configuration
|
|
280
|
+
// =============================================================================
|
|
281
|
+
|
|
282
|
+
/**
|
|
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
|
+
|
|
178
352
|
// =============================================================================
|
|
179
|
-
//
|
|
353
|
+
// Language Model
|
|
180
354
|
// =============================================================================
|
|
181
355
|
|
|
182
356
|
/**
|
|
183
|
-
*
|
|
184
|
-
*
|
|
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
|
+
return [{ json: result }]
|
|
643
|
+
}
|
|
644
|
+
|
|
349
645
|
const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<{
|
|
350
646
|
readonly system: ReadonlyArray<typeof SystemContentBlock.Encoded>
|
|
351
647
|
readonly messages: ReadonlyArray<typeof Message.Encoded>
|
|
@@ -355,28 +651,25 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
|
|
|
355
651
|
|
|
356
652
|
const system: Array<typeof SystemContentBlock.Encoded> = []
|
|
357
653
|
const messages: Array<typeof Message.Encoded> = []
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
654
|
+
// Document names must be present and distinct within a request, so
|
|
655
|
+
// unnamed documents are numbered across the whole conversation.
|
|
656
|
+
let documentCount = 0
|
|
361
657
|
|
|
362
658
|
for (let i = 0; i < groups.length; i++) {
|
|
363
|
-
const group = groups[i]
|
|
659
|
+
const group = groups[i]!
|
|
364
660
|
const isLastGroup = i === groups.length - 1
|
|
365
661
|
|
|
366
662
|
switch (group.type) {
|
|
367
663
|
case "system": {
|
|
368
664
|
if (messages.length > 0) {
|
|
369
|
-
return yield*
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
})
|
|
665
|
+
return yield* invalidUserInput(
|
|
666
|
+
"prepareMessages",
|
|
667
|
+
"Multiple system messages separated by user / assistant messages"
|
|
668
|
+
)
|
|
374
669
|
}
|
|
375
670
|
for (const message of group.messages) {
|
|
376
671
|
system.push({ text: message.content })
|
|
377
|
-
|
|
378
|
-
system.push(BEDROCK_CACHE_POINT)
|
|
379
|
-
}
|
|
672
|
+
pushCachePoint(system, message)
|
|
380
673
|
}
|
|
381
674
|
break
|
|
382
675
|
}
|
|
@@ -387,40 +680,36 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
|
|
|
387
680
|
for (const message of group.messages) {
|
|
388
681
|
switch (message.role) {
|
|
389
682
|
case "user": {
|
|
390
|
-
for (
|
|
391
|
-
const part = message.content[j]
|
|
392
|
-
|
|
683
|
+
for (const part of message.content) {
|
|
393
684
|
switch (part.type) {
|
|
394
685
|
case "text": {
|
|
395
686
|
content.push({ text: part.text })
|
|
687
|
+
pushCachePoint(content, part)
|
|
396
688
|
break
|
|
397
689
|
}
|
|
398
|
-
|
|
399
690
|
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/")) {
|
|
691
|
+
const imageFormat = imageFormats[part.mediaType]
|
|
692
|
+
const documentFormat = documentFormats[part.mediaType]
|
|
693
|
+
if (Predicate.isNotUndefined(imageFormat)) {
|
|
409
694
|
content.push({
|
|
410
|
-
image: {
|
|
411
|
-
format: yield* getImageFormat(part.mediaType),
|
|
412
|
-
source: { bytes: convertToBase64(part.data) }
|
|
413
|
-
}
|
|
695
|
+
image: { format: imageFormat, source: { bytes: yield* fileBytes(part.data) } }
|
|
414
696
|
})
|
|
415
|
-
} else {
|
|
697
|
+
} else if (Predicate.isNotUndefined(documentFormat)) {
|
|
698
|
+
documentCount += 1
|
|
416
699
|
content.push({
|
|
417
700
|
document: {
|
|
418
|
-
format:
|
|
419
|
-
name:
|
|
420
|
-
source: { bytes:
|
|
701
|
+
format: documentFormat,
|
|
702
|
+
name: documentName(part.fileName, documentCount),
|
|
703
|
+
source: { bytes: yield* fileBytes(part.data) }
|
|
421
704
|
}
|
|
422
705
|
})
|
|
706
|
+
} else {
|
|
707
|
+
return yield* invalidUserInput(
|
|
708
|
+
"prepareMessages",
|
|
709
|
+
`Unsupported media type '${part.mediaType}' for file part - this provider supports the images and documents Converse has a format for`
|
|
710
|
+
)
|
|
423
711
|
}
|
|
712
|
+
pushCachePoint(content, part)
|
|
424
713
|
break
|
|
425
714
|
}
|
|
426
715
|
}
|
|
@@ -430,24 +719,25 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
|
|
|
430
719
|
|
|
431
720
|
case "tool": {
|
|
432
721
|
for (const part of message.content) {
|
|
722
|
+
// Only tool-result parts map to Converse blocks; other tool
|
|
723
|
+
// message parts (e.g. tool-approval responses) are skipped.
|
|
724
|
+
if (part.type !== "tool-result") continue
|
|
433
725
|
content.push({
|
|
434
726
|
toolResult: {
|
|
435
727
|
toolUseId: part.id,
|
|
436
|
-
content:
|
|
728
|
+
content: toolResultContent(part.result),
|
|
729
|
+
...(part.isFailure ? { status: "error" } : {})
|
|
437
730
|
}
|
|
438
731
|
})
|
|
732
|
+
pushCachePoint(content, part)
|
|
439
733
|
}
|
|
440
734
|
break
|
|
441
735
|
}
|
|
442
736
|
}
|
|
443
|
-
|
|
444
|
-
if (getCachePoint(message)) {
|
|
445
|
-
content.push(BEDROCK_CACHE_POINT)
|
|
446
|
-
}
|
|
737
|
+
pushCachePoint(content, message)
|
|
447
738
|
}
|
|
448
739
|
|
|
449
740
|
messages.push({ role: "user", content })
|
|
450
|
-
|
|
451
741
|
break
|
|
452
742
|
}
|
|
453
743
|
|
|
@@ -455,54 +745,54 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
|
|
|
455
745
|
const content: Array<typeof ContentBlock.Encoded> = []
|
|
456
746
|
|
|
457
747
|
for (let j = 0; j < group.messages.length; j++) {
|
|
458
|
-
const message = group.messages[j]
|
|
748
|
+
const message = group.messages[j]!
|
|
459
749
|
const isLastMessage = j === group.messages.length - 1
|
|
460
750
|
|
|
461
751
|
for (let k = 0; k < message.content.length; k++) {
|
|
462
|
-
const part = message.content[k]
|
|
752
|
+
const part = message.content[k]!
|
|
463
753
|
const isLastPart = k === message.content.length - 1
|
|
464
754
|
|
|
465
755
|
switch (part.type) {
|
|
466
756
|
case "text": {
|
|
467
757
|
// Skip empty text blocks
|
|
468
758
|
if (part.text.trim().length === 0) {
|
|
469
|
-
|
|
759
|
+
continue
|
|
470
760
|
}
|
|
471
761
|
content.push({
|
|
472
|
-
// Amazon Bedrock does not allow trailing whitespace in
|
|
473
|
-
// assistant
|
|
474
|
-
text:
|
|
762
|
+
// Amazon Bedrock does not allow trailing whitespace in a
|
|
763
|
+
// pre-filled assistant response.
|
|
764
|
+
text: isLastGroup && isLastMessage && isLastPart ? part.text.trim() : part.text
|
|
475
765
|
})
|
|
766
|
+
pushCachePoint(content, part)
|
|
476
767
|
break
|
|
477
768
|
}
|
|
478
|
-
|
|
479
769
|
case "reasoning": {
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
reasoningContent: {
|
|
497
|
-
redactedContent: options.redactedData
|
|
770
|
+
// Bedrock verifies the payload that accompanies a reasoning
|
|
771
|
+
// block, so a reasoning part that did not come from this
|
|
772
|
+
// provider carries nothing it would accept and is dropped
|
|
773
|
+
// rather than sent and rejected.
|
|
774
|
+
const info = part.options["amazon-bedrock"]
|
|
775
|
+
if (Predicate.isNullish(info)) {
|
|
776
|
+
continue
|
|
777
|
+
}
|
|
778
|
+
if (Predicate.isNotUndefined(info.redactedContent)) {
|
|
779
|
+
content.push({ reasoningContent: { redactedContent: info.redactedContent } })
|
|
780
|
+
} else {
|
|
781
|
+
content.push({
|
|
782
|
+
reasoningContent: {
|
|
783
|
+
reasoningText: {
|
|
784
|
+
text: part.text,
|
|
785
|
+
...(Predicate.isNotUndefined(info.signature) ? { signature: info.signature } : {})
|
|
498
786
|
}
|
|
499
|
-
}
|
|
500
|
-
}
|
|
787
|
+
}
|
|
788
|
+
})
|
|
501
789
|
}
|
|
502
790
|
break
|
|
503
791
|
}
|
|
504
|
-
|
|
505
792
|
case "tool-call": {
|
|
793
|
+
if (part.providerExecuted) {
|
|
794
|
+
continue
|
|
795
|
+
}
|
|
506
796
|
content.push({
|
|
507
797
|
toolUse: {
|
|
508
798
|
toolUseId: part.id,
|
|
@@ -510,18 +800,21 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
|
|
|
510
800
|
input: part.params
|
|
511
801
|
}
|
|
512
802
|
})
|
|
803
|
+
pushCachePoint(content, part)
|
|
513
804
|
break
|
|
514
805
|
}
|
|
806
|
+
default: {
|
|
807
|
+
return yield* invalidUserInput(
|
|
808
|
+
"prepareMessages",
|
|
809
|
+
`Unsupported assistant content part of type '${part.type}' - this provider supports text, reasoning, and tool calls`
|
|
810
|
+
)
|
|
811
|
+
}
|
|
515
812
|
}
|
|
516
813
|
}
|
|
517
|
-
|
|
518
|
-
if (getCachePoint(message)) {
|
|
519
|
-
content.push(BEDROCK_CACHE_POINT)
|
|
520
|
-
}
|
|
814
|
+
pushCachePoint(content, message)
|
|
521
815
|
}
|
|
522
816
|
|
|
523
817
|
messages.push({ role: "assistant", content })
|
|
524
|
-
|
|
525
818
|
break
|
|
526
819
|
}
|
|
527
820
|
}
|
|
@@ -531,6 +824,94 @@ const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect
|
|
|
531
824
|
}
|
|
532
825
|
)
|
|
533
826
|
|
|
827
|
+
// =============================================================================
|
|
828
|
+
// Schema Helpers
|
|
829
|
+
// =============================================================================
|
|
830
|
+
|
|
831
|
+
const tryJsonSchema = <A>(method: string, evaluate: () => A): Effect.Effect<A, AiError.AiError> =>
|
|
832
|
+
Effect.try({
|
|
833
|
+
try: evaluate,
|
|
834
|
+
catch: (error) =>
|
|
835
|
+
fail(
|
|
836
|
+
method,
|
|
837
|
+
new AiError.UnsupportedSchemaError({ description: error instanceof Error ? error.message : String(error) })
|
|
838
|
+
)
|
|
839
|
+
})
|
|
840
|
+
|
|
841
|
+
// Bedrock is sent each tool's codec schema, which differs from the tool's own
|
|
842
|
+
// schema wherever the codec rewrites a parameter. Params that follow the codec
|
|
843
|
+
// are re-encoded with the tool's schema for the Toolkit to decode. Any others
|
|
844
|
+
// are left as they are, so that the Toolkit reports the error.
|
|
845
|
+
const decodeToolParams = (
|
|
846
|
+
tools: ReadonlyArray<Tool.Any>,
|
|
847
|
+
toolName: string,
|
|
848
|
+
params: unknown
|
|
849
|
+
): Effect.Effect<unknown> => {
|
|
850
|
+
const tool = tools.find((tool) => tool.name === toolName)
|
|
851
|
+
if (Predicate.isUndefined(tool)) {
|
|
852
|
+
return Effect.succeed(params)
|
|
853
|
+
}
|
|
854
|
+
return Effect.try(() => toCodecAnthropic(tool.parametersSchema).codec).pipe(
|
|
855
|
+
Effect.flatMap((codec) => Schema.decodeUnknownEffect(codec)(params)),
|
|
856
|
+
Effect.flatMap((decoded) => Schema.encodeUnknownEffect(tool.parametersSchema)(decoded)),
|
|
857
|
+
Effect.orElseSucceed(() => params)
|
|
858
|
+
) as Effect.Effect<unknown>
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// =============================================================================
|
|
862
|
+
// Tool Conversion
|
|
863
|
+
// =============================================================================
|
|
864
|
+
|
|
865
|
+
const prepareTools: (
|
|
866
|
+
options: LanguageModel.ProviderOptions
|
|
867
|
+
) => Effect.Effect<
|
|
868
|
+
typeof ToolConfiguration.Encoded | undefined,
|
|
869
|
+
AiError.AiError
|
|
870
|
+
> = Effect.fnUntraced(function*(options) {
|
|
871
|
+
// Converse rejects an empty `tools` array, and it has no tool choice that
|
|
872
|
+
// forbids tool calls.
|
|
873
|
+
if (options.tools.length === 0 || options.toolChoice === "none") {
|
|
874
|
+
return undefined
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
const tools: Array<typeof BedrockTool.Encoded> = []
|
|
878
|
+
for (const tool of options.tools) {
|
|
879
|
+
// Provider-defined tools are rejected, and only they go by another name
|
|
880
|
+
// on the wire, so no `Tool.NameMapper` is needed.
|
|
881
|
+
if (!Tool.isUserDefined(tool)) {
|
|
882
|
+
return yield* invalidUserInput(
|
|
883
|
+
"prepareTools",
|
|
884
|
+
`Unsupported tool '${(tool as { name: string }).name}' - this provider supports user-defined tools only`
|
|
885
|
+
)
|
|
886
|
+
}
|
|
887
|
+
const description = Tool.getDescription(tool)
|
|
888
|
+
const json = yield* tryJsonSchema("prepareTools", () => Tool.getJsonSchema(tool, { transformer: toCodecAnthropic }))
|
|
889
|
+
tools.push({
|
|
890
|
+
toolSpec: {
|
|
891
|
+
name: tool.name,
|
|
892
|
+
...(Predicate.isNotUndefined(description) ? { description } : {}),
|
|
893
|
+
inputSchema: { json: json as Record<string, unknown> }
|
|
894
|
+
}
|
|
895
|
+
})
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
let toolChoice: typeof ToolChoice.Encoded
|
|
899
|
+
const choice = options.toolChoice
|
|
900
|
+
if (choice === "auto") {
|
|
901
|
+
toolChoice = { auto: {} }
|
|
902
|
+
} else if (choice === "required") {
|
|
903
|
+
toolChoice = { any: {} }
|
|
904
|
+
} else if ("tool" in choice) {
|
|
905
|
+
toolChoice = { tool: { name: choice.tool } }
|
|
906
|
+
} else {
|
|
907
|
+
// `LanguageModel` already filters the toolkit by `toolChoice.oneOf`
|
|
908
|
+
// before a provider sees it, so this only picks the mode.
|
|
909
|
+
toolChoice = choice.mode === "required" ? { any: {} } : { auto: {} }
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
return { tools, toolChoice }
|
|
913
|
+
})
|
|
914
|
+
|
|
534
915
|
// =============================================================================
|
|
535
916
|
// Response Conversion
|
|
536
917
|
// =============================================================================
|
|
@@ -539,602 +920,308 @@ const makeResponse: (
|
|
|
539
920
|
request: typeof ConverseRequest.Encoded,
|
|
540
921
|
response: ConverseResponse,
|
|
541
922
|
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
|
-
})
|
|
923
|
+
) => Effect.Effect<Array<Response.PartEncoded>, AiError.AiError> = Effect.fnUntraced(
|
|
924
|
+
function*(request, response, options) {
|
|
925
|
+
const parts: Array<Response.PartEncoded> = []
|
|
926
|
+
// Without native structured output the object is asked for through a tool
|
|
927
|
+
// named after it (see `makeRequest`).
|
|
928
|
+
const objectToolName = options.responseFormat.type === "json" &&
|
|
929
|
+
Predicate.isUndefined(request.outputConfig?.textFormat)
|
|
930
|
+
? options.responseFormat.objectName
|
|
931
|
+
: undefined
|
|
932
|
+
// A model can call the object tool more than once. The first call is the
|
|
933
|
+
// object: joining the inputs of several calls would not be valid JSON.
|
|
934
|
+
const objectToolPart = Predicate.isUndefined(objectToolName)
|
|
935
|
+
? undefined
|
|
936
|
+
: response.output.message.content.find((part) => part.toolUse?.name === objectToolName)
|
|
937
|
+
const hasObjectTool = Predicate.isNotUndefined(objectToolPart)
|
|
938
|
+
|
|
939
|
+
parts.push(yield* responseMetadataPart(request.modelId))
|
|
940
|
+
|
|
941
|
+
for (const part of response.output.message.content) {
|
|
942
|
+
if (Predicate.isNotUndefined(part.text)) {
|
|
943
|
+
// With native structured output the object arrives here, as JSON text
|
|
944
|
+
// the LanguageModel layer decodes. When the object tool was called
|
|
945
|
+
// instead, prose next to it must not be concatenated into the JSON.
|
|
946
|
+
if (!hasObjectTool) {
|
|
947
|
+
parts.push({ type: "text", text: part.text })
|
|
567
948
|
}
|
|
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
|
-
})
|
|
949
|
+
} else if (Predicate.isNotUndefined(part.toolUse)) {
|
|
950
|
+
if (part.toolUse.name === objectToolName) {
|
|
951
|
+
// The object tool's input is the object: re-emit it as text for the
|
|
952
|
+
// LanguageModel layer to decode.
|
|
953
|
+
if (part === objectToolPart) {
|
|
954
|
+
parts.push({ type: "text", text: JSON.stringify(part.toolUse.input) })
|
|
955
|
+
}
|
|
956
|
+
continue
|
|
581
957
|
}
|
|
582
|
-
|
|
958
|
+
parts.push({
|
|
959
|
+
type: "tool-call",
|
|
960
|
+
id: part.toolUse.toolUseId,
|
|
961
|
+
name: part.toolUse.name,
|
|
962
|
+
params: yield* decodeToolParams(options.tools, part.toolUse.name, part.toolUse.input),
|
|
963
|
+
providerExecuted: false
|
|
964
|
+
})
|
|
965
|
+
} else if (Predicate.isNotUndefined(part.reasoningContent)) {
|
|
966
|
+
const { reasoningText, redactedContent } = part.reasoningContent
|
|
967
|
+
if (Predicate.isNotUndefined(reasoningText)) {
|
|
583
968
|
parts.push({
|
|
584
969
|
type: "reasoning",
|
|
585
|
-
text:
|
|
970
|
+
text: reasoningText.text,
|
|
586
971
|
metadata: {
|
|
587
|
-
bedrock:
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
}
|
|
972
|
+
"amazon-bedrock": Predicate.isNotUndefined(reasoningText.signature)
|
|
973
|
+
? { signature: reasoningText.signature }
|
|
974
|
+
: {}
|
|
591
975
|
}
|
|
592
976
|
})
|
|
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") {
|
|
977
|
+
} else if (Predicate.isNotUndefined(redactedContent)) {
|
|
978
|
+
// Redacted reasoning has no readable text; the encrypted payload
|
|
979
|
+
// rides along in the metadata so the block can be sent back later.
|
|
601
980
|
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
|
|
981
|
+
type: "reasoning",
|
|
982
|
+
text: "",
|
|
983
|
+
metadata: { "amazon-bedrock": { redactedContent } }
|
|
616
984
|
})
|
|
617
985
|
}
|
|
618
|
-
break
|
|
619
986
|
}
|
|
987
|
+
// Blocks this provider does not model decode with every field undefined
|
|
988
|
+
// and are ignored.
|
|
620
989
|
}
|
|
621
|
-
}
|
|
622
990
|
|
|
623
|
-
|
|
991
|
+
const usage = makeUsage(response.usage)
|
|
992
|
+
annotateResponse(options.span, request.modelId, response.stopReason, usage)
|
|
993
|
+
// Calling the object tool is how the model finishes, not a request to run
|
|
994
|
+
// a tool.
|
|
995
|
+
parts.push(
|
|
996
|
+
finishPart(InternalUtilities.resolveFinishReason(response.stopReason, hasObjectTool), response.stopReason, usage)
|
|
997
|
+
)
|
|
624
998
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
999
|
+
return parts
|
|
1000
|
+
}
|
|
1001
|
+
)
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* Converse returns no response identifier, and the client service does not
|
|
1005
|
+
* surface the raw HTTP request.
|
|
1006
|
+
*/
|
|
1007
|
+
const responseMetadataPart = (modelId: string) =>
|
|
1008
|
+
Effect.map(DateTime.now, (now) => ({
|
|
1009
|
+
type: "response-metadata",
|
|
1010
|
+
id: undefined,
|
|
1011
|
+
modelId,
|
|
1012
|
+
timestamp: DateTime.formatIso(now),
|
|
1013
|
+
request: undefined
|
|
1014
|
+
} as const))
|
|
1015
|
+
|
|
1016
|
+
const finishPart = (reason: Response.FinishReason, stopReason: string | null, usage: Response.Usage) => ({
|
|
1017
|
+
type: "finish",
|
|
1018
|
+
reason,
|
|
1019
|
+
usage,
|
|
1020
|
+
response: undefined,
|
|
1021
|
+
metadata: { "amazon-bedrock": { stopReason } }
|
|
1022
|
+
} as const)
|
|
1023
|
+
|
|
1024
|
+
const makeUsage = (usage: TokenUsage): Response.Usage => {
|
|
1025
|
+
const cacheRead = usage.cacheReadInputTokens
|
|
1026
|
+
const cacheWrite = usage.cacheWriteInputTokens
|
|
1027
|
+
return {
|
|
1028
|
+
inputTokens: {
|
|
1029
|
+
uncached: usage.inputTokens,
|
|
1030
|
+
total: usage.inputTokens + (cacheRead ?? 0) + (cacheWrite ?? 0),
|
|
1031
|
+
cacheRead,
|
|
1032
|
+
cacheWrite
|
|
633
1033
|
},
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
}
|
|
1034
|
+
outputTokens: {
|
|
1035
|
+
total: usage.outputTokens,
|
|
1036
|
+
text: undefined,
|
|
1037
|
+
reasoning: undefined
|
|
639
1038
|
}
|
|
640
|
-
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/**
|
|
1043
|
+
* A streamed reasoning block in flight. Converse streams the signature after
|
|
1044
|
+
* the text, and redacted reasoning as several base64 chunks of one byte
|
|
1045
|
+
* sequence, each encoded on its own, so the chunks are decoded and joined
|
|
1046
|
+
* before the block's metadata is emitted.
|
|
1047
|
+
*/
|
|
1048
|
+
interface ReasoningBlock {
|
|
1049
|
+
signature: string | undefined
|
|
1050
|
+
readonly redactedChunks: Array<Uint8Array>
|
|
1051
|
+
}
|
|
641
1052
|
|
|
642
|
-
|
|
1053
|
+
const reasoningBlockInfo = (block: ReasoningBlock): ReasoningInfo => ({
|
|
1054
|
+
...(Predicate.isNotUndefined(block.signature) ? { signature: block.signature } : {}),
|
|
1055
|
+
...(block.redactedChunks.length > 0 ? { redactedContent: Base64.encode(Bytes.concat(block.redactedChunks)) } : {})
|
|
643
1056
|
})
|
|
644
1057
|
|
|
645
|
-
const makeStreamResponse
|
|
1058
|
+
const makeStreamResponse = (
|
|
646
1059
|
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
|
|
1060
|
+
stream: Stream.Stream<ConverseStreamEvent, AiError.AiError>,
|
|
1061
|
+
tools: ReadonlyArray<Tool.Any>,
|
|
1062
|
+
span: Span
|
|
1063
|
+
): Stream.Stream<Response.StreamPartEncoded, AiError.AiError> => {
|
|
1064
|
+
// Text and reasoning blocks have no `contentBlockStart` event, so they are
|
|
1065
|
+
// started on their first delta.
|
|
1066
|
+
const textBlocks = new Set<number>()
|
|
1067
|
+
const reasoningBlocks = new Map<number, ReasoningBlock>()
|
|
1068
|
+
// Tool-use blocks in flight. Bedrock streams tool arguments as partial
|
|
1069
|
+
// JSON, so the fragments are accumulated here and parsed once the block
|
|
1070
|
+
// stops.
|
|
1071
|
+
const toolBlocks = new Map<number, { readonly id: string; readonly name: string; params: string }>()
|
|
1072
|
+
|
|
1073
|
+
// Captured at `messageStop`; the `finish` part is emitted at `metadata`,
|
|
1074
|
+
// which Bedrock sends afterwards and which carries the usage.
|
|
1075
|
+
let stopReason: string | null = null
|
|
1076
|
+
|
|
1077
|
+
return stream.pipe(
|
|
1078
|
+
Stream.mapEffect(Effect.fnUntraced(function*(event) {
|
|
1079
|
+
const parts: Array<Response.StreamPartEncoded> = []
|
|
1080
|
+
|
|
1081
|
+
if ("messageStart" in event) {
|
|
1082
|
+
parts.push(yield* responseMetadataPart(request.modelId))
|
|
1083
|
+
} else if ("contentBlockStart" in event) {
|
|
1084
|
+
// Tool-use blocks announce themselves here.
|
|
1085
|
+
const start = event.contentBlockStart.start?.toolUse
|
|
1086
|
+
if (Predicate.isNotUndefined(start)) {
|
|
1087
|
+
const { name, toolUseId: id } = start
|
|
1088
|
+
toolBlocks.set(event.contentBlockStart.contentBlockIndex, { id, name, params: "" })
|
|
1089
|
+
parts.push({ type: "tool-params-start", id, name })
|
|
1090
|
+
}
|
|
1091
|
+
} else if ("contentBlockDelta" in event) {
|
|
1092
|
+
const index = event.contentBlockDelta.contentBlockIndex
|
|
1093
|
+
const id = index.toString()
|
|
1094
|
+
const { reasoningContent, text, toolUse } = event.contentBlockDelta.delta
|
|
1095
|
+
if (Predicate.isNotUndefined(toolUse)) {
|
|
1096
|
+
const block = toolBlocks.get(index)
|
|
1097
|
+
// A toolUse delta without a preceding `contentBlockStart` has no
|
|
1098
|
+
// call id to attribute it to, so it is dropped.
|
|
1099
|
+
if (Predicate.isNotUndefined(block)) {
|
|
1100
|
+
block.params += toolUse.input
|
|
1101
|
+
parts.push({ type: "tool-params-delta", id: block.id, delta: toolUse.input })
|
|
694
1102
|
}
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
// `metadata` to land and emit `"finish"` there.
|
|
702
|
-
finishReason = InternalUtilities.resolveFinishReason(event.messageStop.stopReason)
|
|
703
|
-
break
|
|
1103
|
+
} else if (Predicate.isNotUndefined(reasoningContent)) {
|
|
1104
|
+
let block = reasoningBlocks.get(index)
|
|
1105
|
+
if (Predicate.isUndefined(block)) {
|
|
1106
|
+
block = { signature: undefined, redactedChunks: [] }
|
|
1107
|
+
reasoningBlocks.set(index, block)
|
|
1108
|
+
parts.push({ type: "reasoning-start", id })
|
|
704
1109
|
}
|
|
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
|
|
1110
|
+
if (Predicate.isNotUndefined(reasoningContent.text)) {
|
|
1111
|
+
parts.push({ type: "reasoning-delta", id, delta: reasoningContent.text })
|
|
741
1112
|
}
|
|
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
|
|
1113
|
+
if (Predicate.isNotUndefined(reasoningContent.signature)) {
|
|
1114
|
+
block.signature = reasoningContent.signature
|
|
911
1115
|
}
|
|
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
|
|
1116
|
+
if (Predicate.isNotUndefined(reasoningContent.redactedContent)) {
|
|
1117
|
+
const chunk = Base64.decode(reasoningContent.redactedContent)
|
|
1118
|
+
if (Result.isFailure(chunk)) {
|
|
1119
|
+
return yield* fail(
|
|
1120
|
+
"makeStreamResponse",
|
|
1121
|
+
new AiError.InvalidResponseError({
|
|
1122
|
+
description: `Bedrock streamed redacted reasoning that is not base64: ${
|
|
1123
|
+
truncate(reasoningContent.redactedContent, 100)
|
|
1124
|
+
}`
|
|
1125
|
+
})
|
|
1126
|
+
)
|
|
939
1127
|
}
|
|
940
|
-
|
|
1128
|
+
block.redactedChunks.push(chunk.success)
|
|
941
1129
|
}
|
|
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
|
|
1130
|
+
} else if (Predicate.isNotUndefined(text)) {
|
|
1131
|
+
if (!textBlocks.has(index)) {
|
|
1132
|
+
textBlocks.add(index)
|
|
1133
|
+
parts.push({ type: "text-start", id })
|
|
966
1134
|
}
|
|
1135
|
+
parts.push({ type: "text-delta", id, delta: text })
|
|
967
1136
|
}
|
|
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
|
-
}
|
|
1137
|
+
// Deltas this provider does not model decode with every key undefined
|
|
1138
|
+
// and are skipped.
|
|
1139
|
+
} else if ("contentBlockStop" in event) {
|
|
1140
|
+
const index = event.contentBlockStop.contentBlockIndex
|
|
1141
|
+
const id = index.toString()
|
|
1142
|
+
if (textBlocks.delete(index)) {
|
|
1143
|
+
parts.push({ type: "text-end", id })
|
|
1034
1144
|
}
|
|
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
|
|
1145
|
+
const reasoningBlock = reasoningBlocks.get(index)
|
|
1146
|
+
if (Predicate.isNotUndefined(reasoningBlock)) {
|
|
1147
|
+
reasoningBlocks.delete(index)
|
|
1148
|
+
parts.push({ type: "reasoning-end", id, metadata: { "amazon-bedrock": reasoningBlockInfo(reasoningBlock) } })
|
|
1047
1149
|
}
|
|
1150
|
+
const block = toolBlocks.get(index)
|
|
1151
|
+
if (Predicate.isNotUndefined(block)) {
|
|
1152
|
+
toolBlocks.delete(index)
|
|
1153
|
+
const params = yield* Effect.try({
|
|
1154
|
+
// A tool taking no arguments streams no deltas at all.
|
|
1155
|
+
try: () => Tool.unsafeSecureJsonParse(block.params.length === 0 ? "{}" : block.params),
|
|
1156
|
+
catch: () =>
|
|
1157
|
+
fail(
|
|
1158
|
+
"makeStreamResponse",
|
|
1159
|
+
new AiError.InvalidOutputError({
|
|
1160
|
+
description: `Bedrock streamed input for the \`${block.name}\` tool that is not valid JSON: ` +
|
|
1161
|
+
truncate(block.params, 500)
|
|
1162
|
+
})
|
|
1163
|
+
)
|
|
1164
|
+
})
|
|
1165
|
+
parts.push({ type: "tool-params-end", id: block.id })
|
|
1166
|
+
parts.push({
|
|
1167
|
+
type: "tool-call",
|
|
1168
|
+
id: block.id,
|
|
1169
|
+
name: block.name,
|
|
1170
|
+
params: yield* decodeToolParams(tools, block.name, params),
|
|
1171
|
+
providerExecuted: false
|
|
1172
|
+
})
|
|
1173
|
+
}
|
|
1174
|
+
} else if ("messageStop" in event) {
|
|
1175
|
+
stopReason = event.messageStop.stopReason
|
|
1176
|
+
} else if ("metadata" in event) {
|
|
1177
|
+
const usage = makeUsage(event.metadata.usage)
|
|
1178
|
+
annotateResponse(span, request.modelId, stopReason, usage)
|
|
1179
|
+
parts.push(finishPart(
|
|
1180
|
+
stopReason === null ? "unknown" : InternalUtilities.resolveFinishReason(stopReason),
|
|
1181
|
+
stopReason,
|
|
1182
|
+
usage
|
|
1183
|
+
))
|
|
1048
1184
|
}
|
|
1049
|
-
|
|
1050
|
-
|
|
1185
|
+
// Events this provider does not model match none of the branches and
|
|
1186
|
+
// are ignored.
|
|
1051
1187
|
|
|
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
|
-
})
|
|
1188
|
+
return parts
|
|
1189
|
+
})),
|
|
1190
|
+
Stream.flattenIterable
|
|
1191
|
+
)
|
|
1192
|
+
}
|
|
1079
1193
|
|
|
1080
1194
|
// =============================================================================
|
|
1081
1195
|
// Telemetry
|
|
1082
1196
|
// =============================================================================
|
|
1083
1197
|
|
|
1084
|
-
const annotateRequest = (
|
|
1085
|
-
span: Span,
|
|
1086
|
-
request: typeof ConverseRequest.Encoded
|
|
1087
|
-
): void => {
|
|
1198
|
+
const annotateRequest = (span: Span, request: typeof ConverseRequest.Encoded): void => {
|
|
1088
1199
|
addGenAIAnnotations(span, {
|
|
1089
|
-
|
|
1200
|
+
provider: { name: "aws.bedrock" },
|
|
1090
1201
|
operation: { name: "chat" },
|
|
1091
1202
|
request: {
|
|
1092
1203
|
model: request.modelId,
|
|
1204
|
+
maxTokens: request.inferenceConfig?.maxTokens,
|
|
1093
1205
|
temperature: request.inferenceConfig?.temperature,
|
|
1094
1206
|
topP: request.inferenceConfig?.topP,
|
|
1095
|
-
|
|
1096
|
-
stopSequences: request.inferenceConfig?.stopSequences ?? []
|
|
1207
|
+
stopSequences: request.inferenceConfig?.stopSequences
|
|
1097
1208
|
}
|
|
1098
1209
|
})
|
|
1099
1210
|
}
|
|
1100
1211
|
|
|
1101
|
-
const annotateResponse = (
|
|
1102
|
-
span: Span,
|
|
1103
|
-
request: typeof ConverseRequest.Encoded,
|
|
1104
|
-
response: ConverseResponse
|
|
1105
|
-
): void => {
|
|
1212
|
+
const annotateResponse = (span: Span, modelId: string, stopReason: string | null, usage: Response.Usage): void => {
|
|
1106
1213
|
addGenAIAnnotations(span, {
|
|
1107
1214
|
response: {
|
|
1108
|
-
model:
|
|
1109
|
-
finishReasons:
|
|
1215
|
+
model: modelId,
|
|
1216
|
+
finishReasons: stopReason === null ? undefined : [stopReason]
|
|
1110
1217
|
},
|
|
1111
1218
|
usage: {
|
|
1112
|
-
inputTokens:
|
|
1113
|
-
outputTokens:
|
|
1219
|
+
inputTokens: usage.inputTokens.total,
|
|
1220
|
+
outputTokens: usage.outputTokens.total
|
|
1114
1221
|
}
|
|
1115
1222
|
})
|
|
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
|
-
}
|
|
1223
|
+
span.attribute("gen_ai.usage.cache_read.input_tokens", usage.inputTokens.cacheRead ?? 0)
|
|
1224
|
+
span.attribute("gen_ai.usage.cache_write.input_tokens", usage.inputTokens.cacheWrite ?? 0)
|
|
1138
1225
|
}
|
|
1139
1226
|
|
|
1140
1227
|
// =============================================================================
|
|
@@ -1158,6 +1245,10 @@ interface UserMessageGroup {
|
|
|
1158
1245
|
readonly messages: Array<Prompt.ToolMessage | Prompt.UserMessage>
|
|
1159
1246
|
}
|
|
1160
1247
|
|
|
1248
|
+
/**
|
|
1249
|
+
* Converse alternates user and assistant turns, and tool results travel in a
|
|
1250
|
+
* user turn, so consecutive messages of one side are merged.
|
|
1251
|
+
*/
|
|
1161
1252
|
const groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {
|
|
1162
1253
|
const messages: Array<ContentGroup> = []
|
|
1163
1254
|
let current: ContentGroup | undefined = undefined
|
|
@@ -1193,75 +1284,5 @@ const groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {
|
|
|
1193
1284
|
return messages
|
|
1194
1285
|
}
|
|
1195
1286
|
|
|
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
|
-
)
|
|
1287
|
+
const truncate = (text: string, maxLength: number): string =>
|
|
1288
|
+
text.length > maxLength ? `${text.slice(0, maxLength)}...` : text
|