πͺ’ 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(search-bar): score Ask AI parse outcomes on the trace (LFE-11001) (#15407)
Nikita Kabardind22c33260b44
diff --git a/web/src/__tests__/server/unit/parseOutcomeScoring.servertest.ts b/web/src/__tests__/server/unit/parseOutcomeScoring.servertest.tsnew file mode 100644index 0000000000..cebb557f04--- /dev/null+++ b/web/src/__tests__/server/unit/parseOutcomeScoring.servertest.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from "vitest";++import { deriveParseOutcomeScores } from "@/src/features/search-bar/server/parseOutcomeScoring";+import type { GeneratedFilters } from "@/src/features/search-bar/server/parseFilterCompletion";++// Only `.length` of `filters` matters to the derivation, so a loosely-typed+// stand-in keeps these cases focused on the outcome shape rather than real+// `FilterState` entries (already covered by parseFilterCompletion.servertest.ts).+function fakeFilters(count: number): GeneratedFilters["filters"] {+ return Array.from(+ { length: count },+ () => ({}) as GeneratedFilters["filters"][number],+ );+}++describe("deriveParseOutcomeScores", () => {+ it("scores a clean, well-formed answer with no fences", () => {+ const raw =+ '[{"type":"number","column":"latency","operator":">","value":2}]';+ const scores = deriveParseOutcomeScores(raw, {+ filters: fakeFilters(1),+ queryText: "latency > 2",+ droppedCount: 0,+ unknownScoreNames: [],+ });++ expect(scores).toEqual([+ { name: "parse-empty-result", dataType: "BOOLEAN", value: 0 },+ { name: "parse-dropped-filters", dataType: "NUMERIC", value: 0 },+ { name: "parse-unknown-score-names", dataType: "NUMERIC", value: 0 },+ {+ name: "filter-count",+ dataType: "NUMERIC",+ value: 1,+ comment: "latency > 2",+ },+ { name: "output-markdown-fenced", dataType: "BOOLEAN", value: 0 },+ ]);+ });++ it("flags the couldn't-build-filters outcome (empty result)", () => {+ const raw = "[]";+ const scores = deriveParseOutcomeScores(raw, {+ filters: fakeFilters(0),+ queryText: "",+ droppedCount: 0,+ unknownScoreNames: [],+ });++ const empty = scores.find((s) => s.name === "parse-empty-result");+ const count = scores.find((s) => s.name === "filter-count");+ expect(empty).toEqual({+ name: "parse-empty-result",+ dataType: "BOOLEAN",+ value: 1,+ });+ // No filters => no query text => no comment attached.+ expect(count).toEqual({+ name: "filter-count",+ dataType: "NUMERIC",+ value: 0,+ comment: undefined,+ });+ });++ it("detects a ```-fenced raw completion even when parsing recovered", () => {+ const raw = [+ "```json",+ '[{"type":"number","column":"latency","operator":">","value":2}]',+ "```",+ ].join("\n");+ const scores = deriveParseOutcomeScores(raw, {+ filters: fakeFilters(1),+ queryText: "latency > 2",+ droppedCount: 0,+ unknownScoreNames: [],+ });++ expect(scores.find((s) => s.name === "output-markdown-fenced")).toEqual({+ name: "output-markdown-fenced",+ dataType: "BOOLEAN",+ value: 1,+ });+ });++ it("does not flag a clean, unfenced answer whose filter VALUE echoes a literal ``` (LFE-11001)", () => {+ const raw =+ '[{"type":"stringOptions","column":"output","operator":"contains","value":"```"}]';+ const scores = deriveParseOutcomeScores(raw, {+ filters: fakeFilters(1),+ queryText: 'output contains "```"',+ droppedCount: 0,+ unknownScoreNames: [],+ });++ expect(scores.find((s) => s.name === "output-markdown-fenced")).toEqual({+ name: "output-markdown-fenced",+ dataType: "BOOLEAN",+ value: 0,+ });+ });++ it("reports dropped filters and unknown score names as counts", () => {+ const raw =+ '[{"type":"numberObject","column":"scores_avg","key":"my_score","operator":">","value":1}]';+ const scores = deriveParseOutcomeScores(raw, {+ filters: fakeFilters(0),+ queryText: "",+ droppedCount: 1,+ unknownScoreNames: ["my_score"],+ });++ expect(scores.find((s) => s.name === "parse-dropped-filters")).toEqual({+ name: "parse-dropped-filters",+ dataType: "NUMERIC",+ value: 1,+ });+ expect(scores.find((s) => s.name === "parse-unknown-score-names")).toEqual({+ name: "parse-unknown-score-names",+ dataType: "NUMERIC",+ value: 1,+ });+ });++ it("truncates a very long applied query text on the filter-count comment", () => {+ const longQuery = "level = ERROR OR ".repeat(50) + "level = ERROR";+ const scores = deriveParseOutcomeScores("[]", {+ filters: fakeFilters(3),+ queryText: longQuery,+ droppedCount: 0,+ unknownScoreNames: [],+ });++ const filterCount = scores.find((s) => s.name === "filter-count");+ expect(filterCount?.comment?.length).toBeLessThanOrEqual(500);+ expect(longQuery.length).toBeGreaterThan(500);+ });+});diff --git a/web/src/__tests__/server/unit/parseOutcomeScoringWiring.servertest.ts b/web/src/__tests__/server/unit/parseOutcomeScoringWiring.servertest.tsnew file mode 100644index 0000000000..eab9d69e44--- /dev/null+++ b/web/src/__tests__/server/unit/parseOutcomeScoringWiring.servertest.ts@@ -0,0 +1,75 @@+// Mocked smoke test for the I/O side of `parseOutcomeScoring.ts`+// (`recordParseOutcomeScores`), which `parseOutcomeScoring.servertest.ts`+// deliberately does not cover (it only exercises the pure+// `deriveParseOutcomeScores`). This asserts the wiring β a `Langfuse` client+// gets constructed, `.score()` is called once per derived score with the+// expected name/dataType, and the batch is flushed β without a live+// Langfuse client or network call.+import { describe, expect, it, vi } from "vitest";++const scoreMock = vi.fn();+const flushAsyncMock = vi.fn().mockResolvedValue(undefined);++// `parseOutcomeScoring.ts` constructs its own `Langfuse` client directly+// (deliberately not via the shared `getLangfuseClient` helper β see its+// comment on `scoreClient`), so the raw SDK constructor is what needs+// mocking here, not a wrapper module.+vi.mock("langfuse", () => ({+ // A plain `function` (not an arrow function) β `parseOutcomeScoring.ts`+ // instantiates this via `new Langfuse(...)`, which arrow functions cannot+ // be used as a constructor for.+ Langfuse: vi.fn().mockImplementation(function MockLangfuse() {+ return {+ score: scoreMock,+ flushAsync: flushAsyncMock,+ };+ }),+}));++import {+ deriveParseOutcomeScores,+ recordParseOutcomeScores,+} from "@/src/features/search-bar/server/parseOutcomeScoring";++describe("recordParseOutcomeScores (mocked Langfuse client)", () => {+ it("scores the trace once per derived score and flushes the batch", () => {+ const scores = deriveParseOutcomeScores(+ '[{"type":"number","column":"latency","operator":">","value":2}]',+ {+ filters: [{} as never],+ queryText: "latency > 2",+ droppedCount: 0,+ unknownScoreNames: [],+ },+ );++ recordParseOutcomeScores({+ traceId: "trace-abc123",+ scores,+ publicKey: "pk-test",+ secretKey: "sk-test",+ baseUrl: "https://example.com",+ });++ // `recordParseOutcomeScores` runs its I/O synchronously up to the first+ // await (the flush race), so the `.score()` calls and the `flushAsync`+ // invocation are already observable without awaiting anything here.+ expect(scoreMock).toHaveBeenCalledTimes(5);+ expect(+ scoreMock.mock.calls.map(([call]) => ({+ name: call.name,+ dataType: call.dataType,+ })),+ ).toEqual([+ { name: "parse-empty-result", dataType: "BOOLEAN" },+ { name: "parse-dropped-filters", dataType: "NUMERIC" },+ { name: "parse-unknown-score-names", dataType: "NUMERIC" },+ { name: "filter-count", dataType: "NUMERIC" },+ { name: "output-markdown-fenced", dataType: "BOOLEAN" },+ ]);+ expect(+ scoreMock.mock.calls.every(([call]) => call.traceId === "trace-abc123"),+ ).toBe(true);+ expect(flushAsyncMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/features/search-bar/server/parseOutcomeScoring.ts b/web/src/features/search-bar/server/parseOutcomeScoring.tsnew file mode 100644index 0000000000..5d15231aa4--- /dev/null+++ b/web/src/features/search-bar/server/parseOutcomeScoring.ts@@ -0,0 +1,194 @@+// Score the PARSE OUTCOME of an Ask AI filter completion onto the+// generation's trace in the AI-features Langfuse project, so production+// traffic becomes a queryable, self-harvesting quality signal instead of+// only a server `logger.warn` (see `router.ts`'s `generateFilter`, which+// already logs `droppedCount`/`unknownScoreNames` but never persists them).+//+// Split pure derivation (`deriveParseOutcomeScores`, unit-tested directly)+// from the I/O (`recordParseOutcomeScores`, fire-and-forget, never throws)+// for the same reason `parseFilterCompletion.ts` keeps parsing separate from+// the tRPC procedure: the branching logic should be testable without a live+// model OR a live Langfuse client.++import { Langfuse } from "langfuse";+import { logger } from "@langfuse/shared/src/server";+import { getProductBaseUrl } from "@/src/utils/base-url";+import type { GeneratedFilters } from "./parseFilterCompletion";++export type ParseOutcomeScoreName =+ | "parse-empty-result"+ | "parse-dropped-filters"+ | "parse-unknown-score-names"+ | "filter-count"+ | "output-markdown-fenced";++export type ParseOutcomeScore = {+ name: ParseOutcomeScoreName;+ value: number;+ dataType: "NUMERIC" | "BOOLEAN";+ /** Short, human-readable context attached to exactly one score so a+ * reviewer can see what actually applied without decoding the raw+ * completion. */+ comment?: string;+};++// Keep the attached query text short β this is a glance-in-the-UI+// annotation, not a second copy of the trace input/output.+const MAX_QUERY_TEXT_COMMENT_LENGTH = 500;++/**+ * Pure derivation of the parse-outcome scores from the raw completion string+ * and the `parseGeneratedFilters` result. No I/O β this is what the unit+ * tests exercise directly, without a live Langfuse client.+ */+export function deriveParseOutcomeScores(+ raw: string,+ parsed: Pick<+ GeneratedFilters,+ "filters" | "queryText" | "droppedCount" | "unknownScoreNames"+ >,+): ParseOutcomeScore[] {+ const queryTextComment =+ parsed.queryText.length > 0+ ? parsed.queryText.slice(0, MAX_QUERY_TEXT_COMMENT_LENGTH)+ : undefined;++ return [+ {+ name: "parse-empty-result",+ dataType: "BOOLEAN",+ value: parsed.filters.length === 0 ? 1 : 0,+ },+ {+ name: "parse-dropped-filters",+ dataType: "NUMERIC",+ value: parsed.droppedCount,+ },+ {+ name: "parse-unknown-score-names",+ dataType: "NUMERIC",+ value: parsed.unknownScoreNames.length,+ },+ {+ name: "filter-count",+ dataType: "NUMERIC",+ value: parsed.filters.length,+ // Attached here (rather than a new field/metadata write) so a+ // reviewer can see what actually got applied without decoding the raw+ // completion β this score is the closest proxy for "did the request+ // resolve to a real answer".+ comment: queryTextComment,+ },+ {+ // THE key Haiku-adherence signal we're watching while tuning the+ // prompt: the system prompt says "no markdown fences", yet the model+ // frequently OPENS its answer with a ```...``` fence anyway. Anchored+ // to the start of the (trimmed) RAW completion β before any+ // parsing/extraction β rather than a substring search over the whole+ // completion, so a filter VALUE that happens to echo a literal ```+ // (e.g. a `contains` filter on a code block) can never flip this flag;+ // only the model actually opening its answer with a fence can.+ name: "output-markdown-fenced",+ dataType: "BOOLEAN",+ value: raw.trim().startsWith("```") ? 1 : 0,+ },+ ];+}++// A dedicated singleton, deliberately SEPARATE from+// `../../natural-language-filters/server/utils.ts`'s `getLangfuseClient`.+// Every existing caller of that helper passes `enabled: false` (it is only+// ever used to fetch a managed prompt, never to write events), and the+// helper memoizes on the FIRST call regardless of the `enabled` argument any+// later caller passes β reusing it here would silently turn every+// `.score()` call below into a no-op for the lifetime of the process, the+// moment any caller (anywhere) constructs it disabled first.+let scoreClient: Langfuse | null = null;++function getParseOutcomeScoreClient(params: {+ publicKey: string;+ secretKey: string;+ baseUrl: string | undefined;+}): Langfuse {+ if (!scoreClient) {+ scoreClient = new Langfuse({+ publicKey: params.publicKey,+ secretKey: params.secretKey,+ // Mirrors `getLangfuseClient`'s fallback: self-referential deployments+ // (e.g. PR previews) must talk to themselves, not cloud.langfuse.com.+ baseUrl: params.baseUrl ?? getProductBaseUrl().toString(),+ // This path must never affect the user-facing response (see+ // `recordParseOutcomeScores`), so a slow/unreachable AI-features+ // project should fail fast in the background rather than retry.+ fetchRetryCount: 0,+ requestTimeout: 3_000,+ });+ }+ return scoreClient;+}++// Bounds how long `recordParseOutcomeScores` waits on the background flush+// before giving up β the SDK's own request keeps running (or times out via+// `requestTimeout` above) regardless; this only bounds how long our+// fire-and-forget promise chain stays alive.+const FLUSH_TIMEOUT_MS = 2_000;++/**+ * Fire-and-forget: attaches `scores` to `traceId` in the AI-features+ * Langfuse project. Never throws and returns no promise for the caller to+ * await β every failure mode (client construction, `.score()`, flushing)+ * resolves to a `logger.warn`, so a slow or unreachable AI-features project+ * can never add latency to, or break, the user's response.+ */+export function recordParseOutcomeScores(params: {+ traceId: string;+ scores: ParseOutcomeScore[];+ publicKey: string;+ secretKey: string;+ baseUrl?: string;+}): void {+ // `.catch` (rather than `await`/`void`) is the whole point: the caller+ // gets a plain `void`-returning function back and never sees a promise to+ // accidentally await, while this one is still guaranteed "handled" so it+ // can never surface as an unhandled rejection.+ runParseOutcomeScoring(params).catch((error) => {+ logger.warn("Failed to record Ask AI parse-outcome scores", {+ traceId: params.traceId,+ error,+ });+ });+}++async function runParseOutcomeScoring(params: {+ traceId: string;+ scores: ParseOutcomeScore[];+ publicKey: string;+ secretKey: string;+ baseUrl?: string;+}): Promise<void> {+ const { traceId, scores, publicKey, secretKey, baseUrl } = params;+ const client = getParseOutcomeScoreClient({ publicKey, secretKey, baseUrl });+ for (const score of scores) {+ client.score({+ traceId,+ name: score.name,+ value: score.value,+ dataType: score.dataType,+ ...(score.comment ? { comment: score.comment } : {}),+ });+ }+ // `.catch` here (rather than only relying on the caller's `.catch` above)+ // means the flush promise is always settled before the race below can+ // move on, so a late rejection can never surface as an unhandled promise+ // rejection after the timeout wins.+ const flushed = client.flushAsync().catch((error) => {+ logger.warn("Ask AI parse-outcome score flush failed", {+ traceId,+ error,+ });+ });+ await Promise.race([+ flushed,+ new Promise<void>((resolve) => setTimeout(resolve, FLUSH_TIMEOUT_MS)),+ ]);+}diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.tsindex de7ccb000a..23e535f0f6 100644--- a/web/src/features/search-bar/server/router.ts+++ b/web/src/features/search-bar/server/router.ts@@ -26,6 +26,7 @@ import {logger,} from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";+import { randomBytes } from "crypto";import { z } from "zod";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {@@ -35,6 +36,10 @@ import {import { buildFilterContextMessage } from "./buildFilterPrompt";import { resolveFilterSystemPrompt } from "./resolveFilterPrompt";import { parseGeneratedFilters } from "./parseFilterCompletion";+import {+ deriveParseOutcomeScores,+ recordParseOutcomeScores,+} from "./parseOutcomeScoring";import {generateLangfuseAIText,getLangfuseAITraceSinkParams,@@ -139,6 +144,16 @@ export const searchBarRouter = createTRPCRouter({});}+ // Pre-generated (rather than left to `getLangfuseAITraceSinkParams`'s+ // own default) so this handler OWNS the id: the parse-outcome scores+ // attached below must land on the exact same trace as the+ // generation, and a future satisfaction signal needs a stable id to+ // key off too. Same format the default would have produced (a 32-hex+ // W3C trace id) β only needed when we're actually tracing.+ const traceId = aiTelemetryEnabled+ ? randomBytes(16).toString("hex")+ : undefined;+// Prefer the MANAGED `search-bar-filter` Langfuse prompt (dogfooding// β same AI-features project/client the v3 natural-language-filter// path uses); falls back to the code-built skeleton whenever the@@ -190,6 +205,7 @@ export const searchBarRouter = createTRPCRouter({maxTokens: 2048,traceSinkParams: aiTelemetryEnabled? getLangfuseAITraceSinkParams({+ traceId,environment:LangfuseInternalTraceEnvironment.NaturalLanguageFilter,feature: "search-bar-filter",@@ -246,6 +262,43 @@ export const searchBarRouter = createTRPCRouter({);}+ // Turn the parse outcome into queryable scores on the generation's+ // trace, so production traffic self-harvests quality signal (e.g.+ // the model wrapping its answer in ```markdown fences despite the+ // prompt saying not to) instead of only ever hitting the warn log+ // above. Gated exactly like the trace write itself (telemetry+ // consent + AI-features keys present) β this writes into the same+ // AI-features project under the same consent surface. Fire-and-forget+ // and fully isolated in its own try/catch: a slow or failing score+ // write must never break or slow this response.+ if (+ aiTelemetryEnabled &&+ traceId &&+ env.LANGFUSE_AI_FEATURES_PUBLIC_KEY &&+ env.LANGFUSE_AI_FEATURES_SECRET_KEY+ ) {+ try {+ recordParseOutcomeScores({+ traceId,+ scores: deriveParseOutcomeScores(llmCompletion, {+ filters,+ queryText,+ droppedCount,+ unknownScoreNames,+ }),+ publicKey: env.LANGFUSE_AI_FEATURES_PUBLIC_KEY,+ secretKey: env.LANGFUSE_AI_FEATURES_SECRET_KEY,+ baseUrl: env.LANGFUSE_AI_FEATURES_HOST,+ });+ } catch (error) {+ logger.warn("Failed to record Ask AI parse-outcome scores", {+ projectId: input.projectId,+ traceId,+ error,+ });+ }+ }+return { filters, queryText, unknownScoreNames };} catch (error) {// Already-shaped rejections (auth / precondition / not-found) are