Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(assistant): trace cost correctly (#14945)

Nimar7a3fa899c5b0
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index ef13798697..359a9fa3ca 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -33,6 +33,7 @@ const instrumentationMocks = vi.hoisted(() => {
recordEvents: vi.fn(),
recordAvailableTools: vi.fn(),
recordToolCallApproval: vi.fn(),
+ recordStepFinish: vi.fn(),
end: vi.fn(),
endWithError: vi.fn(),
flush: vi.fn(),
@@ -831,7 +832,16 @@ describe("createAgUiStream", () => {
version: 2,
},
}),
+ model: "eu.anthropic.claude-opus-4-8",
});
+ const onStepFinish = agentConfig?.defaultOptions?.onStepFinish as
+ | ((event: unknown) => void)
+ | undefined;
+ expect(onStepFinish).toEqual(expect.any(Function));
+ onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 } });
+ expect(
+ instrumentationMocks.instrumentation.recordStepFinish,
+ ).toHaveBeenCalledWith({ usage: { inputTokens: 10, outputTokens: 5 } });
expect(
instrumentationMocks.instrumentation.recordEvents.mock.calls.flatMap(
([events]) => (events as AgUiEvent[]).map((event) => event.type),
diff --git a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
index a01210c08b..2395ce8dbb 100644
--- a/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
+++ b/web/src/__tests__/server/unit/in-app-agent-instrumentation.servertest.ts
@@ -837,6 +837,93 @@ describe("InAppAgentInstrumentation", () => {
expect.anything(),
);
});
+
+ it("aggregates step usage and model onto the agent generation", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordStepFinish({
+ usage: {
+ inputTokens: 1100,
+ outputTokens: 50,
+ totalTokens: 1150,
+ cachedInputTokens: 800,
+ cacheCreationInputTokens: 100,
+ },
+ });
+ instrumentation.recordStepFinish({
+ usage: {
+ inputTokens: 1200,
+ outputTokens: 30,
+ totalTokens: 1230,
+ cachedInputTokens: 1000,
+ },
+ });
+ instrumentation.end({});
+
+ expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ model: "eu.anthropic.claude-sonnet-4-5-20250929-v1:0",
+ usageDetails: {
+ // Mastra's inputTokens includes cache reads/writes; the priced
+ // `input` key must only contain non-cached input tokens.
+ input: 400,
+ output: 80,
+ cache_read_input_tokens: 1800,
+ cache_creation_input_tokens: 100,
+ total: 2380,
+ },
+ }),
+ );
+ });
+
+ it("records aggregated usage when the run fails", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordStepFinish({
+ usage: { inputTokens: 100, outputTokens: 10, totalTokens: 110 },
+ });
+ instrumentation.endWithError(new Error("agent failed"));
+
+ expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ level: "ERROR",
+ model: "eu.anthropic.claude-sonnet-4-5-20250929-v1:0",
+ usageDetails: {
+ input: 100,
+ output: 10,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: 0,
+ total: 110,
+ },
+ }),
+ );
+ });
+
+ it("omits usage and model when no step reported usage", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.recordStepFinish(undefined);
+ instrumentation.recordStepFinish({ usage: { foo: 1 } });
+ instrumentation.end({});
+
+ const agentGenerationBody = mocks.agentGeneration.update.mock.calls[0]?.[0];
+
+ expect(agentGenerationBody).not.toHaveProperty("usageDetails");
+ expect(agentGenerationBody).not.toHaveProperty("model");
+ });
+
+ it("ignores step finish events after instrumentation ended", () => {
+ const instrumentation = createInstrumentation();
+
+ instrumentation.end({});
+ instrumentation.recordStepFinish({
+ usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
+ });
+
+ expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
+ expect.not.objectContaining({ usageDetails: expect.anything() }),
+ );
+ });
});
function createInstrumentation(
@@ -854,5 +941,6 @@ function createInstrumentation(
targetProjectId: "project-1",
environment: "prod",
prompt,
+ model: "eu.anthropic.claude-sonnet-4-5-20250929-v1:0",
});
}
diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.ts
index 55d3f781b2..01895b54ce 100644
--- a/web/src/ee/features/in-app-agent/server/agent.ts
+++ b/web/src/ee/features/in-app-agent/server/agent.ts
@@ -195,8 +195,14 @@ export async function createAgUiStream(params: {
tracing: params.options.langfuseTracing
? { ...params.options.langfuseTracing, prompt }
: undefined,
+ model: params.options.awsBedrock.modelId,
});
instrumentation?.recordAvailableSkills?.(LANGFUSE_IN_APP_AGENT_SKILLS);
+ const onStepFinish = instrumentation
+ ? (event: unknown) => {
+ instrumentation.recordStepFinish?.(event);
+ }
+ : undefined;
let subscription: { unsubscribe: () => void } | undefined;
let ending = false;
@@ -425,6 +431,7 @@ export async function createAgUiStream(params: {
instructions,
onToolsAvailable: (tools) =>
instrumentation?.recordAvailableTools?.(tools),
+ onStepFinish,
})
.then(async (initialAdapter) => {
if (ending || closed || params.signal.aborted) {
@@ -476,6 +483,7 @@ export async function createAgUiStream(params: {
},
awsProfile,
instructions,
+ onStepFinish,
});
if (ending || closed || params.signal.aborted) {
@@ -669,6 +677,7 @@ async function createMastraAdapter(params: {
awsProfile?: string;
instructions: string;
onToolsAvailable?: (tools: Record<string, unknown>) => void;
+ onStepFinish?: (event: unknown) => void;
}) {
const bedrock = createAmazonBedrock({
...(params.options.awsBedrock.region
@@ -753,6 +762,9 @@ async function createMastraAdapter(params: {
defaultOptions: {
abortSignal: params.signal,
maxSteps: MAX_AGENT_STEPS,
+ // Fires once per LLM call with that call's token usage; the AG-UI
+ // event stream itself never carries usage.
+ ...(params.onStepFinish ? { onStepFinish: params.onStepFinish } : {}),
...(reasoningProviderOptions
? { providerOptions: reasoningProviderOptions }
: {}),
diff --git a/web/src/ee/features/in-app-agent/server/instrumentation.ts b/web/src/ee/features/in-app-agent/server/instrumentation.ts
index 0e59d3b00e..ecb91a5f1e 100644
--- a/web/src/ee/features/in-app-agent/server/instrumentation.ts
+++ b/web/src/ee/features/in-app-agent/server/instrumentation.ts
@@ -32,6 +32,7 @@ export type InAppAgentTracingConfig = {
export type InAppAgentInstrumentationParams = {
input: AgUiRunAgentInput;
tracing?: InAppAgentTracingConfig;
+ model?: string;
};
export type InAppAgentPromptMetadata = {
@@ -98,6 +99,7 @@ type ToolCallApprovalStatus = "approved" | "rejected";
export function createInAppAgentInstrumentation({
input,
tracing,
+ model,
}: InAppAgentInstrumentationParams) {
if (!tracing?.targetProjectId) {
return undefined;
@@ -115,6 +117,7 @@ export function createInAppAgentInstrumentation({
targetProjectId: tracing.targetProjectId,
environment: tracing.environment,
prompt: tracing.prompt,
+ model,
});
} catch (error) {
logger.warn("Failed to initialize in-app agent Langfuse tracing", error);
@@ -152,6 +155,8 @@ export class InAppAgentInstrumentation {
private pendingThinking: AgentRunThinkingPart[] = [];
private completionStartTime?: Date;
private ended = false;
+ private readonly model?: string;
+ private usageDetails?: Record<string, number>;
constructor(params: {
input: AgUiRunAgentInput;
@@ -164,6 +169,7 @@ export class InAppAgentInstrumentation {
targetProjectId: string;
environment: string;
prompt?: InAppAgentPromptMetadata;
+ model?: string;
}) {
this.metadata = {
...params.metadata,
@@ -181,6 +187,7 @@ export class InAppAgentInstrumentation {
};
this.agentRunInput = getAgentRunInput(params.input);
this.prompt = params.prompt;
+ this.model = params.model;
const traceSinkParams = {
targetProjectId: params.targetProjectId,
@@ -259,6 +266,50 @@ export class InAppAgentInstrumentation {
this.toolCallApprovals.set(approval.toolCallId, approval.status);
}
+ // Receives Mastra's per-LLM-call onStepFinish event and accumulates its
+ // token usage onto the agent-turn generation, since the AG-UI event stream
+ // itself never carries usage.
+ recordStepFinish(event: unknown) {
+ if (this.ended) {
+ return;
+ }
+
+ const usage = isRecord(event) ? event.usage : undefined;
+ if (!isRecord(usage)) {
+ return;
+ }
+
+ const inputTokens = getFiniteNumber(usage.inputTokens);
+ const outputTokens = getFiniteNumber(usage.outputTokens);
+ if (inputTokens === undefined && outputTokens === undefined) {
+ return;
+ }
+
+ const cacheReadTokens = getFiniteNumber(usage.cachedInputTokens) ?? 0;
+ const cacheWriteTokens =
+ getFiniteNumber(usage.cacheCreationInputTokens) ?? 0;
+ const totals = (this.usageDetails ??= {
+ input: 0,
+ output: 0,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: 0,
+ total: 0,
+ });
+
+ // Mastra's inputTokens includes cache reads/writes, while Langfuse model
+ // prices bill `input` as non-cached input tokens with separate cache keys.
+ totals.input += Math.max(
+ 0,
+ (inputTokens ?? 0) - cacheReadTokens - cacheWriteTokens,
+ );
+ totals.output += outputTokens ?? 0;
+ totals.cache_read_input_tokens += cacheReadTokens;
+ totals.cache_creation_input_tokens += cacheWriteTokens;
+ totals.total +=
+ getFiniteNumber(usage.totalTokens) ??
+ (inputTokens ?? 0) + (outputTokens ?? 0);
+ }
+
recordAvailableSkills(skills: unknown[]) {
if (this.ended) {
return;
@@ -291,6 +342,7 @@ export class InAppAgentInstrumentation {
...(this.completionStartTime
? { completionStartTime: this.completionStartTime }
: {}),
+ ...this.getAgentRunUsage(),
level: "ERROR",
statusMessage: message,
metadata: {
@@ -332,6 +384,7 @@ export class InAppAgentInstrumentation {
...(this.completionStartTime
? { completionStartTime: this.completionStartTime }
: {}),
+ ...this.getAgentRunUsage(),
metadata,
...(this.prompt
? {
@@ -584,6 +637,19 @@ export class InAppAgentInstrumentation {
).enqueue("tool-create", body);
}
+ // Model is only set alongside provided usage; on its own it would make
+ // ingestion tokenize the agent-turn input/output into estimated usage.
+ private getAgentRunUsage() {
+ if (!this.usageDetails) {
+ return {};
+ }
+
+ return {
+ usageDetails: this.usageDetails,
+ ...(this.model ? { model: this.model } : {}),
+ };
+ }
+
private endOpenToolSpans(
metadata?: Record<string, unknown>,
statusMessage?: string,
@@ -937,6 +1003,12 @@ function isToolError(output: unknown): boolean {
return isRecord(output) && output.error === true;
}
+function getFiniteNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value)
+ ? value
+ : undefined;
+}
+
function getSerializableToolParameters(tool: Record<string, unknown>): unknown {
const parameters =
tool.parameters ??