🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(events): metadata value filter shortcuts in JSON view (#14381)
Nikita Kabardinea6b1e3190a3
diff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.tsindex 35e85c274c..a9c2b42eee 100644--- a/packages/shared/scripts/seeder/scenarios/trace-tree.ts+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts@@ -339,6 +339,18 @@ const run = async (scenario: "trace-tree","node.depth": String(node.depth),...(isFailedToolRetryPair ? { "retry.count": "2" } : {}),+ // Nested branches are JSON-encoded strings, mirroring how OTel metadata+ // round-trips through the Map(String, String) column (each value is+ // parsed back into a tree for display). This is what lets the metadata+ // view's nested-branch "contains" filter shortcut land on real data.+ scope: JSON.stringify({+ name: "@flue/opentelemetry",+ version: "1.0.0-beta.1",+ }),+ attributes: JSON.stringify({+ "flue.tool.name": isGeneration ? "lookup_weather" : "noop",+ "flue.tool.call_id": `call_${node.index}`,+ }),},provided_model_name: isGeneration ? "gpt-4o" : null,internal_model_id: null,diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex 011c30b68e..5c4b7853e8 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -1,10 +1,33 @@import { memo, type JSX, useState } from "react";+import { useRouter } from "next/router";import { type Row } from "@tanstack/react-table";import { urlRegex } from "@langfuse/shared";import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";import { copyTextToClipboard } from "@/src/utils/clipboard";import { Button } from "@/src/components/ui/button";-import { Copy, Check } from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import {+ buildEventsTablePathForMetadataFilter,+ type MetadataFilterOperator,+} from "@/src/features/events/lib/eventsTablePaths";+import { Copy, Check, EllipsisVertical, Filter, FilterX } from "lucide-react";++/**+ * Enables the per-row actions menu in a metadata JSON view: copy value/+ * structure/path plus "Include in / Exclude from filter" shortcuts that land on+ * the matching events table. Passed only by the metadata view, so input/output+ * cells keep their plain one-click copy button.+ */+export type MetadataFilterActions = {+ projectId: string;+ filterTarget: "observations" | "traces";+};const MAX_STRING_LENGTH_FOR_LINK_DETECTION = 1500;export const MAX_CELL_DISPLAY_CHARS = 2000;@@ -154,17 +177,173 @@ function getCopyValue(value: unknown): string {}}+/** Walks up to the top-level (level 0) ancestor key for a metadata row. */+function resolveTopLevelMetadataKey(row: Row<JsonTableRow>): string {+ let cursor: Row<JsonTableRow> | undefined = row;+ while (cursor && cursor.original.level > 0) {+ cursor = cursor.getParentRow() ?? undefined;+ }+ return cursor?.original.key ?? row.original.key;+}++/**+ * Builds the dotted key path from the row's actual keys (root → leaf). Unlike+ * `convertRowIdToKeyPath`, which reconstructs the path from the hyphen-joined+ * row id, this is lossless for keys that themselves contain `-` (e.g.+ * `x-request-id`).+ */+function resolveKeyPath(row: Row<JsonTableRow>): string {+ const keys: string[] = [];+ let cursor: Row<JsonTableRow> | undefined = row;+ while (cursor) {+ keys.unshift(String(cursor.original.key));+ cursor = cursor.getParentRow() ?? undefined;+ }+ return keys.join(".");+}++/**+ * The per-row overflow menu shown in metadata views. Containers offer "Copy+ * structure"; scalar leaves offer "Copy value" plus filter shortcuts. Rendered+ * only when `metadataActions` is provided, so `useRouter` stays off the hot+ * path for the (far more numerous) input/output JSON cells.+ */+function ValueCellActionsMenu({+ row,+ metadataActions,+}: {+ row: Row<JsonTableRow>;+ metadataActions: MetadataFilterActions;+}) {+ const router = useRouter();+ const { value, type, hasChildren, level } = row.original;++ const filterValue = String(value);+ // A nested value is matched as a substring of its JSON-ENCODED top-level+ // branch, but `filterValue` is the JSON-parsed (unescaped) form shown in the+ // tree. When the value carries JSON-escapable characters (quotes,+ // backslashes, newlines) the two differ, so `contains` would never match —+ // hide the shortcut rather than build a confidently-wrong filter.+ //+ // Top-level scalars are *usually* stored raw (ingestion keeps top-level+ // strings as-is), so we skip the check there. This heuristic misses the rare+ // case of a top-level value that was itself JSON-encoded with escapes; we+ // accept that miss because the alternative — always applying the check —+ // would wrongly hide the far more common top-level raw string with literal+ // newlines (which filters fine), since its encoded form also differs.+ const valueMatchesStoredForm =+ level === 0 || JSON.stringify(filterValue).slice(1, -1) === filterValue;+ const isScalarLeaf =+ !hasChildren &&+ (type === "string" || type === "number" || type === "boolean") &&+ // Skip empty values: `contains ""` matches every row (ClickHouse+ // position(x, "") === 1, and Map[missingKey] defaults to "") while+ // `does not contain ""` matches none — both shortcuts would be no-ops.+ filterValue.length > 0 &&+ valueMatchesStoredForm;++ // Metadata is a flat Map(String, String), so a nested value can only be+ // matched as a substring of its top-level branch. We use contains/does not+ // contain uniformly (top-level included) so Include and Exclude stay exact+ // complements — stringObject has no "!=" to invert an exact "=".+ const metadataKey = resolveTopLevelMetadataKey(row);+ const includeOperator: MetadataFilterOperator = "contains";+ const excludeOperator: MetadataFilterOperator = "does not contain";+ const displayValue = type === "string" ? `"${filterValue}"` : filterValue;++ const handleCopyData = () => {+ copyTextToClipboard(getCopyValue(value));+ };+ const handleCopyPath = () => {+ copyTextToClipboard(resolveKeyPath(row));+ };+ const navigateWithFilter = (operator: MetadataFilterOperator) => {+ router.push(+ buildEventsTablePathForMetadataFilter({+ currentPath: router.asPath,+ projectId: metadataActions.projectId,+ metadataKey,+ value: filterValue,+ operator,+ target: metadataActions.filterTarget,+ }),+ );+ };++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ aria-label="Value actions"+ title="Actions"+ className="bg-background/80 hover:bg-background absolute top-1/2 right-1 h-4 w-4 -translate-y-1/2 border p-0 opacity-0 shadow-xs transition-opacity duration-200 group-hover:opacity-100 data-[state=open]:opacity-100"+ onClick={(e) => e.stopPropagation()}+ >+ <EllipsisVertical className="h-3 w-3" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="max-w-[320px]"+ onClick={(e) => e.stopPropagation()}+ >+ <DropdownMenuItem className="text-xs" onSelect={handleCopyData}>+ <Copy className="mr-2 h-3.5 w-3.5 shrink-0" />+ {hasChildren ? "Copy structure" : "Copy value"}+ </DropdownMenuItem>+ <DropdownMenuItem className="text-xs" onSelect={handleCopyPath}>+ <Copy className="mr-2 h-3.5 w-3.5 shrink-0" />+ Copy path+ </DropdownMenuItem>+ {isScalarLeaf && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-xs"+ onSelect={() => navigateWithFilter(includeOperator)}+ >+ <Filter className="mr-2 h-3.5 w-3.5 shrink-0" />+ <span className="flex min-w-0 flex-col">+ <span>Include in filter</span>+ <span className="text-muted-foreground truncate font-mono">+ metadata.{metadataKey} {includeOperator} {displayValue}+ </span>+ </span>+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-xs"+ onSelect={() => navigateWithFilter(excludeOperator)}+ >+ <FilterX className="mr-2 h-3.5 w-3.5 shrink-0" />+ <span className="flex min-w-0 flex-col">+ <span>Exclude from filter</span>+ <span className="text-muted-foreground truncate font-mono">+ metadata.{metadataKey} {excludeOperator} {displayValue}+ </span>+ </span>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}+export const ValueCell = memo(({row,expandedCells,toggleCellExpansion,preserveStringWhitespace = false,+ metadataActions,}: {row: Row<JsonTableRow>;expandedCells: Set<string>;toggleCellExpansion: (cellId: string) => void;preserveStringWhitespace?: boolean;+ metadataActions?: MetadataFilterActions;}) => {const { value, type } = row.original;const cellId = `${row.id}-value`;@@ -300,21 +479,26 @@ export const ValueCell = memo(</div>)}- {/* Copy button - appears on hover */}- <Button- variant="ghost"- size="icon"- className="bg-background/80 hover:bg-background absolute top-0 right-0 h-5 w-5 border p-0.5 opacity-0 shadow-xs transition-opacity duration-200 group-hover:opacity-100"- onClick={handleCopy}- title="Copy value"- aria-label="Copy cell value"- >- {showCopySuccess ? (- <Check className="h-2.5 w-2.5 text-green-600" />- ) : (- <Copy className="h-2.5 w-2.5" />- )}- </Button>+ {/* Hover affordance: a one-click copy by default, or an actions menu+ (copy + filter shortcuts) in metadata views. */}+ {metadataActions ? (+ <ValueCellActionsMenu row={row} metadataActions={metadataActions} />+ ) : (+ <Button+ variant="ghost"+ size="icon"+ className="bg-background/80 hover:bg-background absolute top-0 right-0 h-5 w-5 border p-0.5 opacity-0 shadow-xs transition-opacity duration-200 group-hover:opacity-100"+ onClick={handleCopy}+ title="Copy value"+ aria-label="Copy cell value"+ >+ {showCopySuccess ? (+ <Check className="h-2.5 w-2.5 text-green-600" />+ ) : (+ <Copy className="h-2.5 w-2.5" />+ )}+ </Button>+ )}</div>);},diff --git a/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx b/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsxindex 114d2afada..47810123dc 100644--- a/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx+++ b/web/src/components/trace/components/IOPreview/IOPreviewPretty.tsx@@ -1,6 +1,7 @@import { useMemo } from "react";import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { type MetadataFilterActions } from "@/src/components/table/ValueCell";import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";import { type MediaReturnType } from "@/src/features/media/validation";import { useChatMLParser } from "./hooks/useChatMLParser";@@ -156,6 +157,16 @@ export function IOPreviewPretty({: (preParsedMetadata ??deepParseJson(metadata, { maxSize: 100_000, maxDepth: 2 }));+ // Enable the metadata rows' actions menu (copy + add-to-filter). Observation+ // metadata filters the observations table; trace metadata the traces table.+ const metadataActions = useMemo<MetadataFilterActions>(+ () => ({+ projectId,+ filterTarget: observationId ? "observations" : "traces",+ }),+ [projectId, observationId],+ );+// Parse ChatML formatconst {canDisplayAsChat,@@ -299,6 +310,7 @@ export function IOPreviewPretty({currentView="pretty"externalExpansionState={metadataExpansionState}onExternalExpansionChange={onMetadataExpansionChange}+ metadataActions={metadataActions}/></div>)}diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex c96b6057ab..d9b8282c98 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -57,6 +57,7 @@ import {import {ValueCell,getValueStringLength,+ type MetadataFilterActions,} from "@/src/components/table/ValueCell";import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";@@ -541,6 +542,7 @@ function JsonPrettyTable({toggleCellExpansion,stickyTopLevelKey = false,showObservationTypeBadge = false,+ metadataActions,}: {data: JsonTableRow[];expandAllRef?: React.RefObject<(() => void) | null>;@@ -557,6 +559,7 @@ function JsonPrettyTable({toggleCellExpansion: (cellId: string) => void;stickyTopLevelKey?: boolean;showObservationTypeBadge?: boolean;+ metadataActions?: MetadataFilterActions;}) {const headerRef = useRef<HTMLTableRowElement>(null);const topLevelRowRef = useRef<HTMLTableRowElement>(null);@@ -685,6 +688,7 @@ function JsonPrettyTable({preserveStringWhitespace={row.original.key === "code_eval_source_code"}+ metadataActions={metadataActions}/>),},@@ -878,6 +882,9 @@ export function PrettyJsonView(props: {showObservationTypeBadge?: boolean;/** Content to render between header and main content (e.g., thinking blocks) */afterHeader?: React.ReactNode;+ /** When set, rows show an actions menu with copy + add-to-filter shortcuts+ (metadata views only). */+ metadataActions?: MetadataFilterActions;}) {// Use pre-parsed data if available, otherwise parse on-demandconst parsedJson = useMemo(() => {@@ -1408,6 +1415,7 @@ export function PrettyJsonView(props: {toggleCellExpansion={toggleCellExpansion}stickyTopLevelKey={props.stickyTopLevelKey}showObservationTypeBadge={props.showObservationTypeBadge}+ metadataActions={props.metadataActions}/>)}</div>diff --git a/web/src/features/events/lib/eventsTablePaths.clienttest.ts b/web/src/features/events/lib/eventsTablePaths.clienttest.tsnew file mode 100644index 0000000000..2fb261b687--- /dev/null+++ b/web/src/features/events/lib/eventsTablePaths.clienttest.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from "vitest";+import { type FilterState } from "@langfuse/shared";+import {+ decodeFiltersGeneric,+ encodeFiltersGeneric,+} from "@/src/features/filters/lib/filter-query-encoding";+import { buildEventsTablePathForMetadataFilter } from "./eventsTablePaths";++const PROJECT = "p1";++const meta = (+ key: string,+ operator: "=" | "contains" | "does not contain" | "starts with" | "ends with",+ value: string,+): FilterState[number] =>+ ({+ column: "metadata",+ type: "stringObject",+ key,+ operator,+ value,+ }) as FilterState[number];++/** Build a `currentPath` the same way the events table encodes its URL. */+const currentPathWith = (+ filters: FilterState,+ opts: { dateRange?: string } = {},+): string => {+ const params = new URLSearchParams();+ if (filters.length > 0) params.set("filter", encodeFiltersGeneric(filters));+ if (opts.dateRange) params.set("dateRange", opts.dateRange);+ const q = params.toString();+ return `/project/${PROJECT}/observations${q ? `?${q}` : ""}`;+};++/** Decode the filters the builder produced back out of the result path. */+const filtersOf = (path: string): FilterState => {+ const url = new URL(path, "https://x.local");+ return decodeFiltersGeneric(url.searchParams.get("filter") ?? "");+};++const build = (+ currentPath: string,+ operator: "contains" | "does not contain",+ opts: {+ metadataKey?: string;+ value?: string;+ target?: "observations" | "traces";+ } = {},+) =>+ buildEventsTablePathForMetadataFilter({+ currentPath,+ projectId: PROJECT,+ metadataKey: opts.metadataKey ?? "scope",+ value: opts.value ?? "alpha",+ operator,+ target: opts.target ?? "observations",+ });++describe("buildEventsTablePathForMetadataFilter", () => {+ it("adds a single clause from an empty filter state", () => {+ const path = build("/project/p1/observations", "contains");+ expect(path.startsWith("/project/p1/observations?")).toBe(true);+ expect(filtersOf(path)).toEqual([meta("scope", "contains", "alpha")]);+ });++ it("routes to the requested table", () => {+ const path = build("/project/p1/traces", "contains", { target: "traces" });+ expect(path.startsWith("/project/p1/traces?")).toBe(true);+ });++ it("preserves the dateRange param", () => {+ const path = build(+ currentPathWith([], { dateRange: "All time" }),+ "contains",+ );+ const url = new URL(path, "https://x.local");+ expect(url.searchParams.get("dateRange")).toBe("All time");+ });++ it("toggles Include -> Exclude on the same value (replace, not AND)", () => {+ const path = build(+ currentPathWith([meta("scope", "contains", "alpha")]),+ "does not contain",+ );+ expect(filtersOf(path)).toEqual([+ meta("scope", "does not contain", "alpha"),+ ]);+ });++ it("toggles Exclude -> Include on the same value", () => {+ const path = build(+ currentPathWith([meta("scope", "does not contain", "alpha")]),+ "contains",+ );+ expect(filtersOf(path)).toEqual([meta("scope", "contains", "alpha")]);+ });++ it("is idempotent when re-adding the same clause", () => {+ const path = build(+ currentPathWith([meta("scope", "contains", "alpha")]),+ "contains",+ );+ expect(filtersOf(path)).toEqual([meta("scope", "contains", "alpha")]);+ });++ it("AND-merges clauses on a different key", () => {+ const path = build(+ currentPathWith([meta("env", "contains", "prod")]),+ "contains",+ { metadataKey: "scope", value: "alpha" },+ );+ expect(filtersOf(path)).toEqual([+ meta("env", "contains", "prod"),+ meta("scope", "contains", "alpha"),+ ]);+ });++ it("AND-merges clauses on the same key but a different value", () => {+ const path = build(+ currentPathWith([meta("scope", "contains", "alpha")]),+ "contains",+ { value: "beta" },+ );+ expect(filtersOf(path)).toEqual([+ meta("scope", "contains", "alpha"),+ meta("scope", "contains", "beta"),+ ]);+ });++ it("Include preserves a stricter '=' clause (no broadening)", () => {+ const path = build(+ currentPathWith([meta("scope", "=", "production")]),+ "contains",+ { value: "production" },+ );+ // `= production` is kept; the redundant `contains production` ANDs with it.+ expect(filtersOf(path)).toEqual([+ meta("scope", "=", "production"),+ meta("scope", "contains", "production"),+ ]);+ });++ it("Exclude drops a contradicting '=' clause on the same value", () => {+ const path = build(+ currentPathWith([meta("scope", "=", "production")]),+ "does not contain",+ { value: "production" },+ );+ // `= v AND does not contain v` is always false — the `=` must be dropped.+ expect(filtersOf(path)).toEqual([+ meta("scope", "does not contain", "production"),+ ]);+ });++ it("Exclude drops a contradicting 'starts with' clause on the same value", () => {+ const path = build(+ currentPathWith([meta("scope", "starts with", "production")]),+ "does not contain",+ { value: "production" },+ );+ expect(filtersOf(path)).toEqual([+ meta("scope", "does not contain", "production"),+ ]);+ });+});diff --git a/web/src/features/events/lib/eventsTablePaths.ts b/web/src/features/events/lib/eventsTablePaths.tsindex c8ef0950fc..da352a3d5b 100644--- a/web/src/features/events/lib/eventsTablePaths.ts+++ b/web/src/features/events/lib/eventsTablePaths.ts@@ -1,5 +1,8 @@import { type FilterState } from "@langfuse/shared";-import { encodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";+import {+ decodeFiltersGeneric,+ encodeFiltersGeneric,+} from "@/src/features/filters/lib/filter-query-encoding";type BuildEventsTablePathForSpanNameParams = {currentPath: string;@@ -73,3 +76,86 @@ export function buildEventsTablePathForObservationType({value: observationType,});}++export type MetadataFilterOperator = "=" | "contains" | "does not contain";++type BuildEventsTablePathForMetadataFilterParams = {+ currentPath: string;+ projectId: string;+ metadataKey: string;+ value: string;+ operator: MetadataFilterOperator;+ /** Whether to land on the observations or traces events table. */+ target: "observations" | "traces";+};++/**+ * Builds an events-table URL that adds a `metadata` filter (a `stringObject`+ * clause). Unlike the name/type helpers above, this MERGES into any filters+ * already present in `currentPath` (e.g. the list filter behind a peek) so the+ * action reads as "add to filter" rather than "replace". The clicked value is+ * matched against the top-level metadata key — metadata is stored as a flat+ * `Map(String, String)`, so a nested value is filtered as a `contains` on its+ * top-level branch (the caller chooses the operator accordingly).+ */+export function buildEventsTablePathForMetadataFilter({+ currentPath,+ projectId,+ metadataKey,+ value,+ operator,+ target,+}: BuildEventsTablePathForMetadataFilterParams) {+ const url = new URL(currentPath, "https://langfuse.local");+ const params = new URLSearchParams();++ const dateRange = url.searchParams.get("dateRange");+ if (dateRange) {+ params.set("dateRange", dateRange);+ }++ const existingFilters = decodeFiltersGeneric(+ url.searchParams.get("filter") ?? "",+ );++ // Reconcile the new clause against any existing clause on this same+ // key+value, direction-aware:+ // - Include (`contains`) only toggles the menu's OWN operators (contains /+ // does not contain). A stricter clause set elsewhere — the filter-builder+ // defaults stringObject to `=`, plus starts/ends with — is preserved, so a+ // one-click Include never broadens an exact filter (`= v AND contains v`+ // reduces to `= v`).+ // - Exclude (`does not contain`) contradicts EVERY positive clause on the+ // value (`= v`, `starts/ends with v` all imply it contains v), so it drops+ // them all; otherwise `= v AND does not contain v` is always false and+ // silently empties the table.+ // Clauses on other keys/values are always left untouched (AND-merge).+ const isExclude = operator === "does not contain";+ const withoutConflicting = existingFilters.filter((f) => {+ const sameTarget =+ f.column === "metadata" &&+ f.type === "stringObject" &&+ f.key === metadataKey &&+ f.value === value;+ if (!sameTarget) return true;+ if (isExclude) return false;+ return f.operator !== "contains" && f.operator !== "does not contain";+ });++ const filters: FilterState = [+ ...withoutConflicting,+ {+ column: "metadata",+ type: "stringObject",+ key: metadataKey,+ operator,+ value,+ },+ ];++ params.set("filter", encodeFiltersGeneric(filters));++ const query = params.toString();++ return `/project/${projectId}/${target}${query ? `?${query}` : ""}`;+}