Skip to content

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

feat(tracing): graph views for new observation types (#8690)

Nimar8f1a2022268e
diff --git a/CLAUDE.md b/CLAUDE.md
index 8e09fc504f..2bae2e2ace 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -85,6 +85,8 @@ Depending on the file location (sync, async)
pnpm test-sync --testPathPattern="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"
# For tests in the async folder:
pnpm test -- --testPathPattern="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"
+# For client tests:
+pnpm test-client --testPathPattern="buildStepData" --testNamePattern="buildStepData"
```
### Testing in the Worker Package
@@ -195,4 +197,4 @@ To get a project, use the `get_project` capability with the full project name as
- For easier code reviews, prefer not to move functions etc around within a file unless necessary or instructed to do so
## Development Tips
-- Before trying to build the package, try running the linter once first
\ No newline at end of file
+- Before trying to build the package, try running the linter once first
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index ee206eb991..3cb118b12c 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1995,6 +1995,10 @@ export async function getAgentGraphData(params: {
SELECT
id,
parent_observation_id,
+ type,
+ name,
+ start_time,
+ end_time,
metadata['langgraph_node'] AS node,
metadata['langgraph_step'] AS step
FROM
diff --git a/web/src/__tests__/buildStepData.clienttest.ts b/web/src/__tests__/buildStepData.clienttest.ts
new file mode 100644
index 0000000000..b6be052306
--- /dev/null
+++ b/web/src/__tests__/buildStepData.clienttest.ts
@@ -0,0 +1,404 @@
+// No test dependencies from shared
+jest.mock("@langfuse/shared", () => ({
+ ObservationType: {
+ SPAN: "SPAN",
+ EVENT: "EVENT",
+ GENERATION: "GENERATION",
+ AGENT: "AGENT",
+ TOOL: "TOOL",
+ CHAIN: "CHAIN",
+ RETRIEVER: "RETRIEVER",
+ EVALUATOR: "EVALUATOR",
+ EMBEDDING: "EMBEDDING",
+ GUARDRAIL: "GUARDRAIL",
+ },
+}));
+
+import { buildStepData } from "@/src/features/trace-graph-view/buildStepData";
+import { type AgentGraphDataResponse } from "@/src/features/trace-graph-view/types";
+
+describe("buildStepData", () => {
+ const createMockObservation = (
+ overrides: Partial<AgentGraphDataResponse> = {},
+ ): AgentGraphDataResponse => ({
+ id: "mock-id",
+ name: "mock-name",
+ node: null,
+ step: null,
+ parentObservationId: null,
+ startTime: "2025-08-21 18:53:25.571",
+ endTime: "2025-08-21 18:53:25.587",
+ observationType: "AGENT",
+ ...overrides,
+ });
+
+ describe("basic sequential timing", () => {
+ it("should put sequential observations in different steps", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "obs1",
+ name: "first",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.100",
+ }),
+ createMockObservation({
+ id: "obs2",
+ name: "second",
+ startTime: "2025-08-21 18:53:25.200", // Starts after first ends
+ endTime: "2025-08-21 18:53:25.300",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ // Remove system nodes for easier testing
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+
+ expect(userObservations).toHaveLength(2);
+
+ const first = userObservations.find((obs) => obs.name === "first");
+ const second = userObservations.find((obs) => obs.name === "second");
+
+ expect(first?.step).toBe(1);
+ expect(second?.step).toBe(2);
+ });
+ });
+
+ describe("overlapping observations", () => {
+ it("should put overlapping observations in same step", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "obs1",
+ name: "first",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.200",
+ }),
+ createMockObservation({
+ id: "obs2",
+ name: "second",
+ startTime: "2025-08-21 18:53:25.100", // Starts before first ends
+ endTime: "2025-08-21 18:53:25.300",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+
+ expect(userObservations).toHaveLength(2);
+
+ const first = userObservations.find((obs) => obs.name === "first");
+ const second = userObservations.find((obs) => obs.name === "second");
+
+ expect(first?.step).toBe(1);
+ expect(second?.step).toBe(1); // Same step due to overlap
+ });
+
+ it("should handle multiple parallel observations in same step", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "obs1",
+ name: "first",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.300",
+ }),
+ createMockObservation({
+ id: "obs2",
+ name: "second",
+ startTime: "2025-08-21 18:53:25.050", // Overlaps with first
+ endTime: "2025-08-21 18:53:25.250",
+ }),
+ createMockObservation({
+ id: "obs3",
+ name: "third",
+ startTime: "2025-08-21 18:53:25.150", // Overlaps with both first and second
+ endTime: "2025-08-21 18:53:25.400",
+ }),
+ createMockObservation({
+ id: "obs4",
+ name: "fourth",
+ startTime: "2025-08-21 18:53:25.500", // Starts after all others end - should be step 2
+ endTime: "2025-08-21 18:53:25.600",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+ expect(userObservations).toHaveLength(4);
+
+ const first = userObservations.find((obs) => obs.name === "first");
+ const second = userObservations.find((obs) => obs.name === "second");
+ const third = userObservations.find((obs) => obs.name === "third");
+ const fourth = userObservations.find((obs) => obs.name === "fourth");
+
+ // First three should all be in step 1 (parallel execution)
+ expect(first?.step).toBe(1);
+ expect(second?.step).toBe(1);
+ expect(third?.step).toBe(1);
+
+ // Fourth starts after all others end, so step 2 (sequential)
+ expect(fourth?.step).toBe(2);
+ });
+
+ it("should handle complex cleanup scenario - observation added then kicked out", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "obs1",
+ name: "long_task",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.500", // Long running task
+ }),
+ createMockObservation({
+ id: "obs2",
+ name: "short_overlap",
+ startTime: "2025-08-21 18:53:25.100", // Starts before long_task ends (gets added to group)
+ endTime: "2025-08-21 18:53:25.150", // But ends early
+ }),
+ createMockObservation({
+ id: "obs3",
+ name: "late_start",
+ startTime: "2025-08-21 18:53:25.200", // Starts after short_overlap ends (gets kicked out during cleanup)
+ endTime: "2025-08-21 18:53:25.300",
+ }),
+ createMockObservation({
+ id: "obs4",
+ name: "independent",
+ startTime: "2025-08-21 18:53:25.600", // Completely separate, should be step 3
+ endTime: "2025-08-21 18:53:25.700",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+ expect(userObservations).toHaveLength(4);
+
+ const longTask = userObservations.find((obs) => obs.name === "long_task");
+ const shortOverlap = userObservations.find(
+ (obs) => obs.name === "short_overlap",
+ );
+ const lateStart = userObservations.find(
+ (obs) => obs.name === "late_start",
+ );
+ const independent = userObservations.find(
+ (obs) => obs.name === "independent",
+ );
+
+ // Expected behavior:
+ // Step 1: long_task, short_overlap (they overlap)
+ // late_start initially gets added because it starts before long_task ends (200 < 500)
+ // BUT during cleanup, late_start gets kicked out because it starts after short_overlap ends (200 >= 150)
+ // Step 2: late_start (processed in recursive call)
+ // Step 3: independent (completely separate)
+
+ expect(longTask?.step).toBe(1);
+ expect(shortOverlap?.step).toBe(1); // Overlaps with long_task
+ expect(lateStart?.step).toBe(2); // Kicked out during cleanup, processed recursively
+ expect(independent?.step).toBe(3); // Sequential after everything else
+ });
+ });
+
+ describe("parent-child constraints", () => {
+ it("should enforce parent-child step ordering", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "parent",
+ name: "parent_task",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.100",
+ parentObservationId: null,
+ }),
+ createMockObservation({
+ id: "child",
+ name: "child_task",
+ startTime: "2025-08-21 18:53:25.050", // Overlaps with parent
+ endTime: "2025-08-21 18:53:25.150",
+ parentObservationId: "parent",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+
+ const parent = userObservations.find((obs) => obs.name === "parent_task");
+ const child = userObservations.find((obs) => obs.name === "child_task");
+
+ expect(parent?.step).toBe(1);
+ expect(child?.step).toBe(2); // Must be after parent despite timing overlap
+ });
+
+ it("should push subsequent steps forward when inserting child", () => {
+ const observations: AgentGraphDataResponse[] = [
+ // Parent in step 1
+ createMockObservation({
+ id: "parent",
+ name: "parent_task",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.100",
+ parentObservationId: null,
+ }),
+ // Child that would be step 1 due to timing, but should be step 2 due to parent constraint
+ createMockObservation({
+ id: "child",
+ name: "child_task",
+ startTime: "2025-08-21 18:53:25.050",
+ endTime: "2025-08-21 18:53:25.080",
+ parentObservationId: "parent",
+ }),
+ // Independent task that would be step 2 due to timing, should be pushed to step 3
+ createMockObservation({
+ id: "independent",
+ name: "independent_task",
+ startTime: "2025-08-21 18:53:25.200",
+ endTime: "2025-08-21 18:53:25.300",
+ parentObservationId: null,
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+
+ const parent = userObservations.find((obs) => obs.name === "parent_task");
+ const child = userObservations.find((obs) => obs.name === "child_task");
+ const independent = userObservations.find(
+ (obs) => obs.name === "independent_task",
+ );
+
+ expect(parent?.step).toBe(1);
+ expect(child?.step).toBe(2); // Inserted due to parent constraint
+ expect(independent?.step).toBe(3); // Pushed forward
+ });
+
+ it("should handle parent appearing after child in array processing order", () => {
+ const observations: AgentGraphDataResponse[] = [
+ // Child appears FIRST in array (would be processed first in loop)
+ createMockObservation({
+ id: "child",
+ name: "child_task",
+ startTime: "2025-08-21 18:53:25.050", // Overlaps with parent timing-wise
+ endTime: "2025-08-21 18:53:25.080",
+ parentObservationId: "parent",
+ }),
+ // Parent appears SECOND in array (would be processed second in loop)
+ createMockObservation({
+ id: "parent",
+ name: "parent_task",
+ startTime: "2025-08-21 18:53:25.000",
+ endTime: "2025-08-21 18:53:25.100",
+ parentObservationId: null,
+ }),
+ ];
+
+ const result = buildStepData(observations);
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+
+ const parent = userObservations.find((obs) => obs.name === "parent_task");
+ const child = userObservations.find((obs) => obs.name === "child_task");
+
+ // Should still enforce parent-child constraint despite processing order
+ expect(parent?.step).toBe(1);
+ expect(child?.step).toBe(2);
+ });
+ });
+
+ describe("real scenario - joke evaluation case", () => {
+ it("should handle the create_joke_evaluation_agent and get_joke_database_inspiration case", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "785eaa36815cb1fa",
+ name: "run_smolagents_joke_evaluation",
+ startTime: "2025-08-21 18:53:25.570",
+ endTime: "2025-08-21 18:53:40.573",
+ parentObservationId: null,
+ }),
+ createMockObservation({
+ id: "b8fcc9d3cf148524",
+ name: "create_joke_evaluation_agent",
+ startTime: "2025-08-21 18:53:25.571",
+ endTime: "2025-08-21 18:53:25.587",
+ parentObservationId: "785eaa36815cb1fa",
+ }),
+ createMockObservation({
+ id: "55821479672f1de5",
+ name: "get_joke_database_inspiration",
+ startTime: "2025-08-21 18:53:27.446", // Starts after create_joke ends
+ endTime: "2025-08-21 18:53:27.446",
+ parentObservationId: "785eaa36815cb1fa",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+
+ const runAgent = userObservations.find(
+ (obs) => obs.name === "run_smolagents_joke_evaluation",
+ );
+ const createAgent = userObservations.find(
+ (obs) => obs.name === "create_joke_evaluation_agent",
+ );
+ const getData = userObservations.find(
+ (obs) => obs.name === "get_joke_database_inspiration",
+ );
+
+ expect(runAgent?.step).toBe(1);
+ expect(createAgent?.step).toBe(2); // Child of run_agent, so step 2
+ expect(getData?.step).toBe(3); // Child of run_agent, but starts after create_agent ends, so step 3
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle empty array", () => {
+ const result = buildStepData([]);
+ // Should only have system nodes (__start__, __end__)
+ expect(result).toHaveLength(2);
+ expect(result.every((obs) => obs.name.includes("__"))).toBe(true);
+ });
+
+ it("should handle single observation", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "single",
+ name: "single_task",
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ // Should have single observation plus system nodes
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+ expect(userObservations).toHaveLength(1);
+ expect(userObservations[0].step).toBe(1);
+ });
+
+ it("should filter out EVENT observation types", () => {
+ const observations: AgentGraphDataResponse[] = [
+ createMockObservation({
+ id: "agent",
+ name: "agent_task",
+ observationType: "AGENT",
+ }),
+ createMockObservation({
+ id: "span",
+ name: "span_task",
+ observationType: "SPAN", // Currently not filtered out
+ }),
+ createMockObservation({
+ id: "event",
+ name: "event_task",
+ observationType: "EVENT", // Should be filtered out
+ }),
+ ];
+
+ const result = buildStepData(observations);
+
+ const userObservations = result.filter((obs) => !obs.name.includes("__"));
+ expect(userObservations).toHaveLength(2);
+ expect(userObservations[0].name).toBe("agent_task");
+ expect(userObservations[1].name).toBe("span_task");
+ });
+ });
+});
diff --git a/web/src/components/ItemBadge.tsx b/web/src/components/ItemBadge.tsx
index ee4229f98c..2e2d6d748e 100644
--- a/web/src/components/ItemBadge.tsx
+++ b/web/src/components/ItemBadge.tsx
@@ -70,7 +70,7 @@ const iconVariants = cva(cn("h-4 w-4"), {
SPAN: "text-muted-blue",
AGENT: "text-purple-600",
TOOL: "text-orange-600",
- CHAIN: "text-violet-600",
+ CHAIN: "text-pink-600",
RETRIEVER: "text-teal-600",
EMBEDDING: "text-amber-600",
GUARDRAIL: "text-red-600",
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index fa6990f7ae..dd917470b3 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -175,8 +175,30 @@ export function Trace(props: {
},
);
- const agentGraphData = agentGraphDataQuery.data ?? [];
- const isGraphViewAvailable = agentGraphData.length > 0;
+ const agentGraphData = useMemo(() => {
+ return agentGraphDataQuery.data ?? [];
+ }, [agentGraphDataQuery.data]);
+
+ const isGraphViewAvailable = useMemo(() => {
+ if (agentGraphData.length === 0) {
+ return false;
+ }
+
+ // Check if there are observations that would be included in the graph (not SPAN, EVENT, or GENERATION)
+ const hasGraphableObservations = agentGraphData.some((obs) => {
+ return (
+ obs.observationType !== "SPAN" &&
+ obs.observationType !== "EVENT" &&
+ obs.observationType !== "GENERATION"
+ );
+ });
+
+ const hasLangGraphData = agentGraphData.some(
+ (obs) => obs.step != null && obs.step !== 0,
+ );
+
+ return hasGraphableObservations || hasLangGraphData;
+ }, [agentGraphData]);
const toggleCollapsedNode = useCallback((id: string) => {
setCollapsedNodes((prev) =>
diff --git a/web/src/features/trace-graph-view/buildGraphCanvasData.ts b/web/src/features/trace-graph-view/buildGraphCanvasData.ts
new file mode 100644
index 0000000000..8a304fbb7c
--- /dev/null
+++ b/web/src/features/trace-graph-view/buildGraphCanvasData.ts
@@ -0,0 +1,193 @@
+import {
+ type GraphCanvasData,
+ type GraphNodeData,
+ type AgentGraphDataResponse,
+ LANGGRAPH_START_NODE_NAME,
+ LANGGRAPH_END_NODE_NAME,
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+} from "./types";
+
+export interface GraphParseResult {
+ graph: GraphCanvasData;
+ nodeToParentObservationMap: Record<string, string>;
+}
+
+export function transformLanggraphToGeneralized(
+ data: AgentGraphDataResponse[],
+): AgentGraphDataResponse[] {
+ // can't draw nodes without `node` property set for LangGraph
+ const filteredData = data.filter(
+ (obs) => obs.node && obs.node.trim().length > 0,
+ );
+
+ const transformedData = filteredData.map((obs) => {
+ let transformedObs = {
+ ...obs,
+ // fallback to node name if node empty (shouldn't happen!)
+ name: obs.node || obs.name,
+ };
+
+ // Transform system nodes to Langfuse system nodes
+ if (obs.node === LANGGRAPH_START_NODE_NAME) {
+ transformedObs.name = LANGFUSE_START_NODE_NAME;
+ transformedObs.id = LANGFUSE_START_NODE_NAME;
+ } else if (obs.node === LANGGRAPH_END_NODE_NAME) {
+ transformedObs.name = LANGFUSE_END_NODE_NAME;
+ transformedObs.id = LANGFUSE_END_NODE_NAME;
+ }
+
+ return transformedObs;
+ });
+
+ // Add Langfuse system nodes if they don't exist
+ const hasStartNode = transformedData.some(
+ (obs) => obs.name === LANGFUSE_START_NODE_NAME,
+ );
+ const hasEndNode = transformedData.some(
+ (obs) => obs.name === LANGFUSE_END_NODE_NAME,
+ );
+
+ const systemNodes: AgentGraphDataResponse[] = [];
+
+ if (!hasStartNode) {
+ // Find the top-level parent for system node mapping
+ const topLevelObs = transformedData.find((obs) => !obs.parentObservationId);
+ systemNodes.push({
+ id: LANGFUSE_START_NODE_NAME,
+ name: LANGFUSE_START_NODE_NAME,
+ node: LANGFUSE_START_NODE_NAME,
+ step: 0,
+ parentObservationId: topLevelObs?.parentObservationId || null,
+ startTime: new Date().toISOString(),
+ endTime: new Date().toISOString(),
+ observationType: "LANGGRAPH_SYSTEM",
+ });
+ }
+
+ if (!hasEndNode) {
+ const topLevelObs = transformedData.find((obs) => !obs.parentObservationId);
+ const maxStep = Math.max(...transformedData.map((obs) => obs.step || 0));
+ systemNodes.push({
+ id: LANGFUSE_END_NODE_NAME,
+ name: LANGFUSE_END_NODE_NAME,
+ node: LANGFUSE_END_NODE_NAME,
+ step: maxStep + 1,
+ parentObservationId: topLevelObs?.parentObservationId || null,
+ startTime: new Date().toISOString(),
+ endTime: new Date().toISOString(),
+ observationType: "LANGGRAPH_SYSTEM",
+ });
+ }
+
+ return [...transformedData, ...systemNodes];
+}
+
+export function buildGraphFromStepData(
+ data: AgentGraphDataResponse[],
+): GraphParseResult {
+ if (data.length === 0) {
+ return {
+ graph: { nodes: [], edges: [] },
+ nodeToParentObservationMap: {},
+ };
+ }
+
+ const stepToNodesMap = new Map<number, Set<string>>();
+ const nodeToParentObservationMap = new Map<string, string>();
+
+ data.forEach((obs) => {
+ const { node, step } = obs;
+
+ if (step !== null && node !== null) {
+ if (!stepToNodesMap.has(step)) {
+ stepToNodesMap.set(step, new Set());
+ }
+ stepToNodesMap.get(step)!.add(node);
+ }
+
+ if (obs.parentObservationId) {
+ const parent = data.find((o) => o.id === obs.parentObservationId);
+ // initialize the end node to point to the top-most span
+ if (!parent) {
+ nodeToParentObservationMap.set(
+ LANGFUSE_END_NODE_NAME,
+ obs.parentObservationId,
+ );
+ }
+
+ // Only register id if it is top-most to allow navigation on node click in graph
+ if (obs.name !== parent?.name && node !== null) {
+ nodeToParentObservationMap.set(node, obs.id);
+ }
+ } else if (node !== null) {
+ nodeToParentObservationMap.set(node, obs.id);
+ }
+ });
+
+ // Build nodes from step mapping
+ const allStepNodes = Array.from(stepToNodesMap.values()).flatMap((set) =>
+ Array.from(set),
+ );
+ const nodeNames = [...new Set([...allStepNodes, LANGFUSE_END_NODE_NAME])];
+
+ const nodes: GraphNodeData[] = nodeNames.map((nodeName) => {
+ if (
+ nodeName === LANGFUSE_END_NODE_NAME ||
+ nodeName === LANGFUSE_START_NODE_NAME
+ ) {
+ return {
+ id: nodeName,
+ label: nodeName,
+ type: "LANGGRAPH_SYSTEM",
+ };
+ }
+ const obs = data.find((o) => o.node === nodeName);
+ return {
+ id: nodeName,
+ label: nodeName,
+ type: obs?.observationType || "UNKNOWN",
+ };
+ });
+
+ const edges = generateEdgesWithParallelBranches(stepToNodesMap);
+
+ return {
+ graph: { nodes, edges },
+ nodeToParentObservationMap: Object.fromEntries(
+ nodeToParentObservationMap.entries(),
+ ),
+ };
+}
+
+function generateEdgesWithParallelBranches(
+ stepToNodesMap: Map<number, Set<string>>,
+) {
+ // generate edges with proper parallel branch handling
+ const sortedSteps = [...stepToNodesMap.entries()].sort(([a], [b]) => a - b);
+ const edges: Array<{ from: string; to: string }> = [];
+
+ sortedSteps.forEach(([, currentNodes], i) => {
+ const isLastStep = i === sortedSteps.length - 1;
+ const targetNodes = isLastStep
+ ? [LANGFUSE_END_NODE_NAME]
+ : Array.from(sortedSteps[i + 1][1]);
+
+ // connect all current nodes to all target nodes
+ Array.from(currentNodes).forEach((currentNode) => {
+ // end nodes should be terminal -> don't draw edges from them
+ if (
+ currentNode === LANGFUSE_END_NODE_NAME ||
+ currentNode === LANGGRAPH_END_NODE_NAME
+ ) {
+ return;
+ }
+
+ targetNodes.forEach((targetNode) => {
+ edges.push({ from: currentNode, to: targetNode });
+ });
+ });
+ });
+
+ return edges;
+}
diff --git a/web/src/features/trace-graph-view/buildStepData.ts b/web/src/features/trace-graph-view/buildStepData.ts
new file mode 100644
index 0000000000..be9510961b
--- /dev/null
+++ b/web/src/features/trace-graph-view/buildStepData.ts
@@ -0,0 +1,232 @@
+import { ObservationType } from "@langfuse/shared";
+import {
+ type AgentGraphDataResponse,
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+} from "./types";
+
+const MAX_NODE_NUMBER_FOR_PERFORMANCE = 250;
+
+function buildStepGroups(
+ observations: AgentGraphDataResponse[],
+ timestampCache: Map<string, { start: number; end: number }>,
+): AgentGraphDataResponse[][] {
+ if (observations.length === 0) return [];
+
+ const stepGroups: AgentGraphDataResponse[][] = [];
+
+ // create observation group and put the beginning observation in it
+ let currentGroup = [observations[0]];
+ const remainingObs = observations.slice(1);
+
+ // loop through all remaining observations that are not added to any group yet
+ for (const obs of remainingObs) {
+ const obsStart = timestampCache.get(obs.id)!.start;
+
+ // TODO: perf, could break early if current observation starts after all current group members finish
+
+ // if observation starts before any observations in current group finished, add it to the current group
+ const startsBeforeAnyFinishes = currentGroup.some((groupObs) => {
+ const groupEnd = timestampCache.get(groupObs.id)!.end;
+ return obsStart < groupEnd;
+ });
+
+ if (startsBeforeAnyFinishes) {
+ currentGroup.push(obs);
+ }
+ }
+
+ const cleanedGroup: AgentGraphDataResponse[] = [];
+
+ // build final current group. check if observation doesn't start after any finishes, only then add it
+ currentGroup.forEach((obs) => {
+ const obsStart = timestampCache.get(obs.id)!.start;
+
+ const startsAfterAnyOtherFinishes = currentGroup.some((otherObs) => {
+ if (otherObs === obs) return false;
+
+ const otherEnd = timestampCache.get(otherObs.id)!.end;
+ return obsStart >= otherEnd;
+ });
+
+ if (!startsAfterAnyOtherFinishes) {
+ cleanedGroup.push(obs);
+ }
+ });
+
+ stepGroups.push(cleanedGroup);
+
+ // Find unprocessed by checking what's not in cleanedGroup
+ // TODO: perf, can track unprocessed while building cleanedGroup
+ const processedIds = new Set(cleanedGroup.map((obs) => obs.id));
+ const unprocessed = observations.filter((obs) => !processedIds.has(obs.id));
+
+ // process remaining observations in recursion
+ if (unprocessed.length > 0) {
+ const remainingStepGroups = buildStepGroups(unprocessed, timestampCache);
+ stepGroups.push(...remainingStepGroups);
+ }
+
+ return stepGroups;
+}
+
+function assignGlobalTimingSteps(
+ data: AgentGraphDataResponse[],
+): AgentGraphDataResponse[] {
+ const dataCopy: AgentGraphDataResponse[] = [];
+ const timestampCache = new Map<string, { start: number; end: number }>();
+ for (const obs of data) {
+ const obsCopy = { ...obs };
+ dataCopy.push(obsCopy);
+ timestampCache.set(obs.id, {
+ start: new Date(obs.startTime).getTime(),
+ end: obs.endTime
+ ? new Date(obs.endTime).getTime()
+ : new Date(obs.startTime).getTime(),
+ });
+ }
+
+ // sort observations by start time
+ const sortedObs = [...dataCopy].sort(
+ (a, b) => timestampCache.get(a.id)!.start - timestampCache.get(b.id)!.start,
+ );
+
+ const stepGroups = buildStepGroups(sortedObs, timestampCache);
+
+ // assign step numbers and flatten
+ let result: AgentGraphDataResponse[] = [];
+ stepGroups.forEach((group, stepIndex) => {
+ group.forEach((obs) => {
+ obs.step = stepIndex + 1;
+ obs.node = obs.name;
+ result.push(obs);
+ });
+ });
+
+ // apply span parent-child step constraint: any child must be at least parent_step + 1
+ // any step groups down the line will be pushed down by the same amount
+ let constraintViolations = true;
+
+ while (constraintViolations) {
+ constraintViolations = false;
+
+ // Track step adjustments to apply during result building
+ const stepAdjustments = new Map<string, number>();
+ const idToStepMap = new Map<string, number>();
+
+ // build step map while tracking step adjustments
+ for (const obs of result) {
+ stepAdjustments.set(obs.id, 0); // Initialize adjustment
+ idToStepMap.set(obs.id, obs.step!); // we checked against null already
+ }
+
+ const stepPushes: Array<{ fromStep: number; pushCount: number }> = [];
+ // identify if any spans must be pushed down
+ for (const obs of result) {
+ if (obs.parentObservationId) {
+ const parentStep = idToStepMap.get(obs.parentObservationId);
+ const currentStep = obs.step;
+ if (
+ parentStep !== undefined &&
+ parentStep !== null &&
+ currentStep !== null
+ ) {
+ const requiredMinStep = parentStep + 1;
+ if (currentStep < requiredMinStep) {
+ // Track step push: all observations at requiredMinStep+ need +1
+ stepPushes.push({ fromStep: requiredMinStep, pushCount: 1 });
+
+ stepAdjustments.set(obs.id, requiredMinStep - currentStep);
+ constraintViolations = true;
+ }
+ }
+ }
+ }
+
+ // apply step pushes by directly incrementing affected observations
+ for (const push of stepPushes) {
+ for (const obs of result) {
+ if (obs.step !== null && obs.step >= push.fromStep) {
+ const currentAdjustment = stepAdjustments.get(obs.id) || 0;
+ stepAdjustments.set(obs.id, currentAdjustment + push.pushCount);
+ }
+ }
+ }
+
+ // Build result with step adjustments applied
+ result = result.map((obs) => ({
+ ...obs,
+ step:
+ obs.step !== null
+ ? obs.step + (stepAdjustments.get(obs.id) || 0)
+ : obs.step,
+ }));
+ } // end loop to check if parent-child constraints require step adjustments
+
+ return result;
+}
+
+function addLangfuseSystemNodes(
+ data: AgentGraphDataResponse[],
+): AgentGraphDataResponse[] {
+ const systemNodes: AgentGraphDataResponse[] = [];
+
+ // Find the top-level parent for system node mapping
+ const topLevelObs = data.find((obs) => !obs.parentObservationId);
+
+ // Use deterministic timestamp to avoid infinite re-renders
+ const systemTimestamp = "2024-01-01T00:00:00.000Z";
+
+ // Add __start_lf__ node at step 0
+ systemNodes.push({
+ id: LANGFUSE_START_NODE_NAME,
+ name: LANGFUSE_START_NODE_NAME,
+ node: LANGFUSE_START_NODE_NAME,
+ step: 0,
+ parentObservationId: topLevelObs?.parentObservationId || null,
+ startTime: systemTimestamp,
+ endTime: systemTimestamp,
+ observationType: "LANGGRAPH_SYSTEM",
+ });
+
+ // Add __end_lf__ node at max step + 1
+ const maxStep = Math.max(...data.map((obs) => obs.step || 0));
+ systemNodes.push({
+ id: LANGFUSE_END_NODE_NAME,
+ name: LANGFUSE_END_NODE_NAME,
+ node: LANGFUSE_END_NODE_NAME,
+ step: maxStep + 1,
+ parentObservationId: topLevelObs?.parentObservationId || null,
+ startTime: systemTimestamp,
+ endTime: systemTimestamp,
+ observationType: "LANGGRAPH_SYSTEM",
+ });
+
+ return [...data, ...systemNodes];
+}
+
+export function buildStepData(
+ agentGraphData: AgentGraphDataResponse[],
+): AgentGraphDataResponse[] {
+ if (agentGraphData.length >= MAX_NODE_NUMBER_FOR_PERFORMANCE) {
+ return [];
+ }
+
+ // for now, we don't want to show SPAN/EVENTs in our agent graphs
+ // TODO: move this filter to a separate function
+ const filteredData = agentGraphData.filter(
+ (item) =>
+ // Just not show events for now
+ // item.observationType !== ObservationType.SPAN &&
+ // item.observationType !== ObservationType.GENERATION &&
+ item.observationType !== ObservationType.EVENT,
+ );
+
+ // Assign step numbers based on global timing analysis
+ const dataWithSteps = assignGlobalTimingSteps(filteredData);
+
+ // Add Langfuse system nodes to make it consistent with LangGraph path
+ const dataWithSystemNodes = addLangfuseSystemNodes(dataWithSteps);
+
+ return dataWithSystemNodes;
+}
diff --git a/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsx b/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsx
index 20e51de02c..3ba7330e5b 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsx
@@ -3,6 +3,12 @@ import { Network } from "vis-network/standalone";
import { ZoomIn, ZoomOut } from "lucide-react";
import type { GraphCanvasData } from "../types";
+import {
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+ LANGGRAPH_START_NODE_NAME,
+ LANGGRAPH_END_NODE_NAME,
+} from "../types";
import { Button } from "@/src/components/ui/button";
type TraceGraphCanvasProps = {
@@ -18,20 +24,97 @@ export const TraceGraphCanvas: React.FC<TraceGraphCanvasProps> = (props) => {
const containerRef = useRef<HTMLDivElement>(null);
const networkRef = useRef<Network | null>(null);
+ const getNodeStyle = (nodeType: string) => {
+ switch (nodeType) {
+ case "AGENT":
+ return {
+ border: "#9333ea", // purple-600 (text-purple-600)
+ background: "#c4b5fd", // purple-300
+ highlight: { border: "#7c3aed", background: "#a78bfa" },
+ };
+ case "TOOL":
+ return {
+ border: "#ea580c", // orange-600 (text-orange-600)
+ background: "#fed7aa", // orange-300
+ highlight: { border: "#dc2626", background: "#fdba74" },
+ };
+ case "GENERATION":
+ return {
+ border: "#c026d3", // magenta/fuchsia-600 (text-muted-magenta)
+ background: "#f0abfc", // fuchsia-300
+ highlight: { border: "#a21caf", background: "#e879f9" },
+ };
+ case "SPAN":
+ return {
+ border: "#2563eb", // blue-600 (text-muted-blue)
+ background: "#93c5fd", // blue-300
+ highlight: { border: "#1d4ed8", background: "#60a5fa" },
+ };
+ case "CHAIN":
+ return {
+ border: "#db2777", // pink-600 (text-pink-600)
+ background: "#f9a8d4", // pink-300
+ highlight: { border: "#be185d", background: "#f472b6" },
+ };
+ case "RETRIEVER":
+ return {
+ border: "#0d9488", // teal-600 (text-teal-600)
+ background: "#5eead4", // teal-300
+ highlight: { border: "#0f766e", background: "#2dd4bf" },
+ };
+ case "EVENT":
+ return {
+ border: "#059669", // green-600 (text-muted-green)
+ background: "#6ee7b7", // green-300
+ highlight: { border: "#047857", background: "#34d399" },
+ };
+ case "EMBEDDING":
+ return {
+ border: "#d97706", // amber-600 (text-amber-600)
+ background: "#fbbf24", // amber-300
+ highlight: { border: "#b45309", background: "#f59e0b" },
+ };
+ case "GUARDRAIL":
+ return {
+ border: "#dc2626", // red-600 (text-red-600)
+ background: "#fca5a5", // red-300
+ highlight: { border: "#b91c1c", background: "#f87171" },
+ };
+ case "LANGGRAPH_SYSTEM":
+ return {
+ border: "#374151", // gray
+ background: "#d1d5db",
+ highlight: { border: "#1f2937", background: "#9ca3af" },
+ };
+ default:
+ return {
+ border: "#1e3a8a", // default blue
+ background: "#93c5fd",
+ highlight: { border: "#1e40af", background: "#60a5fa" },
+ };
+ }
+ };
+
const nodes = useMemo(
() =>
graphData.nodes.map((node) => {
const nodeData = {
- id: node,
- label: node,
+ id: node.id,
+ label: node.label,
+ color: getNodeStyle(node.type),
};
- if (node === "__start__") {
+
+ // Special positioning and colors for system nodes
+ if (
+ node.id === LANGFUSE_START_NODE_NAME ||
+ node.id === LANGGRAPH_START_NODE_NAME
+ ) {
return {
...nodeData,
x: -200,
y: 0,
color: {
- border: "#166534",
+ border: "#166534", // green
background: "#86efac",
highlight: {
border: "#15803d",
@@ -40,13 +123,16 @@ export const TraceGraphCanvas: React.FC<TraceGraphCanvasProps> = (props) => {
},
};
}
- if (node === "__end__") {
+ if (
+ node.id === LANGFUSE_END_NODE_NAME ||
+ node.id === LANGGRAPH_END_NODE_NAME
+ ) {
return {
...nodeData,
x: 200,
y: 0,
color: {
- border: "#7f1d1d",
+ border: "#7f1d1d", // red
background: "#fecaca",
highlight: {
border: "#991b1b",
@@ -84,14 +170,6 @@ export const TraceGraphCanvas: React.FC<TraceGraphCanvasProps> = (props) => {
left: 10,
},
borderWidth: 1,
- color: {
- border: "#1e3a8a",
- background: "#93c5fd",
- highlight: {
- border: "#1e40af",
- background: "#60a5fa",
- },
- },
font: {
size: 14,
color: "#000000",
@@ -184,7 +262,9 @@ export const TraceGraphCanvas: React.FC<TraceGraphCanvasProps> = (props) => {
if (selectedNodeName) {
// Validate that the node exists before trying to select it
- const nodeExists = graphData.nodes.includes(selectedNodeName);
+ const nodeExists = graphData.nodes.some(
+ (node) => node.id === selectedNodeName,
+ );
if (nodeExists) {
try {
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
index 36bdd1e25c..34e3cdd8fa 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
@@ -2,43 +2,67 @@ import React, { useEffect, useState, useMemo, useCallback } from "react";
import { StringParam, useQueryParam } from "use-query-params";
import { TraceGraphCanvas } from "./TraceGraphCanvas";
+import { type AgentGraphDataResponse } from "../types";
+import { buildStepData } from "../buildStepData";
import {
- type GraphCanvasData,
- LANGGRAPH_END_NODE_NAME,
- type AgentGraphDataResponse,
- LANGGRAPH_START_NODE_NAME,
-} from "../types";
+ buildGraphFromStepData,
+ transformLanggraphToGeneralized,
+} from "../buildGraphCanvasData";
type TraceGraphViewProps = {
agentGraphData: AgentGraphDataResponse[];
};
-export const TraceGraphView: React.FC<TraceGraphViewProps> = (props) => {
- const { agentGraphData } = props;
-
+export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
+ agentGraphData,
+}) => {
const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);
- const { graph, nodeToParentObservationMap } = useMemo(
- () => parseGraph({ agentGraphData }),
- [agentGraphData],
- );
-
const [currentObservationId, setCurrentObservationId] = useQueryParam(
"observation",
StringParam,
);
+ const normalizedData = useMemo(() => {
+ const hasStepData = agentGraphData.some(
+ (o) => o.step != null && o.step !== 0 && o.node != null,
+ );
+ if (!hasStepData) {
+ // has no steps → add timing-based steps
+ return buildStepData(agentGraphData);
+ } else {
+ const isLangGraph = agentGraphData.some(
+ (o) => o.node && o.node.trim().length > 0,
+ );
+ if (isLangGraph) {
+ // TODO: make detection more robust based on metadata
+ return transformLanggraphToGeneralized(agentGraphData);
+ } else {
+ return agentGraphData; // Already normalized
+ }
+ }
+ }, [agentGraphData]);
+
+ const { graph, nodeToParentObservationMap } = useMemo(() => {
+ return buildGraphFromStepData(normalizedData);
+ }, [normalizedData]);
+
useEffect(() => {
- const nodeName = agentGraphData.find(
- (o) => o.id === currentObservationId,
- )?.node;
+ const nodeName = Object.keys(nodeToParentObservationMap).find(
+ (nodeKey) => nodeToParentObservationMap[nodeKey] === currentObservationId,
+ );
// Only set selectedNodeName if the node actually exists in the graph
- if (nodeName && graph.nodes.includes(nodeName)) {
+ if (nodeName && graph.nodes.some((node) => node.id === nodeName)) {
setSelectedNodeName(nodeName);
} else {
setSelectedNodeName(null);
}
- }, [currentObservationId, agentGraphData, graph.nodes]);
+ }, [
+ currentObservationId,
+ agentGraphData,
+ graph.nodes,
+ nodeToParentObservationMap,
+ ]);
const onCanvasNodeNameChange = useCallback(
(nodeName: string | null) => {
@@ -64,70 +88,3 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = (props) => {
</div>
);
};
-
-function parseGraph(params: { agentGraphData: AgentGraphDataResponse[] }): {
- graph: GraphCanvasData;
- nodeToParentObservationMap: Record<string, string>;
-} {
- const { agentGraphData } = params;
-
- const stepToNodeMap = new Map<number, string>();
- const nodeToParentObservationMap = new Map<string, string>();
-
- agentGraphData.forEach((o) => {
- const { node, step } = o;
-
- stepToNodeMap.set(step, node);
-
- if (o.parentObservationId) {
- const parent = agentGraphData.find(
- (obs) => obs.id === o.parentObservationId,
- );
-
- // initialize the end node to point to the top-most langgraph span
- if (!parent) {
- nodeToParentObservationMap.set(
- LANGGRAPH_END_NODE_NAME,
- o.parentObservationId,
- );
-
- // Also initialize the start node if it hasn't been seen yet
- // Langgraph >= v4 is no longer adding a span for the start node
- if (!nodeToParentObservationMap.has(LANGGRAPH_START_NODE_NAME)) {
- stepToNodeMap.set(0, LANGGRAPH_START_NODE_NAME);
- nodeToParentObservationMap.set(
- LANGGRAPH_START_NODE_NAME,
- o.parentObservationId,
- );
- }
- }
-
- // Only register id if it is top-most to allow navigation on node click in graph
- if (o.node !== parent?.node) {
- nodeToParentObservationMap.set(node, o.id);
- }
- } else {
- nodeToParentObservationMap.set(node, o.id);
- }
- });
-
- const nodes = [
- ...new Set([...stepToNodeMap.values(), LANGGRAPH_END_NODE_NAME]),
- ];
- const edges = [...stepToNodeMap.entries()]
- .sort((a, b) => a[0] - b[0])
- .map(([_, node], idx, arr) => ({
- from: node,
- to: idx === arr.length - 1 ? LANGGRAPH_END_NODE_NAME : arr[idx + 1][1],
- }));
-
- return {
- graph: {
- nodes,
- edges,
- },
- nodeToParentObservationMap: Object.fromEntries(
- nodeToParentObservationMap.entries(),
- ),
- };
-}
diff --git a/web/src/features/trace-graph-view/types.ts b/web/src/features/trace-graph-view/types.ts
index 39c136fd30..a1f3ae54fc 100644
--- a/web/src/features/trace-graph-view/types.ts
+++ b/web/src/features/trace-graph-view/types.ts
@@ -1,7 +1,13 @@
import { z } from "zod/v4";
+export type GraphNodeData = {
+ id: string;
+ label: string;
+ type: string;
+};
+
export type GraphCanvasData = {
- nodes: string[];
+ nodes: GraphNodeData[];
edges: { from: string; to: string }[];
};
@@ -9,6 +15,8 @@ export const LANGGRAPH_NODE_TAG = "langgraph_node";
export const LANGGRAPH_STEP_TAG = "langgraph_step";
export const LANGGRAPH_START_NODE_NAME = "__start__";
export const LANGGRAPH_END_NODE_NAME = "__end__";
+export const LANGFUSE_START_NODE_NAME = "__start__";
+export const LANGFUSE_END_NODE_NAME = "__end__";
export const LanggraphMetadataSchema = z.object({
[LANGGRAPH_NODE_TAG]: z.string(),
@@ -17,14 +25,22 @@ export const LanggraphMetadataSchema = z.object({
export const AgentGraphDataSchema = z.object({
id: z.string(),
- parent_observation_id: z.string(),
- node: z.string().min(1).nullish(),
+ parent_observation_id: z.string().nullish(),
+ type: z.string(),
+ name: z.string(),
+ start_time: z.string(),
+ end_time: z.string().nullish(),
+ node: z.string().nullish(),
step: z.coerce.number().nullish(),
});
export type AgentGraphDataResponse = {
id: string;
- node: string;
- step: number;
- parentObservationId: string;
+ node: string | null; // langgraph_node
+ step: number | null;
+ parentObservationId: string | null;
+ name: string; // span name
+ startTime: string;
+ endTime?: string;
+ observationType: string;
};
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 04907a8dc4..36d6ddb143 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -502,17 +502,39 @@ export const traceRouter = createTRPCRouter({
const result = records
.map((r) => {
const parsed = AgentGraphDataSchema.safeParse(r);
+ if (!parsed.success) {
+ return null;
+ }
- return parsed.success &&
- parsed.data.step != null &&
- parsed.data.node != null
- ? {
- id: parsed.data.id,
- node: parsed.data.node,
- step: parsed.data.step,
- parentObservationId: parsed.data.parent_observation_id,
- }
- : null;
+ const data = parsed.data;
+ const hasLangGraphData = data.step != null && data.node != null;
+ const hasAgentData = data.type !== "EVENT"; // Include all types except EVENT
+
+ if (hasLangGraphData) {
+ return {
+ id: data.id,
+ node: data.node,
+ step: data.step,
+ parentObservationId: data.parent_observation_id || null,
+ name: data.name,
+ startTime: data.start_time,
+ endTime: data.end_time || undefined,
+ observationType: data.type,
+ };
+ } else if (hasAgentData) {
+ return {
+ id: data.id,
+ node: data.name,
+ step: 0,
+ parentObservationId: data.parent_observation_id || null,
+ name: data.name,
+ startTime: data.start_time,
+ endTime: data.end_time || undefined,
+ observationType: data.type,
+ };
+ }
+
+ return null;
})
.filter((r) => Boolean(r)) as Required<AgentGraphDataResponse>[];