Skip to content

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

fix(sessions): Improve tool call deduplication (#17530)

Ben Bachem37fab0f5d63a
diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls.ts b/web/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls.ts
deleted file mode 100644
index 68867a529b..0000000000
--- a/web/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { type ToolCallPart } from "@langfuse/shared/src/utils/normalized-io";
-
-import {
- getToolObservationCallId,
- type ToolObservation,
-} from "@/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId";
-
-const canonicalizeToolInput = (value: unknown): unknown => {
- let parsedValue = value;
- if (typeof value === "string") {
- try {
- parsedValue = JSON.parse(value) as unknown;
- } catch {
- return value;
- }
- }
-
- if (Array.isArray(parsedValue)) {
- return parsedValue.map(canonicalizeToolInput);
- }
- if (typeof parsedValue !== "object" || parsedValue === null) {
- return parsedValue;
- }
-
- return Object.fromEntries(
- Object.entries(parsedValue)
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([key, nestedValue]) => [key, canonicalizeToolInput(nestedValue)]),
- );
-};
-
-const getToolSemanticKey = (name: string | null | undefined, input: unknown) =>
- name ? JSON.stringify([name, canonicalizeToolInput(input)]) : null;
-
-export function getSemanticallyMatchedChildToolCalls({
- rolledUpToolCalls,
- allToolCalls,
- childToolObservations,
-}: {
- rolledUpToolCalls: readonly ToolCallPart[];
- allToolCalls: readonly ToolCallPart[];
- childToolObservations: readonly ToolObservation[];
-}) {
- const emittedToolCallIds = new Set(
- allToolCalls.flatMap((toolCall) =>
- toolCall.toolCallId ? [toolCall.toolCallId] : [],
- ),
- );
- const unmatchedChildrenBySemanticKey = new Map<string, ToolObservation[]>();
- for (const observation of childToolObservations) {
- if (observation.type !== "TOOL") continue;
- const observationCallId = getToolObservationCallId(observation);
- if (observationCallId && emittedToolCallIds.has(observationCallId))
- continue;
-
- const semanticKey = getToolSemanticKey(observation.name, observation.input);
- if (!semanticKey) continue;
- const matchingChildren = unmatchedChildrenBySemanticKey.get(semanticKey);
- if (matchingChildren) matchingChildren.push(observation);
- else unmatchedChildrenBySemanticKey.set(semanticKey, [observation]);
- }
-
- const unmatchedCallsBySemanticKey = new Map<string, ToolCallPart[]>();
- for (const toolCall of rolledUpToolCalls) {
- const semanticKey = getToolSemanticKey(toolCall.toolName, toolCall.input);
- if (!semanticKey) continue;
- const matchingCalls = unmatchedCallsBySemanticKey.get(semanticKey);
- if (matchingCalls) matchingCalls.push(toolCall);
- else unmatchedCallsBySemanticKey.set(semanticKey, [toolCall]);
- }
-
- const matchedCalls = new Set<ToolCallPart>();
- for (const [semanticKey, calls] of unmatchedCallsBySemanticKey) {
- if (calls.length !== 1) continue;
- if (unmatchedChildrenBySemanticKey.get(semanticKey)?.length !== 1) continue;
- const matchingCall = calls[0];
- if (matchingCall) matchedCalls.add(matchingCall);
- }
- return matchedCalls;
-}
diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts
index 27a609acd5..a4d130287a 100644
--- a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts
+++ b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.clienttest.ts
@@ -435,6 +435,247 @@ describe("prepareSessionTimelineObservations", () => {
).toEqual([]);
});
+ it("deduplicates a generation tool call by a sibling tool observation call id", () => {
+ const prepared = prepareSessionTimelineObservations([
+ observation("root", null, null, "SPAN"),
+ observation(
+ "generation",
+ null,
+ [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "shared-call-id",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: JSON.stringify({ query: "dashboard" }),
+ },
+ },
+ ],
+ },
+ ],
+ "GENERATION",
+ new Date(1),
+ "trace-1",
+ "root",
+ ),
+ observation(
+ "tool-observation",
+ { query: "dashboard" },
+ "Found dashboard",
+ "TOOL",
+ new Date(2),
+ "trace-1",
+ "root",
+ { toolCallId: "shared-call-id" },
+ "search",
+ ),
+ ]);
+
+ expect(
+ prepared.filter(
+ (item) => item.type === "tool" && item.observation.id === "generation",
+ ),
+ ).toEqual([]);
+ expect(
+ prepared.filter(
+ (item) =>
+ item.type === "observation" &&
+ item.observation.id === "tool-observation",
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("does not deduplicate matching tool call ids across traces", () => {
+ const prepared = prepareSessionTimelineObservations([
+ observation(
+ "tool-observation",
+ {},
+ "Tool output",
+ "TOOL",
+ new Date(0),
+ "trace-1",
+ null,
+ { toolCallId: "reused-call-id" },
+ "lookup",
+ ),
+ observation(
+ "generation",
+ null,
+ [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "reused-call-id",
+ type: "function",
+ function: {
+ name: "lookup",
+ arguments: "{}",
+ },
+ },
+ ],
+ },
+ ],
+ "GENERATION",
+ new Date(1),
+ "trace-2",
+ ),
+ ]);
+
+ expect(
+ prepared.filter(
+ (item) => item.type === "tool" && item.observation.id === "generation",
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("keeps the latest representation of a repeated generation tool call", () => {
+ const toolCallOutput = (query: string) => [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "repeated-call-id",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: JSON.stringify({ query }),
+ },
+ },
+ ],
+ },
+ ];
+ const prepared = prepareSessionTimelineObservations([
+ observation(
+ "generation-1",
+ null,
+ toolCallOutput("initial query"),
+ "GENERATION",
+ new Date(0),
+ ),
+ observation(
+ "generation-2",
+ null,
+ toolCallOutput("enriched query"),
+ "GENERATION",
+ new Date(1),
+ ),
+ ]);
+
+ expect(
+ prepared
+ .filter((item) => item.type === "tool")
+ .map((item) => ({
+ observationId: item.observation.id,
+ input: item.toolCall.input,
+ })),
+ ).toEqual([
+ {
+ observationId: "generation-2",
+ input: { query: "enriched query" },
+ },
+ ]);
+ });
+
+ it("prefers a unique sibling tool observation over a semantic generation call", () => {
+ const prepared = prepareSessionTimelineObservations([
+ observation("root", null, null, "SPAN"),
+ observation(
+ "generation",
+ null,
+ [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "generation-call-id",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: JSON.stringify({ query: "dashboard" }),
+ },
+ },
+ ],
+ },
+ ],
+ "GENERATION",
+ new Date(1),
+ "trace-1",
+ "root",
+ ),
+ observation(
+ "tool-observation",
+ JSON.stringify({ query: "dashboard" }),
+ "Found dashboard",
+ "TOOL",
+ new Date(2),
+ "trace-1",
+ "root",
+ null,
+ "search",
+ ),
+ ]);
+
+ expect(
+ prepared.filter(
+ (item) => item.type === "tool" && item.observation.id === "generation",
+ ),
+ ).toEqual([]);
+ });
+
+ it("does not semantically match a tool observation already represented by id", () => {
+ const prepared = prepareSessionTimelineObservations([
+ observation("generation", null, [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "observed-call-id",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: JSON.stringify({ query: "dashboard" }),
+ },
+ },
+ {
+ id: "separate-call-id",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: JSON.stringify({ query: "dashboard" }),
+ },
+ },
+ ],
+ },
+ ]),
+ observation(
+ "tool-observation",
+ { query: "dashboard" },
+ "Found dashboard",
+ "TOOL",
+ new Date(1),
+ "trace-1",
+ "generation",
+ { toolCallId: "observed-call-id" },
+ "search",
+ ),
+ ]);
+
+ expect(
+ prepared
+ .filter((item) => item.type === "tool")
+ .map((item) => item.toolCall.toolCallId),
+ ).toEqual(["separate-call-id"]);
+ });
+
it("keeps a rolled-up tool call when semantic child matching is ambiguous", () => {
const toolCall = {
role: "assistant",
@@ -474,6 +715,120 @@ describe("prepareSessionTimelineObservations", () => {
).toHaveLength(1);
});
+ it("does not semantically match tool executions across branches", () => {
+ const prepared = prepareSessionTimelineObservations([
+ observation("root", null, null, "SPAN"),
+ observation(
+ "first-branch",
+ null,
+ null,
+ "SPAN",
+ new Date(1),
+ "trace-1",
+ "root",
+ ),
+ observation(
+ "first-tool",
+ {},
+ "First result",
+ "TOOL",
+ new Date(2),
+ "trace-1",
+ "first-branch",
+ null,
+ "lookup",
+ ),
+ observation(
+ "second-branch",
+ null,
+ null,
+ "SPAN",
+ new Date(3),
+ "trace-1",
+ "root",
+ ),
+ observation(
+ "second-generation",
+ null,
+ [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "second-call-id",
+ type: "function",
+ function: { name: "lookup", arguments: "{}" },
+ },
+ ],
+ },
+ ],
+ "GENERATION",
+ new Date(4),
+ "trace-1",
+ "second-branch",
+ ),
+ ]);
+
+ expect(
+ prepared.filter(
+ (item) =>
+ item.type === "tool" && item.observation.id === "second-generation",
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("deduplicates identical tool calls within their direct execution scopes", () => {
+ const generation = (id: string, toolCallId: string, startTime: Date) =>
+ observation(
+ id,
+ null,
+ [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: toolCallId,
+ type: "function",
+ function: { name: "lookup", arguments: "{}" },
+ },
+ ],
+ },
+ ],
+ "GENERATION",
+ startTime,
+ );
+ const prepared = prepareSessionTimelineObservations([
+ generation("first-generation", "first-call-id", new Date(0)),
+ observation(
+ "first-tool",
+ {},
+ "First result",
+ "TOOL",
+ new Date(1),
+ "trace-1",
+ "first-generation",
+ null,
+ "lookup",
+ ),
+ generation("second-generation", "second-call-id", new Date(2)),
+ observation(
+ "second-tool",
+ {},
+ "Second result",
+ "TOOL",
+ new Date(3),
+ "trace-1",
+ "second-generation",
+ null,
+ "lookup",
+ ),
+ ]);
+
+ expect(prepared.filter((item) => item.type === "tool")).toEqual([]);
+ });
+
it("flattens multiple nesting levels while preserving sibling chronology", () => {
const prepared = prepareSessionTimelineObservations([
observation("root", "root input", "root output"),
diff --git a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts
index 6bba2926e7..2c0b1067f5 100644
--- a/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts
+++ b/web/src/features/sessions/SessionConversationTimeline/fns/prepareSessionTimelineObservations.ts
@@ -5,7 +5,7 @@ import {
} from "@langfuse/shared/src/utils/normalized-io";
import { deduplicateTimelineInput } from "@/src/features/sessions/SessionConversationTimeline/fns/deduplicateTimelineInput";
-import { getSemanticallyMatchedChildToolCalls } from "@/src/features/sessions/SessionConversationTimeline/fns/getSemanticallyMatchedChildToolCalls";
+import { getToolObservationCallId } from "@/src/features/sessions/SessionConversationTimeline/fns/getToolObservationCallId";
import { getStandaloneToolCallIds } from "@/src/features/sessions/SessionConversationTimeline/fns/getStandaloneToolCallIds";
import { processTimelineMessages } from "@/src/features/sessions/SessionConversationTimeline/fns/processTimelineMessages";
@@ -64,6 +64,33 @@ export type PreparedSessionTimelineItem<
const EMPTY_TOOL_CALL_IDS: ReadonlySet<string> = new Set();
+const canonicalizeToolInput = (value: unknown): unknown => {
+ let parsedValue = value;
+ if (typeof value === "string") {
+ try {
+ parsedValue = JSON.parse(value) as unknown;
+ } catch {
+ return value;
+ }
+ }
+
+ if (Array.isArray(parsedValue)) {
+ return parsedValue.map(canonicalizeToolInput);
+ }
+ if (typeof parsedValue !== "object" || parsedValue === null) {
+ return parsedValue;
+ }
+
+ return Object.fromEntries(
+ Object.entries(parsedValue)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, nestedValue]) => [key, canonicalizeToolInput(nestedValue)]),
+ );
+};
+
+const getToolSemanticKey = (name: string | null | undefined, input: unknown) =>
+ name ? JSON.stringify([name, canonicalizeToolInput(input)]) : null;
+
export function prepareSessionTimelineObservations<
Observation extends SessionTimelineObservation,
>(observations: readonly Observation[]) {
@@ -131,8 +158,8 @@ export function prepareSessionTimelineObservations<
),
});
- const preparedObservations = chronologicalObservations
- .map(({ observation, originalIndex }, index) => ({
+ const chronologicalPreparedObservations = chronologicalObservations.map(
+ ({ observation, originalIndex }, index) => ({
originalIndex,
prepared: {
observation,
@@ -142,7 +169,121 @@ export function prepareSessionTimelineObservations<
rolledUpToolCalls: [],
},
},
- }))
+ }),
+ );
+
+ const latestToolCallById = new Map<string, ToolCallPart>();
+ for (const { prepared } of chronologicalPreparedObservations) {
+ for (const toolCall of prepared.processedMessages.rolledUpToolCalls) {
+ if (!toolCall.toolCallId) continue;
+ latestToolCallById.set(
+ `${prepared.observation.traceId ?? ""}\0${toolCall.toolCallId}`,
+ toolCall,
+ );
+ }
+ }
+ for (const { prepared } of chronologicalPreparedObservations) {
+ prepared.processedMessages.rolledUpToolCalls =
+ prepared.processedMessages.rolledUpToolCalls.filter(
+ (toolCall) =>
+ !toolCall.toolCallId ||
+ latestToolCallById.get(
+ `${prepared.observation.traceId ?? ""}\0${toolCall.toolCallId}`,
+ ) === toolCall,
+ );
+ }
+
+ const toolObservationsBySemanticKey = new Map<string, Observation[]>();
+ const directToolCallsBySemanticKey = new Map<string, ToolCallPart[]>();
+ const siblingToolCallsBySemanticKey = new Map<string, ToolCallPart[]>();
+ const emittedToolCallIds = new Set<string>();
+ for (const { prepared } of chronologicalPreparedObservations) {
+ if (prepared.parsed?.type !== "loaded") continue;
+ for (const message of prepared.parsed.messages) {
+ for (const part of message.parts) {
+ if (part.type !== "tool-call" || !part.toolCallId) continue;
+ emittedToolCallIds.add(
+ `${prepared.observation.traceId ?? ""}\0${part.toolCallId}`,
+ );
+ }
+ }
+ }
+ for (const { prepared } of chronologicalPreparedObservations) {
+ const { observation } = prepared;
+ if (observation.type === "TOOL") {
+ const observationCallId = getToolObservationCallId(observation);
+ if (
+ observationCallId &&
+ emittedToolCallIds.has(
+ `${observation.traceId ?? ""}\0${observationCallId}`,
+ )
+ ) {
+ continue;
+ }
+
+ const semanticKey = getToolSemanticKey(
+ observation.name,
+ observation.input,
+ );
+ if (semanticKey) {
+ const directKey = `${observation.traceId ?? ""}\0${observation.parentObservationId ?? ""}\0${semanticKey}`;
+ const directMatches = toolObservationsBySemanticKey.get(directKey);
+ if (directMatches) directMatches.push(observation);
+ else toolObservationsBySemanticKey.set(directKey, [observation]);
+ }
+ }
+
+ for (const toolCall of prepared.processedMessages.rolledUpToolCalls) {
+ const semanticKey = getToolSemanticKey(toolCall.toolName, toolCall.input);
+ if (!semanticKey) continue;
+ const directKey = `${observation.traceId ?? ""}\0${observation.id}\0${semanticKey}`;
+ const directMatches = directToolCallsBySemanticKey.get(directKey);
+ if (directMatches) directMatches.push(toolCall);
+ else directToolCallsBySemanticKey.set(directKey, [toolCall]);
+
+ const siblingKey = `${observation.traceId ?? ""}\0${observation.parentObservationId ?? ""}\0${semanticKey}`;
+ const siblingMatches = siblingToolCallsBySemanticKey.get(siblingKey);
+ if (siblingMatches) siblingMatches.push(toolCall);
+ else siblingToolCallsBySemanticKey.set(siblingKey, [toolCall]);
+ }
+ }
+ const matchedToolCalls = new Set<ToolCallPart>();
+ const matchedToolObservations = new Set<Observation>();
+ for (const [semanticKey, toolCalls] of directToolCallsBySemanticKey) {
+ if (toolCalls.length !== 1) continue;
+ const toolObservations = toolObservationsBySemanticKey.get(semanticKey);
+ if (toolObservations?.length !== 1) continue;
+ const matchingCall = toolCalls[0];
+ const matchingObservation = toolObservations[0];
+ if (!matchingCall || !matchingObservation) continue;
+ matchedToolCalls.add(matchingCall);
+ matchedToolObservations.add(matchingObservation);
+ }
+ for (const [semanticKey, toolCalls] of siblingToolCallsBySemanticKey) {
+ const unmatchedToolCalls = toolCalls.filter(
+ (toolCall) => !matchedToolCalls.has(toolCall),
+ );
+ if (unmatchedToolCalls.length !== 1) continue;
+ const unmatchedToolObservations = (
+ toolObservationsBySemanticKey.get(semanticKey) ?? []
+ ).filter((observation) => !matchedToolObservations.has(observation));
+ if (unmatchedToolObservations.length !== 1) continue;
+ const matchingCall = unmatchedToolCalls[0];
+ const matchingObservation = unmatchedToolObservations[0];
+ if (!matchingCall || !matchingObservation) continue;
+ matchedToolCalls.add(matchingCall);
+ matchedToolObservations.add(matchingObservation);
+ }
+ if (matchedToolCalls.size > 0) {
+ for (const { prepared } of chronologicalPreparedObservations) {
+ prepared.processedMessages.rolledUpToolCalls =
+ prepared.processedMessages.rolledUpToolCalls.filter(
+ (toolCall) => !matchedToolCalls.has(toolCall),
+ );
+ }
+ }
+
+ const preparedObservations = chronologicalPreparedObservations
.sort((left, right) => left.originalIndex - right.originalIndex)
.map(({ prepared }) => prepared);
const observationKey = (observation: Observation) =>
@@ -178,33 +319,6 @@ export function prepareSessionTimelineObservations<
} else childrenByParentKey.set(parentKey, [prepared]);
}
- for (const prepared of preparedObservations) {
- const childToolObservations = (
- childrenByParentKey.get(observationKey(prepared.observation)) ?? []
- ).map(({ observation }) => observation);
- if (childToolObservations.length === 0) continue;
-
- const allToolCalls =
- prepared.parsed?.type === "loaded"
- ? prepared.parsed.messages.flatMap((message) =>
- message.source === "output"
- ? message.parts.filter(
- (part): part is ToolCallPart => part.type === "tool-call",
- )
- : [],
- )
- : [];
- const matchedCalls = getSemanticallyMatchedChildToolCalls({
- rolledUpToolCalls: prepared.processedMessages.rolledUpToolCalls,
- allToolCalls,
- childToolObservations,
- });
- prepared.processedMessages.rolledUpToolCalls =
- prepared.processedMessages.rolledUpToolCalls.filter(
- (toolCall) => !matchedCalls.has(toolCall),
- );
- }
-
const result: PreparedSessionTimelineItem<Observation>[] = [];
const emitted = new Set<string>();
const active = new Set<string>();