Skip to content

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

fix(agent): Make instrumentation turn-based (#14768)

Ben Bachem8bea1f6f4f47
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 58f96a54f7..91166efb77 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
@@ -1,15 +1,20 @@
import { EventType } from "@ag-ui/core";
+import {
+ getInAppAgentInstrumentationObservationId,
+ getInAppAgentInstrumentationTraceId,
+} from "@/src/ee/features/in-app-agent/constants";
import type { AgUiRunAgentInput } from "@/src/ee/features/in-app-agent/schema";
import { InAppAgentInstrumentation } from "@/src/ee/features/in-app-agent/server/instrumentation";
-const traceId = "0123456789abcdef0123456789abcdef";
-const agentRunObservationId = "run-1";
+const runId = "run-1";
+const traceId = getInAppAgentInstrumentationTraceId(runId);
+const agentRunObservationId = getInAppAgentInstrumentationObservationId(runId);
const mocks = vi.hoisted(() => {
const agentGeneration = {
observationId: "run-1",
- traceId: "0123456789abcdef0123456789abcdef",
+ traceId: "run-1-trace",
update: vi.fn(),
end: vi.fn(),
};
@@ -53,7 +58,7 @@ vi.mock("@langfuse/shared/src/server", () => ({
const input: AgUiRunAgentInput = {
threadId: "conversation-1",
- runId: "run-1",
+ runId,
state: null,
messages: [{ id: "message-1", role: "user", content: "hello" }],
tools: [],
@@ -136,20 +141,22 @@ describe("InAppAgentInstrumentation", () => {
},
targetProjectId: "project-1",
traceId,
- traceName: "in-app-agent",
+ traceName: "agent-turn",
userId: "user-1",
}),
);
expect(mocks.handler.langfuse.trace).toHaveBeenCalledWith(
- expect.objectContaining({ id: traceId, name: "in-app-agent" }),
+ expect.objectContaining({ id: traceId, name: "agent-turn" }),
);
- expect(mocks.handler.langfuse.trace.mock.calls[0][0]).not.toHaveProperty(
- "input",
+ expect(mocks.handler.langfuse.trace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ input: expectedAgentRunInput,
+ }),
);
expect(mocks.trace.generation).toHaveBeenCalledWith(
expect.objectContaining({
id: agentRunObservationId,
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
}),
);
@@ -176,7 +183,7 @@ describe("InAppAgentInstrumentation", () => {
).not.toHaveProperty("toolCallApproval");
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
output: {
messages: [
@@ -202,7 +209,28 @@ describe("InAppAgentInstrumentation", () => {
"span-create",
expect.anything(),
);
- expect(mocks.trace.update.mock.calls[0][0]).not.toHaveProperty("output");
+ expect(mocks.trace.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ input: expectedAgentRunInput,
+ output: {
+ messages: [
+ { role: "assistant", content: "hi there" },
+ {
+ role: "assistant",
+ content: "",
+ tool_calls: [toolCall],
+ },
+ {
+ role: "tool",
+ tool_call_id: "tool-1",
+ content: toolOutput,
+ },
+ ],
+ text: "hi there",
+ tool_calls: [toolCall],
+ },
+ }),
+ );
});
it.each(["approved", "rejected"] as const)(
@@ -287,7 +315,7 @@ describe("InAppAgentInstrumentation", () => {
);
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
output: {
messages: [
@@ -342,7 +370,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: {
messages: [{ role: "user", content: "hello" }],
tools: [
@@ -466,7 +494,7 @@ describe("InAppAgentInstrumentation", () => {
);
expect(mocks.trace.generation).toHaveBeenCalledWith({
id: agentRunObservationId,
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
metadata: {
langfuse_project_id: "project-1",
@@ -484,7 +512,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
promptName: "in-app-agent-system-prompt",
promptVersion: 3,
@@ -492,7 +520,7 @@ describe("InAppAgentInstrumentation", () => {
);
});
- it("does not write trace input and output", () => {
+ it("writes trace input and output", () => {
const instrumentation = createInstrumentation();
instrumentation.recordEvents([
@@ -505,12 +533,9 @@ describe("InAppAgentInstrumentation", () => {
},
]);
- expect(mocks.handler.langfuse.trace.mock.calls[0][0]).not.toHaveProperty(
- "input",
- );
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
output: {
messages: [{ role: "assistant", content: "second turn output" }],
@@ -519,7 +544,15 @@ describe("InAppAgentInstrumentation", () => {
completionStartTime: expect.any(Date),
}),
);
- expect(mocks.trace.update.mock.calls[0][0]).not.toHaveProperty("output");
+ expect(mocks.trace.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ input: expectedAgentRunInput,
+ output: {
+ messages: [{ role: "assistant", content: "second turn output" }],
+ text: "second turn output",
+ },
+ }),
+ );
});
it("records AG-UI context in the agent generation input", () => {
@@ -543,7 +576,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.trace.generation).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: {
messages: [{ role: "user", content: "hello" }],
context: {
@@ -555,12 +588,22 @@ describe("InAppAgentInstrumentation", () => {
},
}),
);
- expect(mocks.handler.langfuse.trace.mock.calls[0][0]).not.toHaveProperty(
- "input",
+ expect(mocks.handler.langfuse.trace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ input: {
+ messages: [{ role: "user", content: "hello" }],
+ context: {
+ current_url:
+ "https://cloud.langfuse.com/project/project-1/traces?filter=value",
+ browser_languages: ["en-US", "en", "de"],
+ current_trace: { id: "trace-1" },
+ },
+ },
+ }),
);
});
- it("records replayed conversation messages in the agent generation input", () => {
+ it("records only the current turn messages in the agent generation input", () => {
createInstrumentation({
messages: [
{
@@ -605,29 +648,9 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.trace.generation).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: {
- messages: [
- { role: "user", content: "previous question" },
- {
- role: "assistant",
- content: "previous answer",
- tool_calls: [
- {
- id: "tool-previous",
- name: "getTrace",
- arguments: '{"traceId":"trace-1"}',
- type: "function",
- },
- ],
- },
- {
- role: "tool",
- tool_call_id: "tool-previous",
- content: { found: true },
- },
- { role: "user", content: "hello" },
- ],
+ messages: [{ role: "user", content: "hello" }],
},
}),
);
@@ -655,7 +678,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
output: {
messages: [{ role: "assistant", content: "chunk output" }],
@@ -691,7 +714,7 @@ describe("InAppAgentInstrumentation", () => {
expect(mocks.agentGeneration.update).toHaveBeenCalledWith(
expect.objectContaining({
- name: "agent-run",
+ name: "agent-turn",
input: expectedAgentRunInput,
output: {
messages: [{ role: "assistant", content: "Done" }],
@@ -733,7 +756,7 @@ function createInstrumentation(
userEmail: "[email protected]",
userProjectRole: "ADMIN",
userIsAdmin: true,
- traceId,
+ runId: input.runId,
targetProjectId: "project-1",
environment: "prod",
prompt,
diff --git a/web/src/ee/features/in-app-agent/constants.ts b/web/src/ee/features/in-app-agent/constants.ts
index 06b70100ff..32d474859e 100644
--- a/web/src/ee/features/in-app-agent/constants.ts
+++ b/web/src/ee/features/in-app-agent/constants.ts
@@ -5,3 +5,13 @@ export const IN_APP_AGENT_REDIRECT_TOOL_NAME = "langfuse_proposeRedirect";
// Langfuse MCP endpoint with a temporary in-app-agent API key and run override.
export const IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER =
"x-langfuse-in-app-agent-tool-override";
+
+// Observation ids stay equal to the per-turn run id so persisted messages,
+// feedback, and traced generations all point at the same Langfuse observation.
+export const getInAppAgentInstrumentationObservationId = (runId: string) =>
+ runId;
+
+// Each in-app agent turn gets its own trace derived from the run id so trace-
+// level telemetry and feedback aggregate on the same per-turn trace.
+export const getInAppAgentInstrumentationTraceId = (runId: string) =>
+ `${runId}-trace`;
diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.ts
index cf21f243b2..be8564a6f7 100644
--- a/web/src/ee/features/in-app-agent/server/handler.ts
+++ b/web/src/ee/features/in-app-agent/server/handler.ts
@@ -8,6 +8,7 @@ import {
createInAppAgentRunId,
} from "@/src/ee/features/in-app-agent/ids";
import { sanitizeInAppAgentContext } from "@/src/ee/features/in-app-agent/context";
+import { getInAppAgentInstrumentationTraceId } from "@/src/ee/features/in-app-agent/constants";
import {
AgUiRunAgentInputSchema,
type AgUiRunAgentInput,
@@ -460,8 +461,10 @@ export default async function handler(request: Request) {
environment: "langfuse-in-app-agent",
feature: "in-app-agent",
projectId,
- traceId: conversation.id,
- traceName: "in-app-agent",
+ traceId: getInAppAgentInstrumentationTraceId(
+ sanitizedInput.runId,
+ ),
+ traceName: "agent-turn",
userId,
metadata: {
langfuse_ai_feature: "in-app-agent",
@@ -482,13 +485,13 @@ export default async function handler(request: Request) {
? {
targetProjectId: traceSinkParams.targetProjectId,
environment: traceSinkParams.environment,
+ runId: sanitizedInput.runId,
user: {
id: userId,
email: user.email,
projectRole: userAccess.projectRole,
isAdmin: userAccess.isAdmin,
},
- traceId: traceSinkParams.traceId,
metadata: traceSinkParams.metadata ?? {},
}
: undefined;
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 edf82a3927..3857961e87 100644
--- a/web/src/ee/features/in-app-agent/server/instrumentation.ts
+++ b/web/src/ee/features/in-app-agent/server/instrumentation.ts
@@ -1,6 +1,10 @@
import { EventType } from "@ag-ui/core";
import { getInternalTracingHandler, logger } from "@langfuse/shared/src/server";
+import {
+ getInAppAgentInstrumentationObservationId,
+ getInAppAgentInstrumentationTraceId,
+} from "@/src/ee/features/in-app-agent/constants";
import type {
AgUiEvent,
AgUiMessage,
@@ -19,7 +23,7 @@ export type InAppAgentTracingConfig = {
// Global Langfuse admin flag. This bypasses project membership checks.
isAdmin: boolean;
};
- traceId: string;
+ runId: string;
targetProjectId: string;
prompt?: InAppAgentPromptMetadata;
};
@@ -34,8 +38,7 @@ export type InAppAgentPromptMetadata = {
version: number;
};
-const IN_APP_AGENT_TRACE_NAME = "in-app-agent";
-const IN_APP_AGENT_RUN_NAME = "agent-run";
+const IN_APP_AGENT_TURN_NAME = "agent-turn";
type InternalTracingHandler = ReturnType<typeof getInternalTracingHandler>;
type InAppAgentTrace = ReturnType<
InternalTracingHandler["handler"]["langfuse"]["trace"]
@@ -99,7 +102,7 @@ export function createInAppAgentInstrumentation({
userEmail: tracing.user.email,
userProjectRole: tracing.user.projectRole,
userIsAdmin: tracing.user.isAdmin,
- traceId: tracing.traceId,
+ runId: tracing.runId,
targetProjectId: tracing.targetProjectId,
environment: tracing.environment,
prompt: tracing.prompt,
@@ -147,7 +150,7 @@ export class InAppAgentInstrumentation {
userEmail?: string | null;
userProjectRole?: InAppAgentUserAccess["projectRole"];
userIsAdmin: boolean;
- traceId: string;
+ runId: string;
targetProjectId: string;
environment: string;
prompt?: InAppAgentPromptMetadata;
@@ -171,8 +174,8 @@ export class InAppAgentInstrumentation {
const traceSinkParams = {
targetProjectId: params.targetProjectId,
- traceId: params.traceId,
- traceName: IN_APP_AGENT_TRACE_NAME,
+ traceId: getInAppAgentInstrumentationTraceId(params.runId),
+ traceName: IN_APP_AGENT_TURN_NAME,
environment: params.environment,
userId: params.userId,
metadata: this.metadata,
@@ -184,16 +187,17 @@ export class InAppAgentInstrumentation {
this.langfuse = handler.langfuse;
this.trace = this.langfuse.trace({
- id: params.traceId,
- name: IN_APP_AGENT_TRACE_NAME,
+ id: getInAppAgentInstrumentationTraceId(params.runId),
+ name: IN_APP_AGENT_TURN_NAME,
userId: params.userId,
sessionId: params.input.threadId,
+ input: this.agentRunInput,
metadata: this.metadata,
tags: ["in-app-agent"],
});
this.agentRun = this.trace.generation({
- id: params.input.runId,
- name: IN_APP_AGENT_RUN_NAME,
+ id: getInAppAgentInstrumentationObservationId(params.input.runId),
+ name: IN_APP_AGENT_TURN_NAME,
input: this.agentRunInput,
metadata: this.metadata,
...(params.prompt
@@ -270,7 +274,7 @@ export class InAppAgentInstrumentation {
const message = error instanceof Error ? error.message : String(error);
this.endOpenToolSpans({ error: message }, message);
this.agentRun.update({
- name: IN_APP_AGENT_RUN_NAME,
+ name: IN_APP_AGENT_TURN_NAME,
input: this.agentRunInput,
output: this.getAgentRunOutput(),
...(this.completionStartTime
@@ -291,6 +295,8 @@ export class InAppAgentInstrumentation {
: {}),
});
this.trace.update({
+ input: this.agentRunInput,
+ output: this.getAgentRunOutput(),
metadata: { ...this.metadata, error: message },
});
this.agentRun.end();
@@ -310,7 +316,7 @@ export class InAppAgentInstrumentation {
...(params?.result ? { result: params.result } : {}),
};
this.agentRun.update({
- name: IN_APP_AGENT_RUN_NAME,
+ name: IN_APP_AGENT_TURN_NAME,
input: this.agentRunInput,
output: this.getAgentRunOutput(),
...(this.completionStartTime
@@ -324,7 +330,11 @@ export class InAppAgentInstrumentation {
}
: {}),
});
- this.trace.update({ metadata });
+ this.trace.update({
+ input: this.agentRunInput,
+ output: this.getAgentRunOutput(),
+ metadata,
+ });
this.agentRun.end();
this.ended = true;
}
@@ -605,7 +615,7 @@ export class InAppAgentInstrumentation {
}
function getAgentRunInput(input: AgUiRunAgentInput): unknown {
- const messages = getAgentRunMessages(input.messages);
+ const messages = getAgentRunMessages(getCurrentTurnMessages(input.messages));
const context = getAgentRunContext(input);
if (!context) {
@@ -618,6 +628,23 @@ function getAgentRunInput(input: AgUiRunAgentInput): unknown {
};
}
+function getCurrentTurnMessages(messages: AgUiMessage[]): AgUiMessage[] {
+ const lastUserMessageIndex = messages.findLastIndex(
+ (message) => message.role === "user",
+ );
+
+ if (lastUserMessageIndex === -1) {
+ return messages;
+ }
+
+ return messages.filter(
+ (message, index) =>
+ message.role === "developer" ||
+ message.role === "system" ||
+ index >= lastUserMessageIndex,
+ );
+}
+
function addAvailableToolsToAgentRunInput(
input: unknown,
tools: AgentRunToolDefinition[],
diff --git a/web/src/ee/features/in-app-agent/server/router.ts b/web/src/ee/features/in-app-agent/server/router.ts
index 58964912c7..4ded36eb6b 100644
--- a/web/src/ee/features/in-app-agent/server/router.ts
+++ b/web/src/ee/features/in-app-agent/server/router.ts
@@ -15,6 +15,10 @@ import {
upsertScore,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
+import {
+ getInAppAgentInstrumentationObservationId,
+ getInAppAgentInstrumentationTraceId,
+} from "@/src/ee/features/in-app-agent/constants";
import { InAppAgentMessageFeedbackValueSchema } from "@/src/ee/features/in-app-agent/schema";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
import {
@@ -244,8 +248,10 @@ export const inAppAgentRouter = createTRPCRouter({
timestamp: convertDateToClickhouseDateTime(now),
project_id: scoreProjectId,
environment: IN_APP_AGENT_FEEDBACK_ENVIRONMENT,
- trace_id: input.conversationId,
- observation_id: input.runId,
+ trace_id: getInAppAgentInstrumentationTraceId(input.runId),
+ observation_id: getInAppAgentInstrumentationObservationId(
+ input.runId,
+ ),
session_id: input.conversationId,
name: IN_APP_AGENT_FEEDBACK_SCORE_NAME,
value: input.value === "thumbs_up" ? 1 : 0,