fix(@effect/ai-amazon-bedrock): emit finish part after metadata so streaming usage is populated#6238
Conversation
…reaming usage is populated
|
|
@kn0ll before I approve this, can you please provide a minimal reproduction program I can run to test the behavior you are referring to. |
|
@IMax153 of course! i got too clever with my issue & PR organization. import * as LanguageModel from "@effect/ai/LanguageModel"
import * as AmazonBedrockClient from "@effect/ai-amazon-bedrock/AmazonBedrockClient"
import * as AmazonBedrockLanguageModel from "@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel"
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"
import { Effect, Layer, Redacted, Stream } from "effect"
const MainLive = AmazonBedrockLanguageModel.layer({
model: "anthropic.claude-3-haiku-20240307-v1:0"
}).pipe(
Layer.provide(AmazonBedrockClient.layer({
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: Redacted.make(process.env.AWS_SECRET_ACCESS_KEY!),
region: "us-east-1"
})),
Layer.provide(NodeHttpClient.layerUndici)
)
const program = LanguageModel.streamText({ prompt: "Say hello in one sentence." }).pipe(
Stream.runFold(undefined as any, (_acc, part) => part.type === "finish" ? part : _acc),
Effect.andThen((finish) => {
console.log(`inputTokens: ${finish.usage.inputTokens}, outputTokens: ${finish.usage.outputTokens}`)
}),
Effect.scoped,
Effect.provide(MainLive)
)
Effect.runPromise(program)this script produces thank you for all your hard work! |
Type
Description
In
makeStreamResponse, themessageStopevent was emitting thefinishpart with a reference to a shared mutableusageobject. Themetadataevent (which carries actual token counts) arrives aftermessageStopin the Bedrock Converse stream, but by that point@effect/ai'sLanguageModel.streamTexthas already runSchema.decodeon thefinishpart, creating a newUsageclass instance from the values at decode time (allundefined).The fix defers emitting the
finishpart:messageStopnow stores the finish reason in a closure variable, and themetadatahandler emits thefinishpart after populating usage.Related
@effect/ai-amazon-bedrock: streaming token usage is always empty #6237