@effect/ai-amazon-bedrock 0.6.2 → 0.7.0
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/AmazonBedrockTool/package.json +6 -0
- package/dist/cjs/AmazonBedrockClient.js +71 -145
- package/dist/cjs/AmazonBedrockClient.js.map +1 -1
- package/dist/cjs/AmazonBedrockLanguageModel.js +833 -337
- package/dist/cjs/AmazonBedrockLanguageModel.js.map +1 -1
- package/dist/cjs/AmazonBedrockSchema.js +94 -39
- package/dist/cjs/AmazonBedrockSchema.js.map +1 -1
- package/dist/cjs/AmazonBedrockTool.js +53 -0
- package/dist/cjs/AmazonBedrockTool.js.map +1 -0
- package/dist/cjs/EventStreamEncoding.js +5 -4
- package/dist/cjs/EventStreamEncoding.js.map +1 -1
- package/dist/cjs/index.js +3 -1
- package/dist/cjs/internal/utilities.js +3 -1
- package/dist/cjs/internal/utilities.js.map +1 -1
- package/dist/dts/AmazonBedrockClient.d.ts +34 -34
- package/dist/dts/AmazonBedrockClient.d.ts.map +1 -1
- package/dist/dts/AmazonBedrockLanguageModel.d.ts +72 -20
- package/dist/dts/AmazonBedrockLanguageModel.d.ts.map +1 -1
- package/dist/dts/AmazonBedrockSchema.d.ts +543 -102
- package/dist/dts/AmazonBedrockSchema.d.ts.map +1 -1
- package/dist/dts/AmazonBedrockTool.d.ts +184 -0
- package/dist/dts/AmazonBedrockTool.d.ts.map +1 -0
- package/dist/dts/EventStreamEncoding.d.ts +2 -2
- package/dist/dts/EventStreamEncoding.d.ts.map +1 -1
- package/dist/dts/index.d.ts +4 -0
- package/dist/dts/index.d.ts.map +1 -1
- package/dist/esm/AmazonBedrockClient.js +71 -144
- package/dist/esm/AmazonBedrockClient.js.map +1 -1
- package/dist/esm/AmazonBedrockLanguageModel.js +830 -333
- package/dist/esm/AmazonBedrockLanguageModel.js.map +1 -1
- package/dist/esm/AmazonBedrockSchema.js +93 -37
- package/dist/esm/AmazonBedrockSchema.js.map +1 -1
- package/dist/esm/AmazonBedrockTool.js +45 -0
- package/dist/esm/AmazonBedrockTool.js.map +1 -0
- package/dist/esm/EventStreamEncoding.js +5 -3
- package/dist/esm/EventStreamEncoding.js.map +1 -1
- package/dist/esm/index.js +4 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/internal/utilities.js +2 -0
- package/dist/esm/internal/utilities.js.map +1 -1
- package/package.json +13 -4
- package/src/AmazonBedrockClient.ts +144 -241
- package/src/AmazonBedrockLanguageModel.ts +962 -372
- package/src/AmazonBedrockSchema.ts +134 -46
- package/src/AmazonBedrockTool.ts +251 -0
- package/src/EventStreamEncoding.ts +80 -73
- package/src/index.ts +5 -0
- package/src/internal/utilities.ts +6 -3
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @since 1.0.0
|
|
3
3
|
*/
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import * as
|
|
7
|
-
import * as
|
|
8
|
-
import * as
|
|
9
|
-
import
|
|
10
|
-
import * as
|
|
4
|
+
import { prepareTools as prepareAnthropicTools } from "@effect/ai-anthropic/AnthropicLanguageModel"
|
|
5
|
+
import * as AnthropicTool from "@effect/ai-anthropic/AnthropicTool"
|
|
6
|
+
import * as AiError from "@effect/ai/AiError"
|
|
7
|
+
import type * as IdGenerator from "@effect/ai/IdGenerator"
|
|
8
|
+
import * as LanguageModel from "@effect/ai/LanguageModel"
|
|
9
|
+
import * as AiModel from "@effect/ai/Model"
|
|
10
|
+
import type * as Prompt from "@effect/ai/Prompt"
|
|
11
|
+
import type * as Response from "@effect/ai/Response"
|
|
12
|
+
import { addGenAIAnnotations } from "@effect/ai/Telemetry"
|
|
13
|
+
import * as Tool from "@effect/ai/Tool"
|
|
11
14
|
import * as Context from "effect/Context"
|
|
15
|
+
import * as DateTime from "effect/DateTime"
|
|
12
16
|
import * as Effect from "effect/Effect"
|
|
13
17
|
import * as Encoding from "effect/Encoding"
|
|
14
|
-
import { dual
|
|
18
|
+
import { dual } from "effect/Function"
|
|
15
19
|
import * as Layer from "effect/Layer"
|
|
16
|
-
import * as Option from "effect/Option"
|
|
17
20
|
import * as Predicate from "effect/Predicate"
|
|
18
21
|
import * as Stream from "effect/Stream"
|
|
19
22
|
import type { Span } from "effect/Tracer"
|
|
@@ -21,20 +24,25 @@ import type { Mutable, Simplify } from "effect/Types"
|
|
|
21
24
|
import { AmazonBedrockClient } from "./AmazonBedrockClient.js"
|
|
22
25
|
import type {
|
|
23
26
|
BedrockFoundationModelId,
|
|
27
|
+
CachePointBlock,
|
|
24
28
|
ContentBlock,
|
|
25
|
-
ConverseMetrics,
|
|
26
29
|
ConverseRequest,
|
|
27
30
|
ConverseResponse,
|
|
31
|
+
ConverseResponseStreamEvent,
|
|
28
32
|
ConverseTrace,
|
|
29
33
|
DocumentFormat,
|
|
30
|
-
ImageFormat,
|
|
31
34
|
Message,
|
|
32
|
-
|
|
35
|
+
SystemContentBlock,
|
|
36
|
+
Tool as AmazonBedrockTool,
|
|
37
|
+
ToolChoice,
|
|
33
38
|
ToolConfiguration
|
|
34
39
|
} from "./AmazonBedrockSchema.js"
|
|
40
|
+
import { ImageFormat } from "./AmazonBedrockSchema.js"
|
|
35
41
|
import * as InternalUtilities from "./internal/utilities.js"
|
|
36
42
|
|
|
37
|
-
const
|
|
43
|
+
const BEDROCK_CACHE_POINT: {
|
|
44
|
+
readonly cachePoint: typeof CachePointBlock.Encoded
|
|
45
|
+
} = { cachePoint: { type: "default" } }
|
|
38
46
|
|
|
39
47
|
/**
|
|
40
48
|
* @since 1.0.0
|
|
@@ -83,30 +91,87 @@ export declare namespace Config {
|
|
|
83
91
|
}
|
|
84
92
|
|
|
85
93
|
// =============================================================================
|
|
86
|
-
// Amazon Bedrock Provider Metadata
|
|
94
|
+
// Amazon Bedrock Provider Options / Metadata
|
|
87
95
|
// =============================================================================
|
|
88
96
|
|
|
89
97
|
/**
|
|
90
98
|
* @since 1.0.0
|
|
91
|
-
* @category
|
|
99
|
+
* @category Provider Options
|
|
92
100
|
*/
|
|
93
|
-
export
|
|
94
|
-
|
|
95
|
-
ProviderMetadata.Service
|
|
96
|
-
>() {}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* @since 1.0.0
|
|
100
|
-
*/
|
|
101
|
-
export declare namespace ProviderMetadata {
|
|
101
|
+
export type AmazonBedrockReasoningInfo = {
|
|
102
|
+
readonly type: "thinking"
|
|
102
103
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
104
|
+
* Thinking content as an encrypted string, which is used to verify
|
|
105
|
+
* that thinking content was indeed generated by Amazon Bedrock's API.
|
|
106
|
+
*/
|
|
107
|
+
readonly signature: string
|
|
108
|
+
} | {
|
|
109
|
+
readonly type: "redacted_thinking"
|
|
110
|
+
/**
|
|
111
|
+
* Thinking content which was flagged by Amazon Bedrock's safety systems, and
|
|
112
|
+
* was therefore encrypted.
|
|
105
113
|
*/
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
114
|
+
readonly redactedData: string
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
declare module "@effect/ai/Prompt" {
|
|
118
|
+
export interface SystemMessageOptions extends ProviderOptions {
|
|
119
|
+
readonly bedrock?: {
|
|
120
|
+
/**
|
|
121
|
+
* Defines a section of content to be cached for reuse in subsequent API
|
|
122
|
+
* calls.
|
|
123
|
+
*/
|
|
124
|
+
readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
|
|
125
|
+
} | undefined
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface UserMessageOptions extends ProviderOptions {
|
|
129
|
+
readonly bedrock?: {
|
|
130
|
+
/**
|
|
131
|
+
* Defines a section of content to be cached for reuse in subsequent API
|
|
132
|
+
* calls.
|
|
133
|
+
*/
|
|
134
|
+
readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
|
|
135
|
+
} | undefined
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface AssistantMessageOptions extends ProviderOptions {
|
|
139
|
+
readonly bedrock?: {
|
|
140
|
+
/**
|
|
141
|
+
* Defines a section of content to be cached for reuse in subsequent API
|
|
142
|
+
* calls.
|
|
143
|
+
*/
|
|
144
|
+
readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
|
|
145
|
+
} | undefined
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface ToolMessageOptions extends ProviderOptions {
|
|
149
|
+
readonly bedrock?: {
|
|
150
|
+
/**
|
|
151
|
+
* Defines a section of content to be cached for reuse in subsequent API
|
|
152
|
+
* calls.
|
|
153
|
+
*/
|
|
154
|
+
readonly cachePoint?: typeof CachePointBlock.Encoded | undefined
|
|
155
|
+
} | undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface ReasoningPartOptions extends ProviderOptions {
|
|
159
|
+
readonly bedrock?: AmazonBedrockReasoningInfo | undefined
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
declare module "@effect/ai/Response" {
|
|
164
|
+
export interface ReasoningPartMetadata extends ProviderMetadata {
|
|
165
|
+
readonly bedrock?: AmazonBedrockReasoningInfo | undefined
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface FinishPartMetadata extends ProviderMetadata {
|
|
169
|
+
readonly bedrock?: {
|
|
170
|
+
readonly trace?: ConverseTrace | undefined
|
|
171
|
+
readonly usage: {
|
|
172
|
+
readonly cacheWriteInputTokens?: number | undefined
|
|
173
|
+
}
|
|
174
|
+
} | undefined
|
|
110
175
|
}
|
|
111
176
|
}
|
|
112
177
|
|
|
@@ -121,7 +186,8 @@ export declare namespace ProviderMetadata {
|
|
|
121
186
|
export const model = (
|
|
122
187
|
model: (string & {}) | Model,
|
|
123
188
|
config?: Omit<Config.Service, "model">
|
|
124
|
-
): AiModel.
|
|
189
|
+
): AiModel.Model<"amazon-bedrock", LanguageModel.LanguageModel, AmazonBedrockClient> =>
|
|
190
|
+
AiModel.make("amazon-bedrock", layer({ model, config }))
|
|
125
191
|
|
|
126
192
|
/**
|
|
127
193
|
* @since 1.0.0
|
|
@@ -133,101 +199,86 @@ export const make = Effect.fnUntraced(function*(options: {
|
|
|
133
199
|
}) {
|
|
134
200
|
const client = yield* AmazonBedrockClient
|
|
135
201
|
|
|
136
|
-
const makeToolConfig = (options: {
|
|
137
|
-
readonly toolChoice: AiLanguageModel.AiLanguageModelOptions["toolChoice"]
|
|
138
|
-
readonly tools: AiLanguageModel.AiLanguageModelOptions["tools"]
|
|
139
|
-
}): typeof ToolConfiguration.Encoded | undefined => {
|
|
140
|
-
if (options.tools.length === 0) return undefined
|
|
141
|
-
const isStructured = options.tools.length === 1 && options.tools[0].structured
|
|
142
|
-
const tools = options.tools.map((tool) => ({
|
|
143
|
-
toolSpec: {
|
|
144
|
-
name: tool.name,
|
|
145
|
-
description: tool.description,
|
|
146
|
-
inputSchema: { json: tool.parameters }
|
|
147
|
-
}
|
|
148
|
-
}))
|
|
149
|
-
const toolConfig: Mutable<typeof ToolConfiguration.Encoded> = { tools } as any
|
|
150
|
-
if (isStructured) {
|
|
151
|
-
toolConfig.toolChoice = { tool: { name: options.tools[0].name } }
|
|
152
|
-
return toolConfig
|
|
153
|
-
}
|
|
154
|
-
if (options.toolChoice === "auto") {
|
|
155
|
-
toolConfig.toolChoice = { auto: {} }
|
|
156
|
-
} else if (options.toolChoice === "none") {
|
|
157
|
-
toolConfig.toolChoice = undefined
|
|
158
|
-
} else if (options.toolChoice === "required") {
|
|
159
|
-
toolConfig.toolChoice = { any: {} }
|
|
160
|
-
} else {
|
|
161
|
-
toolConfig.toolChoice = { tool: { name: options.toolChoice.tool } }
|
|
162
|
-
}
|
|
163
|
-
return toolConfig
|
|
164
|
-
}
|
|
165
|
-
|
|
166
202
|
const makeRequest = Effect.fnUntraced(
|
|
167
|
-
function*(
|
|
203
|
+
function*(providerOptions: LanguageModel.ProviderOptions) {
|
|
168
204
|
const context = yield* Effect.context<never>()
|
|
169
|
-
const
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
...
|
|
175
|
-
|
|
176
|
-
system: system.pipe(
|
|
177
|
-
Option.map((text) => [{ text }]),
|
|
178
|
-
Option.getOrUndefined
|
|
179
|
-
),
|
|
205
|
+
const config = { modelId: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }
|
|
206
|
+
const { messages, system } = yield* prepareMessages(providerOptions)
|
|
207
|
+
const { additionalTools, betas, toolConfig } = yield* prepareTools(providerOptions, config)
|
|
208
|
+
const responseFormat = providerOptions.responseFormat
|
|
209
|
+
const request: typeof ConverseRequest.Encoded = {
|
|
210
|
+
...config,
|
|
211
|
+
system,
|
|
180
212
|
messages,
|
|
181
|
-
|
|
182
|
-
|
|
213
|
+
// Handle tool configuration
|
|
214
|
+
...(responseFormat.type === "json"
|
|
215
|
+
? {
|
|
216
|
+
toolConfig: {
|
|
217
|
+
tools: [{
|
|
218
|
+
toolSpec: {
|
|
219
|
+
name: responseFormat.objectName,
|
|
220
|
+
description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ??
|
|
221
|
+
"Respond with a JSON object",
|
|
222
|
+
inputSchema: {
|
|
223
|
+
json: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast) as any
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}],
|
|
227
|
+
toolChoice: { tool: { name: responseFormat.objectName } }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
: Predicate.isNotUndefined(toolConfig.tools) && toolConfig.tools.length > 0
|
|
231
|
+
? { toolConfig }
|
|
232
|
+
: {}),
|
|
233
|
+
// Handle additional model request fields
|
|
234
|
+
...(Predicate.isNotUndefined(additionalTools)
|
|
235
|
+
? {
|
|
236
|
+
additionalModelRequestFields: {
|
|
237
|
+
...config.additionalModelRequestFields,
|
|
238
|
+
...additionalTools
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
: {})
|
|
242
|
+
}
|
|
243
|
+
return { betas, request }
|
|
183
244
|
}
|
|
184
245
|
)
|
|
185
246
|
|
|
186
|
-
return yield*
|
|
247
|
+
return yield* LanguageModel.make({
|
|
187
248
|
generateText: Effect.fnUntraced(
|
|
188
|
-
function*(
|
|
189
|
-
const request = yield* makeRequest(
|
|
190
|
-
annotateRequest(
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
onSome: ({ modelId }) => modelId ?? options.model
|
|
249
|
+
function*(options) {
|
|
250
|
+
const { betas, request } = yield* makeRequest(options)
|
|
251
|
+
annotateRequest(options.span, request)
|
|
252
|
+
const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined
|
|
253
|
+
const rawResponse = yield* client.converse({
|
|
254
|
+
params: { "anthropic-beta": anthropicBeta },
|
|
255
|
+
payload: request
|
|
196
256
|
})
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
},
|
|
201
|
-
Effect.catchAll((cause) =>
|
|
202
|
-
AiError.is(cause) ? cause : new AiError({
|
|
203
|
-
module: "AmazonBedrockLanguageModel",
|
|
204
|
-
method: "generateText",
|
|
205
|
-
description: "An error occurred",
|
|
206
|
-
cause
|
|
207
|
-
})
|
|
208
|
-
)
|
|
257
|
+
annotateResponse(options.span, request, rawResponse)
|
|
258
|
+
return yield* makeResponse(request, rawResponse, options)
|
|
259
|
+
}
|
|
209
260
|
),
|
|
210
|
-
streamText(
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
})
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
261
|
+
streamText: Effect.fnUntraced(
|
|
262
|
+
function*(options) {
|
|
263
|
+
const { betas, request } = yield* makeRequest(options)
|
|
264
|
+
annotateRequest(options.span, request)
|
|
265
|
+
const anthropicBeta = betas.size > 0 ? Array.from(betas).join(",") : undefined
|
|
266
|
+
const stream = client.converseStream({
|
|
267
|
+
params: { "anthropic-beta": anthropicBeta },
|
|
268
|
+
payload: request
|
|
269
|
+
})
|
|
270
|
+
return { request, stream }
|
|
271
|
+
},
|
|
272
|
+
(effect, options) =>
|
|
273
|
+
effect.pipe(
|
|
274
|
+
Effect.flatMap(({ request, stream }) => makeStreamResponse(request, stream, options)),
|
|
275
|
+
Stream.unwrap,
|
|
276
|
+
Stream.map((response) => {
|
|
277
|
+
annotateStreamResponse(options.span, response)
|
|
278
|
+
return response
|
|
279
|
+
})
|
|
228
280
|
)
|
|
229
|
-
|
|
230
|
-
}
|
|
281
|
+
)
|
|
231
282
|
})
|
|
232
283
|
})
|
|
233
284
|
|
|
@@ -238,8 +289,8 @@ export const make = Effect.fnUntraced(function*(options: {
|
|
|
238
289
|
export const layer = (options: {
|
|
239
290
|
readonly model: (string & {}) | Model
|
|
240
291
|
readonly config?: Omit<Config.Service, "model">
|
|
241
|
-
}): Layer.Layer<
|
|
242
|
-
Layer.effect(
|
|
292
|
+
}): Layer.Layer<LanguageModel.LanguageModel, never, AmazonBedrockClient> =>
|
|
293
|
+
Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))
|
|
243
294
|
|
|
244
295
|
/**
|
|
245
296
|
* @since 1.0.0
|
|
@@ -274,303 +325,710 @@ export const withConfigOverride: {
|
|
|
274
325
|
))
|
|
275
326
|
|
|
276
327
|
// =============================================================================
|
|
277
|
-
//
|
|
328
|
+
// Prompt Conversion
|
|
278
329
|
// =============================================================================
|
|
279
330
|
|
|
280
|
-
|
|
331
|
+
const prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<{
|
|
332
|
+
readonly system: ReadonlyArray<typeof SystemContentBlock.Encoded>
|
|
333
|
+
readonly messages: ReadonlyArray<typeof Message.Encoded>
|
|
334
|
+
}, AiError.AiError> = Effect.fnUntraced(
|
|
335
|
+
function*(options) {
|
|
336
|
+
const groups = groupMessages(options.prompt)
|
|
281
337
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
readonly messages: Array<AiInput.AssistantMessage>
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
interface UserMessageGroup {
|
|
288
|
-
readonly type: "user"
|
|
289
|
-
readonly messages: Array<AiInput.ToolMessage | AiInput.UserMessage>
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const groupMessages = (prompt: AiInput.AiInput): Array<MessageGroup> => {
|
|
293
|
-
const messages: Array<MessageGroup> = []
|
|
294
|
-
let current: MessageGroup | undefined = undefined
|
|
295
|
-
for (const message of prompt.messages) {
|
|
296
|
-
switch (message._tag) {
|
|
297
|
-
case "AssistantMessage": {
|
|
298
|
-
if (current?.type !== "assistant") {
|
|
299
|
-
current = { type: "assistant", messages: [] }
|
|
300
|
-
messages.push(current)
|
|
301
|
-
}
|
|
302
|
-
current.messages.push(message)
|
|
303
|
-
break
|
|
304
|
-
}
|
|
305
|
-
case "ToolMessage":
|
|
306
|
-
case "UserMessage": {
|
|
307
|
-
if (current?.type !== "user") {
|
|
308
|
-
current = { type: "user", messages: [] }
|
|
309
|
-
messages.push(current)
|
|
310
|
-
}
|
|
311
|
-
current.messages.push(message)
|
|
312
|
-
break
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
return messages
|
|
317
|
-
}
|
|
338
|
+
const system: Array<typeof SystemContentBlock.Encoded> = []
|
|
339
|
+
const messages: Array<typeof Message.Encoded> = []
|
|
318
340
|
|
|
319
|
-
let
|
|
341
|
+
let documentCounter = 0
|
|
342
|
+
const nextDocumentName = () => `document-${++documentCounter}`
|
|
320
343
|
|
|
321
|
-
const makeMessages = Effect.fnUntraced(
|
|
322
|
-
function*(method: string, prompt: AiInput.AiInput) {
|
|
323
|
-
const messages: Array<typeof Message.Encoded> = []
|
|
324
|
-
const groups = groupMessages(prompt)
|
|
325
344
|
for (let i = 0; i < groups.length; i++) {
|
|
326
345
|
const group = groups[i]
|
|
327
346
|
const isLastGroup = i === groups.length - 1
|
|
347
|
+
|
|
328
348
|
switch (group.type) {
|
|
329
|
-
case "
|
|
349
|
+
case "system": {
|
|
350
|
+
if (messages.length > 0) {
|
|
351
|
+
return yield* new AiError.MalformedInput({
|
|
352
|
+
module: "AmazonBedrockLanguageModel",
|
|
353
|
+
method: "prepareMessages",
|
|
354
|
+
description: "Multiple system messages separated by user / assistant messages"
|
|
355
|
+
})
|
|
356
|
+
}
|
|
357
|
+
for (const message of group.messages) {
|
|
358
|
+
system.push({ text: message.content })
|
|
359
|
+
if (Predicate.isNotUndefined(getCachePoint(message))) {
|
|
360
|
+
system.push(BEDROCK_CACHE_POINT)
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
break
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
case "user": {
|
|
330
367
|
const content: Array<typeof ContentBlock.Encoded> = []
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
368
|
+
|
|
369
|
+
for (const message of group.messages) {
|
|
370
|
+
switch (message.role) {
|
|
371
|
+
case "user": {
|
|
372
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
373
|
+
const part = message.content[j]
|
|
374
|
+
|
|
375
|
+
switch (part.type) {
|
|
376
|
+
case "text": {
|
|
377
|
+
content.push({ text: part.text })
|
|
378
|
+
break
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
case "file": {
|
|
382
|
+
if (part.data instanceof URL) {
|
|
383
|
+
// TODO(Max): support this
|
|
384
|
+
return yield* new AiError.MalformedInput({
|
|
385
|
+
module: "AmazonBedrockLanguageModel",
|
|
386
|
+
method: "makeMessages",
|
|
387
|
+
description: "File URL inputs are not supported at this time"
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
if (part.mediaType.startsWith("image/")) {
|
|
391
|
+
content.push({
|
|
392
|
+
image: {
|
|
393
|
+
format: yield* getImageFormat(part.mediaType),
|
|
394
|
+
source: { bytes: convertToBase64(part.data) }
|
|
395
|
+
}
|
|
396
|
+
})
|
|
397
|
+
} else {
|
|
398
|
+
content.push({
|
|
399
|
+
document: {
|
|
400
|
+
format: yield* getDocumentFormat(part.mediaType),
|
|
401
|
+
name: nextDocumentName(),
|
|
402
|
+
source: { bytes: convertToBase64(part.data) }
|
|
403
|
+
}
|
|
404
|
+
})
|
|
360
405
|
}
|
|
406
|
+
break
|
|
361
407
|
}
|
|
362
|
-
}
|
|
363
|
-
break
|
|
364
|
-
}
|
|
365
|
-
case "RedactedReasoningPart": {
|
|
366
|
-
const redactedContent = Encoding.encodeBase64(part.redactedText)
|
|
367
|
-
content.push({ reasoningContent: { redactedContent } })
|
|
368
|
-
break
|
|
408
|
+
}
|
|
369
409
|
}
|
|
370
|
-
|
|
410
|
+
break
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
case "tool": {
|
|
414
|
+
for (const part of message.content) {
|
|
371
415
|
content.push({
|
|
372
|
-
|
|
416
|
+
toolResult: {
|
|
373
417
|
toolUseId: part.id,
|
|
374
|
-
|
|
375
|
-
input: part.params
|
|
418
|
+
content: [{ text: JSON.stringify(part.result) }]
|
|
376
419
|
}
|
|
377
420
|
})
|
|
378
|
-
break
|
|
379
421
|
}
|
|
422
|
+
break
|
|
380
423
|
}
|
|
381
424
|
}
|
|
382
425
|
}
|
|
383
|
-
|
|
426
|
+
|
|
427
|
+
messages.push({ role: "user", content })
|
|
428
|
+
|
|
384
429
|
break
|
|
385
430
|
}
|
|
386
|
-
|
|
431
|
+
|
|
432
|
+
case "assistant": {
|
|
387
433
|
const content: Array<typeof ContentBlock.Encoded> = []
|
|
434
|
+
|
|
388
435
|
for (let j = 0; j < group.messages.length; j++) {
|
|
389
436
|
const message = group.messages[j]
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
437
|
+
const isLastMessage = j === group.messages.length - 1
|
|
438
|
+
|
|
439
|
+
for (let k = 0; k < message.content.length; k++) {
|
|
440
|
+
const part = message.content[k]
|
|
441
|
+
const isLastPart = k === message.content.length - 1
|
|
442
|
+
|
|
443
|
+
switch (part.type) {
|
|
444
|
+
case "text": {
|
|
445
|
+
// Skip empty text blocks
|
|
446
|
+
if (part.text.trim().length === 0) {
|
|
447
|
+
break
|
|
448
|
+
}
|
|
395
449
|
content.push({
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
450
|
+
// Amazon Bedrock does not allow trailing whitespace in
|
|
451
|
+
// assistant content blocks
|
|
452
|
+
text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text)
|
|
400
453
|
})
|
|
454
|
+
break
|
|
401
455
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
switch (part._tag) {
|
|
408
|
-
case "FilePart": {
|
|
409
|
-
if (Predicate.isUndefined(part.mediaType)) {
|
|
410
|
-
return yield* new AiError({
|
|
411
|
-
module: "AmazonBedrockLanguageModel",
|
|
412
|
-
method,
|
|
413
|
-
description: "No media type specified for image"
|
|
414
|
-
})
|
|
415
|
-
}
|
|
456
|
+
|
|
457
|
+
case "reasoning": {
|
|
458
|
+
const options = part.options.bedrock
|
|
459
|
+
if (Predicate.isNotUndefined(options)) {
|
|
460
|
+
if (options.type === "thinking") {
|
|
416
461
|
content.push({
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
462
|
+
reasoningContent: {
|
|
463
|
+
reasoningText: {
|
|
464
|
+
// Amazon Bedrock does not allow trailing whitespace in
|
|
465
|
+
// assistant content blocks
|
|
466
|
+
text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text),
|
|
467
|
+
signature: options.signature
|
|
422
468
|
}
|
|
423
469
|
}
|
|
424
470
|
})
|
|
425
|
-
break
|
|
426
471
|
}
|
|
427
|
-
|
|
428
|
-
// TODO: maybe auto-download images from URL
|
|
429
|
-
return yield* new AiError({
|
|
430
|
-
module: "AmazonBedrockLanguageModel",
|
|
431
|
-
method,
|
|
432
|
-
description: "File URLs are not supported at this time"
|
|
433
|
-
})
|
|
434
|
-
}
|
|
435
|
-
case "ImagePart": {
|
|
436
|
-
if (Predicate.isUndefined(part.mediaType)) {
|
|
437
|
-
return yield* new AiError({
|
|
438
|
-
module: "AmazonBedrockLanguageModel",
|
|
439
|
-
method,
|
|
440
|
-
description: "No media type specified for image"
|
|
441
|
-
})
|
|
442
|
-
}
|
|
472
|
+
if (options.type === "redacted_thinking") {
|
|
443
473
|
content.push({
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
source: {
|
|
447
|
-
bytes: Encoding.encodeBase64(part.data)
|
|
448
|
-
}
|
|
474
|
+
reasoningContent: {
|
|
475
|
+
redactedContent: options.redactedData
|
|
449
476
|
}
|
|
450
477
|
})
|
|
451
|
-
break
|
|
452
|
-
}
|
|
453
|
-
case "ImageUrlPart": {
|
|
454
|
-
// TODO: maybe auto-download images from URL
|
|
455
|
-
return yield* new AiError({
|
|
456
|
-
module: "AmazonBedrockLanguageModel",
|
|
457
|
-
method,
|
|
458
|
-
description: "Image URLs are not supported at this time"
|
|
459
|
-
})
|
|
460
|
-
}
|
|
461
|
-
case "TextPart": {
|
|
462
|
-
content.push({
|
|
463
|
-
text: part.text
|
|
464
|
-
})
|
|
465
|
-
break
|
|
466
478
|
}
|
|
467
479
|
}
|
|
480
|
+
break
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
case "tool-call": {
|
|
484
|
+
content.push({
|
|
485
|
+
toolUse: {
|
|
486
|
+
toolUseId: part.id,
|
|
487
|
+
name: part.name,
|
|
488
|
+
input: part.params
|
|
489
|
+
}
|
|
490
|
+
})
|
|
491
|
+
break
|
|
468
492
|
}
|
|
469
|
-
break
|
|
470
493
|
}
|
|
471
494
|
}
|
|
495
|
+
|
|
496
|
+
if (getCachePoint(message)) {
|
|
497
|
+
content.push(BEDROCK_CACHE_POINT)
|
|
498
|
+
}
|
|
472
499
|
}
|
|
473
|
-
|
|
500
|
+
|
|
501
|
+
messages.push({ role: "assistant", content })
|
|
502
|
+
|
|
474
503
|
break
|
|
475
504
|
}
|
|
476
505
|
}
|
|
477
506
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
}
|
|
481
|
-
return yield* new AiError({
|
|
482
|
-
module: "AmazonBedrockLanguageModel",
|
|
483
|
-
method,
|
|
484
|
-
description: "Prompt contained no messages"
|
|
485
|
-
})
|
|
507
|
+
|
|
508
|
+
return { system, messages }
|
|
486
509
|
}
|
|
487
510
|
)
|
|
488
511
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
)
|
|
521
|
-
for (const part of response.output.message.content) {
|
|
522
|
-
if ("text" in part) {
|
|
523
|
-
parts.push(
|
|
524
|
-
new AiResponse.TextPart({
|
|
512
|
+
// =============================================================================
|
|
513
|
+
// Response Conversion
|
|
514
|
+
// =============================================================================
|
|
515
|
+
|
|
516
|
+
const makeResponse: (
|
|
517
|
+
request: typeof ConverseRequest.Encoded,
|
|
518
|
+
response: ConverseResponse,
|
|
519
|
+
options: LanguageModel.ProviderOptions
|
|
520
|
+
) => Effect.Effect<
|
|
521
|
+
Array<Response.PartEncoded>,
|
|
522
|
+
never,
|
|
523
|
+
IdGenerator.IdGenerator
|
|
524
|
+
> = Effect.fnUntraced(function*(request, response, options) {
|
|
525
|
+
const parts: Array<Response.PartEncoded> = []
|
|
526
|
+
|
|
527
|
+
parts.push({
|
|
528
|
+
type: "response-metadata",
|
|
529
|
+
modelId: request.modelId,
|
|
530
|
+
timestamp: DateTime.formatIso(yield* DateTime.now)
|
|
531
|
+
})
|
|
532
|
+
|
|
533
|
+
for (const part of response.output.message.content) {
|
|
534
|
+
switch (part.type) {
|
|
535
|
+
case "text": {
|
|
536
|
+
// The text parts should only be added to the response here if the
|
|
537
|
+
// response format is `"text"`. If the response format is `"json"`,
|
|
538
|
+
// then the text parts must instead be added to the response when a
|
|
539
|
+
// tool call is received.
|
|
540
|
+
if (options.responseFormat.type === "text") {
|
|
541
|
+
parts.push({
|
|
542
|
+
type: "text",
|
|
525
543
|
text: part.text
|
|
526
|
-
}
|
|
527
|
-
|
|
544
|
+
})
|
|
545
|
+
}
|
|
546
|
+
break
|
|
528
547
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
if ("
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
548
|
+
|
|
549
|
+
case "reasoningContent": {
|
|
550
|
+
if (part.reasoningContent.type === "reasoning") {
|
|
551
|
+
const signature = part.reasoningContent.reasoningText.signature
|
|
552
|
+
parts.push({
|
|
553
|
+
type: "reasoning",
|
|
554
|
+
text: part.reasoningContent.reasoningText.text,
|
|
555
|
+
metadata: Predicate.isNotUndefined(signature) ?
|
|
556
|
+
{ bedrock: { type: "thinking", signature } }
|
|
557
|
+
: undefined
|
|
558
|
+
})
|
|
538
559
|
}
|
|
539
|
-
if ("
|
|
540
|
-
parts.push(
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
560
|
+
if (part.reasoningContent.type === "redacted-reasoning") {
|
|
561
|
+
parts.push({
|
|
562
|
+
type: "reasoning",
|
|
563
|
+
text: "",
|
|
564
|
+
metadata: {
|
|
565
|
+
bedrock: {
|
|
566
|
+
type: "redacted_thinking",
|
|
567
|
+
redactedData: part.reasoningContent.redactedContent
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
})
|
|
545
571
|
}
|
|
572
|
+
break
|
|
546
573
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
574
|
+
|
|
575
|
+
case "toolUse": {
|
|
576
|
+
// When a `"json"` response format is requested, the JSON that we need
|
|
577
|
+
// will be returned by the tool call injected into the request
|
|
578
|
+
if (options.responseFormat.type === "json") {
|
|
579
|
+
parts.push({
|
|
580
|
+
type: "text",
|
|
581
|
+
text: JSON.stringify(part.toolUse.input)
|
|
582
|
+
})
|
|
583
|
+
} else {
|
|
584
|
+
const providerTool = AnthropicTool.getProviderDefinedToolName(part.toolUse.name)
|
|
585
|
+
const name = Predicate.isNotUndefined(providerTool) ? providerTool : part.toolUse.name
|
|
586
|
+
const providerName = Predicate.isNotUndefined(providerTool) ? part.toolUse.name : undefined
|
|
587
|
+
parts.push({
|
|
588
|
+
type: "tool-call",
|
|
550
589
|
id: part.toolUse.toolUseId,
|
|
551
|
-
name
|
|
552
|
-
params: part.toolUse.input
|
|
590
|
+
name,
|
|
591
|
+
params: part.toolUse.input,
|
|
592
|
+
providerName,
|
|
593
|
+
providerExecuted: false
|
|
553
594
|
})
|
|
554
|
-
|
|
595
|
+
}
|
|
596
|
+
break
|
|
555
597
|
}
|
|
556
598
|
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const finishReason = InternalUtilities.resolveFinishReason(response.stopReason)
|
|
602
|
+
|
|
603
|
+
parts.push({
|
|
604
|
+
type: "finish",
|
|
605
|
+
reason: finishReason,
|
|
606
|
+
usage: {
|
|
607
|
+
inputTokens: response.usage.inputTokens,
|
|
608
|
+
outputTokens: response.usage.outputTokens,
|
|
609
|
+
totalTokens: response.usage.totalTokens,
|
|
610
|
+
cachedInputTokens: response.usage.cacheReadInputTokens
|
|
611
|
+
},
|
|
612
|
+
metadata: {
|
|
613
|
+
bedrock: {
|
|
614
|
+
trace: response.trace,
|
|
615
|
+
usage: { cacheWriteInputTokens: response.usage.cacheWriteInputTokens }
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
})
|
|
619
|
+
|
|
620
|
+
return parts
|
|
621
|
+
})
|
|
622
|
+
|
|
623
|
+
const makeStreamResponse: (
|
|
624
|
+
request: typeof ConverseRequest.Encoded,
|
|
625
|
+
stream: Stream.Stream<ConverseResponseStreamEvent, AiError.AiError>,
|
|
626
|
+
options: LanguageModel.ProviderOptions
|
|
627
|
+
) => Effect.Effect<
|
|
628
|
+
Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,
|
|
629
|
+
never,
|
|
630
|
+
IdGenerator.IdGenerator
|
|
631
|
+
> = Effect.fnUntraced(
|
|
632
|
+
function*(request, stream, options) {
|
|
633
|
+
const contentBlocks: Record<
|
|
634
|
+
number,
|
|
635
|
+
| {
|
|
636
|
+
readonly type: "text"
|
|
637
|
+
}
|
|
638
|
+
| {
|
|
639
|
+
readonly type: "reasoning"
|
|
640
|
+
}
|
|
641
|
+
| {
|
|
642
|
+
readonly type: "tool-call"
|
|
643
|
+
readonly id: string
|
|
644
|
+
readonly name: string
|
|
645
|
+
params: string
|
|
646
|
+
readonly providerName?: string | undefined
|
|
647
|
+
readonly providerExecuted: boolean
|
|
648
|
+
}
|
|
649
|
+
> = {}
|
|
650
|
+
|
|
651
|
+
let trace: ConverseTrace | undefined = undefined
|
|
652
|
+
let cacheWriteInputTokens: number | undefined = undefined
|
|
653
|
+
const usage: Mutable<typeof Response.Usage.Encoded> = {
|
|
654
|
+
inputTokens: undefined,
|
|
655
|
+
outputTokens: undefined,
|
|
656
|
+
totalTokens: undefined
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return stream.pipe(
|
|
660
|
+
Stream.mapEffect(Effect.fnUntraced(function*(event) {
|
|
661
|
+
const parts: Array<Response.StreamPartEncoded> = []
|
|
662
|
+
|
|
663
|
+
switch (event.type) {
|
|
664
|
+
case "messageStart": {
|
|
665
|
+
parts.push({
|
|
666
|
+
type: "response-metadata",
|
|
667
|
+
modelId: request.modelId,
|
|
668
|
+
timestamp: DateTime.formatIso(yield* DateTime.now)
|
|
669
|
+
})
|
|
670
|
+
break
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
case "messageStop": {
|
|
674
|
+
const reason = InternalUtilities.resolveFinishReason(event.messageStop.stopReason)
|
|
675
|
+
parts.push({
|
|
676
|
+
type: "finish",
|
|
677
|
+
reason,
|
|
678
|
+
usage,
|
|
679
|
+
metadata: {
|
|
680
|
+
bedrock: { trace, usage: { cacheWriteInputTokens } }
|
|
681
|
+
}
|
|
682
|
+
})
|
|
683
|
+
|
|
684
|
+
break
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
case "contentBlockStart": {
|
|
688
|
+
const index = event.contentBlockStart.contentBlockIndex
|
|
689
|
+
const block = event.contentBlockStart
|
|
690
|
+
if (Predicate.isNotUndefined(block.start.toolUse)) {
|
|
691
|
+
const toolUse = block.start.toolUse
|
|
692
|
+
const toolName = toolUse.name
|
|
693
|
+
const providerTool = AnthropicTool.getProviderDefinedToolName(toolName)
|
|
694
|
+
const name = Predicate.isNotUndefined(providerTool) ? providerTool : toolName
|
|
695
|
+
const providerName = Predicate.isNotUndefined(providerTool) ? toolName : undefined
|
|
696
|
+
|
|
697
|
+
contentBlocks[index] = {
|
|
698
|
+
type: "tool-call",
|
|
699
|
+
id: toolUse.toolUseId,
|
|
700
|
+
name,
|
|
701
|
+
params: "",
|
|
702
|
+
providerName,
|
|
703
|
+
providerExecuted: false
|
|
704
|
+
}
|
|
705
|
+
// Only emit tool param delta events for text responses
|
|
706
|
+
if (options.responseFormat.type === "text") {
|
|
707
|
+
parts.push({
|
|
708
|
+
type: "tool-params-start",
|
|
709
|
+
id: toolUse.toolUseId,
|
|
710
|
+
name: toolUse.name,
|
|
711
|
+
providerExecuted: false
|
|
712
|
+
})
|
|
713
|
+
}
|
|
714
|
+
} else {
|
|
715
|
+
contentBlocks[index] = { type: "text" }
|
|
716
|
+
parts.push({
|
|
717
|
+
type: "text-start",
|
|
718
|
+
id: index.toString()
|
|
719
|
+
})
|
|
720
|
+
}
|
|
721
|
+
break
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
case "contentBlockDelta": {
|
|
725
|
+
const index = event.contentBlockDelta.contentBlockIndex
|
|
726
|
+
const delta = event.contentBlockDelta.delta
|
|
727
|
+
|
|
728
|
+
switch (delta.type) {
|
|
729
|
+
case "text": {
|
|
730
|
+
const block = contentBlocks[index]
|
|
731
|
+
if (Predicate.isUndefined(block)) {
|
|
732
|
+
contentBlocks[index] = { type: "text" }
|
|
733
|
+
// Only emit text delta events for text responses
|
|
734
|
+
if (options.responseFormat.type === "text") {
|
|
735
|
+
parts.push({
|
|
736
|
+
type: "text-start",
|
|
737
|
+
id: index.toString()
|
|
738
|
+
})
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
// Only emit text delta events for text responses
|
|
742
|
+
if (options.responseFormat.type === "text") {
|
|
743
|
+
parts.push({
|
|
744
|
+
type: "text-delta",
|
|
745
|
+
id: index.toString(),
|
|
746
|
+
delta: delta.text
|
|
747
|
+
})
|
|
748
|
+
}
|
|
749
|
+
break
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
case "reasoningContent": {
|
|
753
|
+
if ("text" in delta.reasoningContent) {
|
|
754
|
+
const block = contentBlocks[index]
|
|
755
|
+
if (Predicate.isUndefined(block)) {
|
|
756
|
+
contentBlocks[index] = { type: "reasoning" }
|
|
757
|
+
parts.push({
|
|
758
|
+
type: "reasoning-start",
|
|
759
|
+
id: index.toString()
|
|
760
|
+
})
|
|
761
|
+
}
|
|
762
|
+
parts.push({
|
|
763
|
+
type: "reasoning-delta",
|
|
764
|
+
id: index.toString(),
|
|
765
|
+
delta: delta.reasoningContent.text
|
|
766
|
+
})
|
|
767
|
+
} else if ("signature" in delta.reasoningContent) {
|
|
768
|
+
parts.push({
|
|
769
|
+
type: "reasoning-delta",
|
|
770
|
+
id: index.toString(),
|
|
771
|
+
delta: "",
|
|
772
|
+
metadata: {
|
|
773
|
+
bedrock: {
|
|
774
|
+
type: "thinking",
|
|
775
|
+
signature: delta.reasoningContent.signature
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
})
|
|
779
|
+
} else {
|
|
780
|
+
parts.push({
|
|
781
|
+
type: "reasoning-delta",
|
|
782
|
+
id: index.toString(),
|
|
783
|
+
delta: "",
|
|
784
|
+
metadata: {
|
|
785
|
+
bedrock: {
|
|
786
|
+
type: "redacted_thinking",
|
|
787
|
+
redactedData: delta.reasoningContent.redactedContent
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
})
|
|
791
|
+
}
|
|
792
|
+
break
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
case "toolUse": {
|
|
796
|
+
const block = contentBlocks[index]
|
|
797
|
+
if (Predicate.isNotUndefined(block) && block.type === "tool-call") {
|
|
798
|
+
const params = delta.toolUse.input
|
|
799
|
+
// Only emit tool params delta events for text responses
|
|
800
|
+
if (options.responseFormat.type === "text") {
|
|
801
|
+
parts.push({
|
|
802
|
+
type: "tool-params-delta",
|
|
803
|
+
id: block.id,
|
|
804
|
+
delta: params
|
|
805
|
+
})
|
|
806
|
+
}
|
|
807
|
+
block.params += params
|
|
808
|
+
}
|
|
809
|
+
break
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
break
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
case "contentBlockStop": {
|
|
816
|
+
const index = event.contentBlockStop.contentBlockIndex
|
|
817
|
+
const block = contentBlocks[index]
|
|
818
|
+
if (Predicate.isNotUndefined(block)) {
|
|
819
|
+
switch (block.type) {
|
|
820
|
+
case "text": {
|
|
821
|
+
// Only emit text end events for text responses
|
|
822
|
+
if (options.responseFormat.type === "text") {
|
|
823
|
+
parts.push({
|
|
824
|
+
type: "text-end",
|
|
825
|
+
id: index.toString()
|
|
826
|
+
})
|
|
827
|
+
}
|
|
828
|
+
break
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
case "reasoning": {
|
|
832
|
+
parts.push({
|
|
833
|
+
type: "reasoning-end",
|
|
834
|
+
id: index.toString()
|
|
835
|
+
})
|
|
836
|
+
break
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
case "tool-call": {
|
|
840
|
+
// Only emit tool param events for text responses - for JSON
|
|
841
|
+
// responses, the structured output will be emitted as text
|
|
842
|
+
if (options.responseFormat.type === "text") {
|
|
843
|
+
parts.push({
|
|
844
|
+
type: "tool-params-end",
|
|
845
|
+
id: block.id
|
|
846
|
+
})
|
|
847
|
+
parts.push({
|
|
848
|
+
type: "tool-call",
|
|
849
|
+
id: block.id,
|
|
850
|
+
name: block.name,
|
|
851
|
+
params: JSON.parse(block.params),
|
|
852
|
+
providerName: block.providerName,
|
|
853
|
+
providerExecuted: block.providerExecuted
|
|
854
|
+
})
|
|
855
|
+
} else {
|
|
856
|
+
parts.push({
|
|
857
|
+
type: "text-start",
|
|
858
|
+
id: index.toString()
|
|
859
|
+
})
|
|
860
|
+
parts.push({
|
|
861
|
+
type: "text-delta",
|
|
862
|
+
id: index.toString(),
|
|
863
|
+
delta: block.params
|
|
864
|
+
})
|
|
865
|
+
parts.push({
|
|
866
|
+
type: "text-end",
|
|
867
|
+
id: index.toString()
|
|
868
|
+
})
|
|
869
|
+
}
|
|
870
|
+
break
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
delete contentBlocks[index]
|
|
874
|
+
}
|
|
875
|
+
break
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
case "metadata": {
|
|
879
|
+
usage.inputTokens = event.metadata.usage.inputTokens
|
|
880
|
+
usage.outputTokens = event.metadata.usage.outputTokens
|
|
881
|
+
usage.totalTokens = event.metadata.usage.totalTokens
|
|
882
|
+
usage.cachedInputTokens = event.metadata.usage.cacheReadInputTokens
|
|
883
|
+
if (Predicate.isNotUndefined(event.metadata.usage.cacheWriteInputTokens)) {
|
|
884
|
+
cacheWriteInputTokens = event.metadata.usage.cacheWriteInputTokens
|
|
885
|
+
}
|
|
886
|
+
if (Predicate.isNotUndefined(event.metadata.trace)) {
|
|
887
|
+
trace = event.metadata.trace
|
|
888
|
+
}
|
|
889
|
+
break
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
case "internalServerException": {
|
|
893
|
+
parts.push({ type: "error", error: event.internalServerException })
|
|
894
|
+
break
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
case "modelStreamErrorException": {
|
|
898
|
+
parts.push({ type: "error", error: event.modelStreamErrorException })
|
|
899
|
+
break
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
case "serviceUnavailableException": {
|
|
903
|
+
parts.push({ type: "error", error: event.serviceUnavailableException })
|
|
904
|
+
break
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
case "throttlingException": {
|
|
908
|
+
parts.push({ type: "error", error: event.throttlingException })
|
|
909
|
+
break
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
case "validationException": {
|
|
913
|
+
parts.push({ type: "error", error: event.validationException })
|
|
914
|
+
break
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
return parts
|
|
919
|
+
})),
|
|
920
|
+
Stream.flattenIterables
|
|
921
|
+
)
|
|
560
922
|
}
|
|
561
923
|
)
|
|
562
924
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
925
|
+
// =============================================================================
|
|
926
|
+
// Tool Calling
|
|
927
|
+
// =============================================================================
|
|
928
|
+
|
|
929
|
+
const prepareTools: (
|
|
930
|
+
options: LanguageModel.ProviderOptions,
|
|
931
|
+
config: Config.Service
|
|
932
|
+
) => Effect.Effect<{
|
|
933
|
+
readonly betas: ReadonlySet<string>
|
|
934
|
+
readonly toolConfig: Partial<typeof ToolConfiguration.Encoded>
|
|
935
|
+
readonly additionalTools?: Record<string, unknown> | undefined
|
|
936
|
+
}, AiError.AiError> = Effect.fnUntraced(function*(options, config) {
|
|
937
|
+
const betas = new Set<string>()
|
|
938
|
+
|
|
939
|
+
if (options.tools.length === 0) {
|
|
940
|
+
return { toolConfig: {}, betas }
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
const isAnthropicModel = config.modelId!.includes("anthropic.")
|
|
944
|
+
const userDefinedTools: Array<Tool.Any> = []
|
|
945
|
+
const providerDefinedTools: Array<Tool.AnyProviderDefined> = []
|
|
946
|
+
for (const tool of options.tools) {
|
|
947
|
+
if (Tool.isUserDefined(tool)) {
|
|
948
|
+
userDefinedTools.push(tool)
|
|
949
|
+
} else {
|
|
950
|
+
providerDefinedTools.push(tool as Tool.AnyProviderDefined)
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const hasAnthropicTools = isAnthropicModel && providerDefinedTools.length > 0
|
|
955
|
+
|
|
956
|
+
let tools: Array<typeof AmazonBedrockTool.Encoded> = []
|
|
957
|
+
let additionalTools: Record<string, unknown> | undefined = undefined
|
|
958
|
+
|
|
959
|
+
// Handle Anthropic provider-defined tools for Anthropic models on Bedrock
|
|
960
|
+
if (hasAnthropicTools) {
|
|
961
|
+
const prepared = yield* prepareAnthropicTools(options, {})
|
|
962
|
+
|
|
963
|
+
prepared.betas.forEach((beta) => betas.add(beta))
|
|
964
|
+
|
|
965
|
+
if (Predicate.isNotUndefined(prepared.toolChoice)) {
|
|
966
|
+
// For Anthropic tools on Bedrock, only the 'tool_choice' goes into
|
|
967
|
+
// the `additionalModelRequestFields` parameter of the request, while
|
|
968
|
+
// the tool definitions themselves are sent in the usual `toolConfig`
|
|
969
|
+
additionalTools = {
|
|
970
|
+
tool_choice: prepared.toolChoice
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// Handle conversion of provider-defined tools to Amazon Bedrock tool definitions
|
|
975
|
+
for (const providerDefinedTool of providerDefinedTools) {
|
|
976
|
+
tools.push({
|
|
977
|
+
toolSpec: {
|
|
978
|
+
name: providerDefinedTool.providerName,
|
|
979
|
+
description: Tool.getDescription(providerDefinedTool as any),
|
|
980
|
+
inputSchema: {
|
|
981
|
+
json: Tool.getJsonSchema(providerDefinedTool as any) as any
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
})
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// Handle conversion of user-defined tools to Amazon Bedrock tool definitions
|
|
989
|
+
for (const tool of userDefinedTools) {
|
|
990
|
+
tools.push({
|
|
991
|
+
toolSpec: {
|
|
992
|
+
name: tool.name,
|
|
993
|
+
description: Tool.getDescription(tool as any),
|
|
994
|
+
inputSchema: {
|
|
995
|
+
json: Tool.getJsonSchema(tool as any) as any
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
})
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// Handle resolution of tool choice for **Amazon Bedrock** user-defined tools.
|
|
1002
|
+
// The tool choice for Anthropic provider-defined tools is resolved above and
|
|
1003
|
+
// inserted into the additional tool configuration object.
|
|
1004
|
+
let toolChoice: typeof ToolChoice.Encoded | undefined = undefined
|
|
1005
|
+
if (!hasAnthropicTools && tools.length > 0 && Predicate.isNotUndefined(options.toolChoice)) {
|
|
1006
|
+
if (options.toolChoice === "none") {
|
|
1007
|
+
tools.length = 0
|
|
1008
|
+
toolChoice = undefined
|
|
1009
|
+
} else if (options.toolChoice === "auto") {
|
|
1010
|
+
toolChoice = { auto: {} }
|
|
1011
|
+
} else if (options.toolChoice === "required") {
|
|
1012
|
+
toolChoice = { any: {} }
|
|
1013
|
+
} else if ("tool" in options.toolChoice) {
|
|
1014
|
+
toolChoice = { tool: { name: options.toolChoice.tool } }
|
|
1015
|
+
} else {
|
|
1016
|
+
const allowedTools = new Set(options.toolChoice.oneOf)
|
|
1017
|
+
tools = tools.filter((tool) => allowedTools.has(tool.toolSpec?.name))
|
|
1018
|
+
toolChoice = options.toolChoice.mode === "auto" ? { auto: {} } : { any: {} }
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
const toolConfig: Partial<typeof ToolConfiguration.Encoded> = tools.length > 0
|
|
1023
|
+
? { tools, toolChoice }
|
|
1024
|
+
: {}
|
|
1025
|
+
|
|
1026
|
+
return { additionalTools, betas, toolConfig }
|
|
1027
|
+
})
|
|
1028
|
+
|
|
1029
|
+
// =============================================================================
|
|
1030
|
+
// Telemetry
|
|
1031
|
+
// =============================================================================
|
|
574
1032
|
|
|
575
1033
|
const annotateRequest = (
|
|
576
1034
|
span: Span,
|
|
@@ -589,14 +1047,14 @@ const annotateRequest = (
|
|
|
589
1047
|
})
|
|
590
1048
|
}
|
|
591
1049
|
|
|
592
|
-
const
|
|
1050
|
+
const annotateResponse = (
|
|
593
1051
|
span: Span,
|
|
594
|
-
|
|
1052
|
+
request: typeof ConverseRequest.Encoded,
|
|
595
1053
|
response: ConverseResponse
|
|
596
1054
|
): void => {
|
|
597
1055
|
addGenAIAnnotations(span, {
|
|
598
1056
|
response: {
|
|
599
|
-
model: modelId,
|
|
1057
|
+
model: request.modelId,
|
|
600
1058
|
finishReasons: response.stopReason ? [response.stopReason] : undefined
|
|
601
1059
|
},
|
|
602
1060
|
usage: {
|
|
@@ -606,21 +1064,153 @@ const annotateChatResponse = (
|
|
|
606
1064
|
})
|
|
607
1065
|
}
|
|
608
1066
|
|
|
609
|
-
const annotateStreamResponse = (
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
1067
|
+
const annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {
|
|
1068
|
+
if (part.type === "response-metadata") {
|
|
1069
|
+
addGenAIAnnotations(span, {
|
|
1070
|
+
response: {
|
|
1071
|
+
id: part.id,
|
|
1072
|
+
model: part.modelId
|
|
1073
|
+
}
|
|
1074
|
+
})
|
|
1075
|
+
}
|
|
1076
|
+
if (part.type === "finish") {
|
|
1077
|
+
addGenAIAnnotations(span, {
|
|
1078
|
+
response: {
|
|
1079
|
+
finishReasons: [part.reason]
|
|
1080
|
+
},
|
|
1081
|
+
usage: {
|
|
1082
|
+
inputTokens: part.usage.inputTokens,
|
|
1083
|
+
outputTokens: part.usage.outputTokens
|
|
1084
|
+
}
|
|
1085
|
+
})
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// =============================================================================
|
|
1090
|
+
// Utilities
|
|
1091
|
+
// =============================================================================
|
|
1092
|
+
|
|
1093
|
+
type ContentGroup = SystemMessageGroup | AssistantMessageGroup | UserMessageGroup
|
|
1094
|
+
|
|
1095
|
+
interface SystemMessageGroup {
|
|
1096
|
+
readonly type: "system"
|
|
1097
|
+
readonly messages: Array<Prompt.SystemMessage>
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
interface AssistantMessageGroup {
|
|
1101
|
+
readonly type: "assistant"
|
|
1102
|
+
readonly messages: Array<Prompt.AssistantMessage>
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
interface UserMessageGroup {
|
|
1106
|
+
readonly type: "user"
|
|
1107
|
+
readonly messages: Array<Prompt.ToolMessage | Prompt.UserMessage>
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
const groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {
|
|
1111
|
+
const messages: Array<ContentGroup> = []
|
|
1112
|
+
let current: ContentGroup | undefined = undefined
|
|
1113
|
+
for (const message of prompt.content) {
|
|
1114
|
+
switch (message.role) {
|
|
1115
|
+
case "system": {
|
|
1116
|
+
if (current?.type !== "system") {
|
|
1117
|
+
current = { type: "system", messages: [] }
|
|
1118
|
+
messages.push(current)
|
|
1119
|
+
}
|
|
1120
|
+
current.messages.push(message)
|
|
1121
|
+
break
|
|
1122
|
+
}
|
|
1123
|
+
case "assistant": {
|
|
1124
|
+
if (current?.type !== "assistant") {
|
|
1125
|
+
current = { type: "assistant", messages: [] }
|
|
1126
|
+
messages.push(current)
|
|
1127
|
+
}
|
|
1128
|
+
current.messages.push(message)
|
|
1129
|
+
break
|
|
1130
|
+
}
|
|
1131
|
+
case "tool":
|
|
1132
|
+
case "user": {
|
|
1133
|
+
if (current?.type !== "user") {
|
|
1134
|
+
current = { type: "user", messages: [] }
|
|
1135
|
+
messages.push(current)
|
|
1136
|
+
}
|
|
1137
|
+
current.messages.push(message)
|
|
1138
|
+
break
|
|
1139
|
+
}
|
|
624
1140
|
}
|
|
625
|
-
}
|
|
1141
|
+
}
|
|
1142
|
+
return messages
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant
|
|
1147
|
+
* responses, so we trim the final text part here if it's the last message in
|
|
1148
|
+
* the group.
|
|
1149
|
+
*/
|
|
1150
|
+
const trimIfLast = (
|
|
1151
|
+
isLastGroup: boolean,
|
|
1152
|
+
isLastMessage: boolean,
|
|
1153
|
+
isLastPart: boolean,
|
|
1154
|
+
text: string
|
|
1155
|
+
) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text
|
|
1156
|
+
|
|
1157
|
+
const getCachePoint = (
|
|
1158
|
+
part:
|
|
1159
|
+
| Prompt.SystemMessage
|
|
1160
|
+
| Prompt.UserMessage
|
|
1161
|
+
| Prompt.AssistantMessage
|
|
1162
|
+
| Prompt.ToolMessage
|
|
1163
|
+
): typeof CachePointBlock.Encoded | undefined => part.options.bedrock?.cachePoint
|
|
1164
|
+
|
|
1165
|
+
const convertToBase64 = (data: string | Uint8Array): string =>
|
|
1166
|
+
typeof data === "string" ? data : Encoding.encodeBase64(data)
|
|
1167
|
+
|
|
1168
|
+
const DOCUMENT_MIME_TYPES: Record<string, typeof DocumentFormat.Encoded> = {
|
|
1169
|
+
"application/pdf": "pdf",
|
|
1170
|
+
"text/csv": "csv",
|
|
1171
|
+
"application/msword": "doc",
|
|
1172
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
|
1173
|
+
"application/vnd.ms-excel": "xls",
|
|
1174
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
1175
|
+
"text/html": "html",
|
|
1176
|
+
"text/plain": "txt",
|
|
1177
|
+
"text/markdown": "md"
|
|
626
1178
|
}
|
|
1179
|
+
|
|
1180
|
+
const getDocumentFormat: (
|
|
1181
|
+
mediaType: string
|
|
1182
|
+
) => Effect.Effect<typeof DocumentFormat.Encoded, AiError.AiError> = Effect.fnUntraced(
|
|
1183
|
+
function*(mediaType) {
|
|
1184
|
+
const format = DOCUMENT_MIME_TYPES[mediaType]
|
|
1185
|
+
|
|
1186
|
+
if (Predicate.isUndefined(format)) {
|
|
1187
|
+
return yield* new AiError.MalformedInput({
|
|
1188
|
+
module: "AmazonBedrockLanguageModel",
|
|
1189
|
+
method: "getDocumentFormat",
|
|
1190
|
+
description: `Unsupported document MIME type: ${mediaType} - expected ` +
|
|
1191
|
+
`one of: ${Object.keys(DOCUMENT_MIME_TYPES)}`
|
|
1192
|
+
})
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
return format
|
|
1196
|
+
}
|
|
1197
|
+
)
|
|
1198
|
+
|
|
1199
|
+
const getImageFormat: (
|
|
1200
|
+
mediaType: string
|
|
1201
|
+
) => Effect.Effect<typeof ImageFormat.Encoded, AiError.AiError> = Effect.fnUntraced(
|
|
1202
|
+
function*(mediaType) {
|
|
1203
|
+
const format = ImageFormat.literals.find((format) => mediaType === `image/${format}`)
|
|
1204
|
+
|
|
1205
|
+
if (Predicate.isUndefined(format)) {
|
|
1206
|
+
return yield* new AiError.MalformedInput({
|
|
1207
|
+
module: "AmazonBedrockLanguageModel",
|
|
1208
|
+
method: "getImageFormat",
|
|
1209
|
+
description: `Unsupported image MIME type: ${mediaType} - expected ` +
|
|
1210
|
+
`one of: ${ImageFormat.literals.map((format) => `image/${format}`).join(",")}`
|
|
1211
|
+
})
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
return format
|
|
1215
|
+
}
|
|
1216
|
+
)
|