Skip to content

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

fix(ui-graph-view): fetch graph data separately (#6781)

Hassieb Pakzad1354db489fab
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 94b7c39b6b..249ba71a73 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1036,3 +1036,37 @@ export const traceWithSessionIdExists = async (
return result.length > 0;
};
+
+export async function getAgentGraphData(params: {
+ projectId: string;
+ traceId: string;
+ chMinStartTime: string;
+ chMaxStartTime: string;
+}) {
+ const { projectId, traceId, chMinStartTime, chMaxStartTime } = params;
+
+ const query = `
+ SELECT
+ id,
+ parent_observation_id,
+ metadata['langgraph_node'] AS node,
+ metadata['langgraph_step'] AS step
+ FROM
+ observations
+ WHERE
+ project_id = {projectId: String}
+ AND trace_id = {traceId: String}
+ AND start_time >= {chMinStartTime: DateTime64(3)}
+ AND start_time <= {chMaxStartTime: DateTime64(3)}
+ `;
+
+ return queryClickhouse({
+ query,
+ params: {
+ traceId,
+ projectId,
+ chMinStartTime,
+ chMaxStartTime,
+ },
+ });
+}
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 5a81e93a2e..dbd9b7f66e 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -17,7 +17,6 @@ import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
import { type APIScoreV2, ObservationLevel } from "@langfuse/shared";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
import { TraceGraphView } from "@/src/features/trace-graph-view/components/TraceGraphView";
-import { isLanggraphTrace } from "@/src/features/trace-graph-view/utils/isLanggraphTrace";
import { Command, CommandInput } from "@/src/components/ui/command";
import { Switch } from "@/src/components/ui/switch";
import { Button } from "@/src/components/ui/button";
@@ -134,6 +133,31 @@ export function Trace(props: {
},
);
+ const observationStartTimes = props.observations.map((o) =>
+ o.startTime.getTime(),
+ );
+ const minStartTime = new Date(
+ Math.min(...observationStartTimes, Date.now()), // the Date now is a guard for empty obs list
+ ).toISOString();
+ const maxStartTime = new Date(
+ Math.max(...observationStartTimes, 0), // the zero is a guard for empty obs list
+ ).toISOString();
+
+ const agentGraphDataQuery = api.traces.getAgentGraphData.useQuery(
+ {
+ projectId: props.trace.projectId,
+ traceId: props.trace.id,
+ minStartTime,
+ maxStartTime,
+ },
+ {
+ enabled: isAuthenticatedAndProjectMember && props.observations.length > 0,
+ },
+ );
+
+ const agentGraphData = agentGraphDataQuery.data ?? [];
+ const isGraphViewAvailable = agentGraphData.length > 0;
+
const toggleCollapsedObservation = useCallback(
(id: string) => {
if (collapsedObservations.includes(id)) {
@@ -246,7 +270,7 @@ export function Trace(props: {
<DropdownMenuLabel>Settings</DropdownMenuLabel>
<DropdownMenuSeparator />
- {isLanggraphTrace(props.observations) && (
+ {isGraphViewAvailable && (
<>
<DropdownMenuItem
asChild
@@ -377,7 +401,7 @@ export function Trace(props: {
<div className="h-full overflow-hidden">
{props.selectedTab?.includes("timeline") ? (
<div className="h-full w-full flex-1 flex-col overflow-hidden">
- {isLanggraphTrace(props.observations) && showGraph ? (
+ {isGraphViewAvailable && showGraph ? (
<div className="flex h-full w-full flex-col overflow-hidden">
<div className="h-1/2 w-full overflow-y-auto overflow-x-hidden">
<TraceTimelineView
@@ -401,10 +425,7 @@ export function Trace(props: {
<div className="h-1/2 w-full overflow-hidden border-t">
<TraceGraphView
key={`graph-timeline-${props.trace.id}`}
- trace={props.trace}
- scores={props.scores}
- observations={props.observations}
- projectId={props.trace.projectId}
+ agentGraphData={agentGraphData}
/>
</div>
</div>
@@ -432,7 +453,7 @@ export function Trace(props: {
</div>
) : (
<div className="h-full w-full flex-1 flex-col overflow-hidden">
- {isLanggraphTrace(props.observations) && showGraph ? (
+ {isGraphViewAvailable && showGraph ? (
<div className="flex h-full w-full flex-col overflow-hidden">
<div className="h-1/2 w-full overflow-y-auto">
<ObservationTree
@@ -459,10 +480,7 @@ export function Trace(props: {
<div className="h-1/2 w-full overflow-hidden border-t">
<TraceGraphView
key={`graph-tree-${props.trace.id}`}
- trace={props.trace}
- scores={props.scores}
- observations={props.observations}
- projectId={props.trace.projectId}
+ agentGraphData={agentGraphData}
/>
</div>
</div>
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
index 2d5b6f286f..36ea286b31 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
@@ -1,49 +1,24 @@
import React, { useEffect, useState, useMemo, useCallback } from "react";
import { StringParam, useQueryParam } from "use-query-params";
-import type { APIScoreV2, TraceDomain } from "@langfuse/shared";
-import type { ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
import { TraceGraphCanvas } from "./TraceGraphCanvas";
import {
type GraphCanvasData,
- LANGGRAPH_STEP_TAG,
- LANGGRAPH_NODE_TAG,
LANGGRAPH_END_NODE_NAME,
- LanggraphMetadataSchema,
+ type AgentGraphDataResponse,
} from "../types";
type TraceGraphViewProps = {
- observations: ObservationReturnTypeWithMetadata[];
- trace: Omit<TraceDomain, "input" | "output" | "metadata"> & {
- input: string | null;
- output: string | null;
- metadata: string | null;
- };
- scores: APIScoreV2[];
- projectId: string;
+ agentGraphData: AgentGraphDataResponse[];
};
export const TraceGraphView: React.FC<TraceGraphViewProps> = (props) => {
- const { observations: rawObservations } = props;
- const observations = rawObservations.map((o) => {
- let parsedMetadata = o.metadata;
-
- try {
- parsedMetadata =
- o.metadata && typeof o.metadata === "string"
- ? JSON.parse(o.metadata)
- : o.metadata;
- } catch {
- return o;
- }
-
- return { ...o, metadata: parsedMetadata };
- });
+ const { agentGraphData } = props;
const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);
const { graph, nodeToParentObservationMap } = useMemo(
- () => parseGraph({ observations }),
- [observations],
+ () => parseGraph({ agentGraphData }),
+ [agentGraphData],
);
const [currentObservationId, setCurrentObservationId] = useQueryParam(
@@ -52,17 +27,12 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = (props) => {
);
useEffect(() => {
- const currentObservation = observations.find(
+ const nodeName = agentGraphData.find(
(o) => o.id === currentObservationId,
- );
- const nodeName =
- currentObservation &&
- LanggraphMetadataSchema.safeParse(currentObservation.metadata).data?.[
- LANGGRAPH_NODE_TAG
- ];
+ )?.node;
setSelectedNodeName(nodeName ?? null);
- }, [currentObservationId, observations]);
+ }, [currentObservationId, agentGraphData]);
const onCanvasNodeNameChange = useCallback(
(nodeName: string | null) => {
@@ -89,44 +59,35 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = (props) => {
);
};
-function parseGraph(params: {
- observations: TraceGraphViewProps["observations"];
-}): {
+function parseGraph(params: { agentGraphData: AgentGraphDataResponse[] }): {
graph: GraphCanvasData;
nodeToParentObservationMap: Record<string, string>;
} {
- const { observations } = params;
+ const { agentGraphData } = params;
const stepToNodeMap = new Map<number, string>();
const nodeToParentObservationMap = new Map<string, string>();
- observations?.forEach((o) => {
- const parsedMetadata = LanggraphMetadataSchema.safeParse(o.metadata);
-
- if (!parsedMetadata.success) return;
-
- const { [LANGGRAPH_NODE_TAG]: node, [LANGGRAPH_STEP_TAG]: step } =
- parsedMetadata.data;
+ agentGraphData.forEach((o) => {
+ const { node, step } = o;
stepToNodeMap.set(step, node);
- // Check if parent is in the same node. If not, observation must be top-most observation of the node
if (o.parentObservationId) {
- const parent = observations.find(
+ const parent = agentGraphData.find(
(obs) => obs.id === o.parentObservationId,
);
- const parsedParentMetadata = LanggraphMetadataSchema.safeParse(
- parent?.metadata,
- );
- if (parent && !parsedParentMetadata.success) {
- nodeToParentObservationMap.set(LANGGRAPH_END_NODE_NAME, parent.id);
+ // initialize the end node to point to the top-most langgraph span
+ if (!parent) {
+ nodeToParentObservationMap.set(
+ LANGGRAPH_END_NODE_NAME,
+ o.parentObservationId,
+ );
}
- if (
- !parsedParentMetadata.success ||
- parsedParentMetadata.data[LANGGRAPH_NODE_TAG] !== node
- ) {
+ // 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 {
diff --git a/web/src/features/trace-graph-view/types.ts b/web/src/features/trace-graph-view/types.ts
index c7d4309e58..7fc203d6a4 100644
--- a/web/src/features/trace-graph-view/types.ts
+++ b/web/src/features/trace-graph-view/types.ts
@@ -14,3 +14,17 @@ export const LanggraphMetadataSchema = z.object({
[LANGGRAPH_NODE_TAG]: z.string(),
[LANGGRAPH_STEP_TAG]: z.number(),
});
+
+export const AgentGraphDataSchema = z.object({
+ id: z.string(),
+ parent_observation_id: z.string(),
+ node: z.string().min(1).nullish(),
+ step: z.coerce.number().nullish(),
+});
+
+export type AgentGraphDataResponse = {
+ id: string;
+ node: string;
+ step: number;
+ parentObservationId: string;
+};
diff --git a/web/src/features/trace-graph-view/utils/isLanggraphTrace.ts b/web/src/features/trace-graph-view/utils/isLanggraphTrace.ts
deleted file mode 100644
index c606c056c7..0000000000
--- a/web/src/features/trace-graph-view/utils/isLanggraphTrace.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
-import { LanggraphMetadataSchema } from "../types";
-
-export const isLanggraphTrace = (
- observations: ObservationReturnTypeWithMetadata[],
-) => {
- return observations.some((o) => {
- let metadata = o.metadata;
-
- if (metadata && typeof metadata == "string") {
- try {
- metadata = JSON.parse(metadata);
- } catch {}
- }
-
- return LanggraphMetadataSchema.safeParse(metadata).success;
- });
-};
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index f960af0619..856186af16 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -38,11 +38,17 @@ import {
TraceDeleteQueue,
getTracesTableMetrics,
getCategoricalScoresGroupedByName,
+ convertDateToClickhouseDateTime,
+ getAgentGraphData,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { randomUUID } from "crypto";
import { createBatchActionJob } from "@/src/features/table/server/createBatchActionJob";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import {
+ type AgentGraphDataResponse,
+ AgentGraphDataSchema,
+} from "@/src/features/trace-graph-view/types";
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -483,4 +489,50 @@ export const traceRouter = createTRPCRouter({
});
}
}),
+
+ getAgentGraphData: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ traceId: z.string(),
+ minStartTime: z.string(),
+ maxStartTime: z.string(),
+ }),
+ )
+ .query(async ({ input }): Promise<Required<AgentGraphDataResponse>[]> => {
+ const { traceId, projectId, minStartTime, maxStartTime } = input;
+
+ const chMinStartTime = convertDateToClickhouseDateTime(
+ new Date(minStartTime),
+ );
+ const chMaxStartTime = convertDateToClickhouseDateTime(
+ new Date(maxStartTime),
+ );
+
+ const records = await getAgentGraphData({
+ projectId,
+ traceId,
+ chMinStartTime,
+ chMaxStartTime,
+ });
+
+ const result = records
+ .map((r) => {
+ const parsed = AgentGraphDataSchema.safeParse(r);
+
+ 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;
+ })
+ .filter((r) => Boolean(r)) as Required<AgentGraphDataResponse>[];
+
+ return result;
+ }),
});