πͺ’ 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): detangle Ask AI system prompt from injected context (LFE-11003) (#15292)
Nikita Kabardin97059ee36a99
diff --git a/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts b/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.tsindex 410650b29c..0ea3e5fde7 100644--- a/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts+++ b/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts@@ -7,6 +7,7 @@ import {type FieldDef,} from "@/src/features/search-bar/lib/fields";import {+ buildFilterContextMessage,buildFilterSystemPrompt,specForField,} from "@/src/features/search-bar/server/buildFilterPrompt";@@ -75,21 +76,81 @@ describe("buildFilterSystemPrompt", () => {expect(prompt).toContain(SCORE_COLUMNS.trace.boolean);});- it("omits the refine section without a current query", () => {- expect(prompt).not.toContain("Current filters");+ it("contains the refine RULES, but never the injected VALUES", () => {+ // The refinement rules ("KEEP every existing filter...", the worked+ // example) are instructions on HOW to use current filters, not the+ // filters themselves β they belong in the system prompt so a later user+ // turn (the actual request) can never outrank them. Only the injected,+ // per-request VALUES (the query text being refined, observed project+ // data) live in `buildFilterContextMessage`'s own message.+ expect(prompt).toContain("## Refining existing filters");+ expect(prompt).toContain("KEEP every existing filter");+ expect(prompt).toContain(+ '[{"type":"stringOptions","column":"level","operator":"any of","value":["ERROR"]},{"type":"stringOptions","column":"environment","operator":"any of","value":["production"]}]',+ );+ // No injected VALUES (nor the headings that only ever wrap a VALUE) ever+ // appear in the static skeleton.+ expect(prompt).not.toContain("## Current filters");+ expect(prompt).not.toContain("## Observed project data");+ });++ it("no longer accepts currentQuery/dataContext β single-datetime signature", () => {+ // Regression guard for the detangle: the skeleton takes only the anchor+ // datetime now, so passing extra args would be a silent no-op if the+ // signature ever regained them without a type error surfacing here.+ expect(buildFilterSystemPrompt.length).toBe(1);});+});- it("includes the current query as refine context when provided", () => {- const refinePrompt = buildFilterSystemPrompt(- "Monday, 2026-06-15T00:00:00.000Z",+describe("buildFilterContextMessage", () => {+ it("returns null when neither current query nor data context is given", () => {+ expect(buildFilterContextMessage()).toBeNull();+ expect(buildFilterContextMessage("", "")).toBeNull();+ expect(buildFilterContextMessage(" ", undefined)).toBeNull();+ });++ it("includes the current query as a bare VALUE, no refine RULES", () => {+ const message = buildFilterContextMessage("environment:production level:ERROR",);- expect(refinePrompt).toContain("Current filters β REFINE, do not replace");- expect(refinePrompt).toContain("environment:production level:ERROR");- // The preservation instruction + worked example are what stop the model- // from replacing the whole set when the user says "only X".- expect(refinePrompt).toContain("ON TOP OF the current ones");- expect(refinePrompt).toContain("Worked example");+ expect(message).not.toBeNull();+ expect(message).toContain("## Current filters");+ expect(message).toContain("environment:production level:ERROR");+ // The refine RULES (why/how to keep existing filters) now live only in+ // the system prompt β this message must never re-state them, or a later+ // user turn (the actual request) could again outrank them.+ expect(message).not.toContain("KEEP every existing filter");+ expect(message).not.toContain("ON TOP OF the current ones");+ expect(message).not.toContain("Worked example");+ // No data context was given, so that section should be absent.+ expect(message).not.toContain("Observed project data");+ });++ it("includes observed project data as a bare VALUE, no usage RULES", () => {+ const message = buildFilterContextMessage(+ undefined,+ "metadata keys: routing.queue, tenant",+ );+ expect(message).not.toBeNull();+ expect(message).toContain("## Observed project data");+ expect(message).toContain("metadata keys: routing.queue, tenant");+ expect(message).not.toContain("Current filters");+ // The usage rule ("map the request to what ACTUALLY appears...") now+ // lives in the system prompt.+ expect(message).not.toContain("ACTUALLY appear");+ });++ it("includes both sections, refine before data, when both are provided", () => {+ const message = buildFilterContextMessage(+ "level:ERROR",+ "metadata keys: routing.queue",+ );+ expect(message).not.toBeNull();+ expect(message).toContain("## Current filters");+ expect(message).toContain("## Observed project data");+ expect(message!.indexOf("Current filters")).toBeLessThan(+ message!.indexOf("Observed project data"),+ );});});diff --git a/web/src/features/search-bar/server/buildFilterPrompt.ts b/web/src/features/search-bar/server/buildFilterPrompt.tsindex 3ceb206bec..973f8e81a4 100644--- a/web/src/features/search-bar/server/buildFilterPrompt.ts+++ b/web/src/features/search-bar/server/buildFilterPrompt.ts@@ -80,43 +80,28 @@ function fieldCatalogLine(field: FieldDef): string {}/**- * Build the full system prompt. `currentDatetime` anchors relative time- * expressions ("today", "last 24h") to the request time. `currentQuery`, when- * present, is the user's existing filters (in this same syntax) so the model- * REFINES them and returns the complete updated set.+ * Build the STATIC system prompt: role, output format, column catalog, and+ * all fixed rules/examples, anchored to `currentDatetime` (so relative time+ * expressions like "today" / "last 24h" resolve against the request time).+ * This includes the "## Refining existing filters" rules β those are+ * instructions on HOW to use the current filters, not the filters+ * themselves, so they belong in the system prompt and stay unconditionally+ * present. They're harmless when no current filters are sent: the rule text+ * itself is conditioned on "if there are current filters ... in the+ * following message".+ *+ * Deliberately holds no per-request DATA β the current query being refined+ * and the observed project data are dynamic values, not instructions, so they+ * travel in a separate message (`buildFilterContextMessage`). This keeps the+ * self-traced generation legible (prompt vs. injected data are visibly+ * different messages), stops a later user turn from being able to outrank+ * rules that would otherwise ride along in a user message, and sets up the+ * skeleton to become a managed prompt without dynamic values baked into its+ * text.*/-export function buildFilterSystemPrompt(- currentDatetime: string,- currentQuery?: string,- dataContext?: string,-): string {+export function buildFilterSystemPrompt(currentDatetime: string): string {const catalog = FIELDS.map(fieldCatalogLine).join("\n");const nullableIds = FIELDS.filter((f) => f.nullable).map((f) => f.id);- const refine = (currentQuery ?? "").trim();- const data = (dataContext ?? "").trim();- const dataSection =- data.length > 0- ? `\n## Observed project data\n\nMap the request to the columns, values, and metadata keys that ACTUALLY appear below β prefer an observed value/metadata key over guessing a column. If a phrase matches a metadata key, use \`metadata.<key>\`. Do not invent values that aren't here unless the user gave a literal one.\n\n${data}\n`- : "";- const refineSection =- refine.length > 0- ? `\n## Current filters β REFINE, do not replace--The user ALREADY has these filters applied (same syntax as your output):-\`${refine}\`--The new request is an EDIT to this set, not a fresh start. Rules:-- KEEP every existing filter unless the request explicitly removes it or directly contradicts it.-- ADD a filter for whatever the request narrows down to.-- Only modify or drop a filter the request actually targets.--A phrase like "only X" / "just X" / "show me X" / "narrow to X" means ADD an X filter ON TOP OF the current ones β it does NOT mean discard the rest. Return the COMPLETE resulting array (existing filters that remain PLUS any new ones), never just the new delta.--Worked example β current filters \`level:ERROR\`, request "only in production":-you return BOTH filters, not just environment:-[{"type":"stringOptions","column":"level","operator":"any of","value":["ERROR"]},{"type":"stringOptions","column":"environment","operator":"any of","value":["production"]}]-`- : "";return `## Role@@ -134,10 +119,13 @@ column matches. You can filter on:**negation / exclusion**.Prefer values, metadata keys, and score names that appear in the observed-project data below (when provided) over inventing your own. Use real catalog-columns for standard fields; for anything custom or domain-specific, use-\`metadata.<key>\`. Don't fall back to a vague column guess when metadata or-content search expresses the intent better.+project data (when provided) over inventing your own β map the request to the+columns, values, and metadata keys that ACTUALLY appear there rather than+guessing, and don't invent a value that isn't present unless the user gave+that literal value themselves. Use real catalog columns for standard fields;+for anything custom or domain-specific, use \`metadata.<key>\`. Don't fall back+to a vague column guess when metadata or content search expresses the intent+better.If the request is vague or maps to no concrete filter (e.g. "unusual","interesting", "weird", "anything odd"), return [] β do NOT invent columns,@@ -226,11 +214,26 @@ traceTags is an array. "tagged a or b" β any of [a, b]; "tagged BOTH a and b"- "root spans" / "top-level" β isRootObservation = true.- "named X" / "called X" β the name or traceName column (NOT environment).+## Refining existing filters++If there are current filters provided in the following message, the user+ALREADY has those filters applied (same syntax as your output). The new+request is an EDIT to this set, not a fresh start. Rules:+- KEEP every existing filter unless the request explicitly removes it or directly contradicts it.+- ADD a filter for whatever the request narrows down to.+- Only modify or drop a filter the request actually targets.++A phrase like "only X" / "just X" / "show me X" / "narrow to X" means ADD an X filter ON TOP OF the current ones β it does NOT mean discard the rest. Return the COMPLETE resulting array (existing filters that remain PLUS any new ones), never just the new delta.++Worked example β current filters \`level:ERROR\`, request "only in production":+you return BOTH filters, not just environment:+[{"type":"stringOptions","column":"level","operator":"any of","value":["ERROR"]},{"type":"stringOptions","column":"environment","operator":"any of","value":["production"]}]+## Current datetimeThe current datetime is: ${currentDatetime}Use it to resolve relative time expressions against the startTime column.-${refineSection}${dataSection}+## ExamplesThese span the full surface β comparisons, scores, metadata, content search,@@ -261,3 +264,50 @@ Output: [{"type":"arrayOptions","column":"traceTags","operator":"all of","value"Input: "gpt-4 generations costing more than $0.50 that aren't errors"Output: [{"type":"stringOptions","column":"providedModelName","operator":"any of","value":["gpt-4"]},{"type":"stringOptions","column":"type","operator":"any of","value":["GENERATION"]},{"type":"number","column":"totalCost","operator":">","value":0.5},{"type":"stringOptions","column":"level","operator":"none of","value":["ERROR"]}]`;}++/**+ * Build the INJECTED-CONTEXT message: the current filters being refined and+ * the observed project data, as a SEPARATE message from the system skeleton+ * (`buildFilterSystemPrompt`). Both are dynamic, request-specific VALUES, not+ * instructions β keeping them out of the system prompt is what lets a trace+ * show "here is the prompt" and "here is the data we handed it" as distinct+ * messages instead of one undifferentiated blob.+ *+ * This message carries ONLY the values, never the rules for how to use them:+ * the refine rules ("## Refining existing filters") and the observed-data+ * usage rules live in `buildFilterSystemPrompt` instead, so a later USER turn+ * (the actual request) can never outrank them the way it could when the+ * rules travelled in a user message. Putting untrusted/variable instructions+ * in a user turn risks the model treating the next user turn as an override.+ *+ * Returns `null` when there is neither a current query nor data context, so+ * the caller can omit the message entirely rather than sending an empty one.+ */+export function buildFilterContextMessage(+ currentQuery?: string,+ dataContext?: string,+): string | null {+ const refine = (currentQuery ?? "").trim();+ const data = (dataContext ?? "").trim();+ if (refine.length === 0 && data.length === 0) return null;++ const refineSection =+ refine.length > 0+ ? `## Current filters++Refine these (same syntax as your output):+\`${refine}\`+`+ : "";+ const dataSection =+ data.length > 0+ ? `## Observed project data++${data}+`+ : "";++ return refineSection.length > 0 && dataSection.length > 0+ ? `${refineSection}\n${dataSection}`+ : `${refineSection}${dataSection}`;+}diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.tsindex 3837df5a32..6df90b9bf8 100644--- a/web/src/features/search-bar/server/router.ts+++ b/web/src/features/search-bar/server/router.ts@@ -15,6 +15,7 @@ import {} from "@/src/server/api/trpc";import { TRPCError } from "@trpc/server";import {+ type ChatMessage,ChatMessageRole,ChatMessageType,LangfuseInternalTraceEnvironment,@@ -27,7 +28,10 @@ import {MAX_SCORE_NAME_LENGTH,MAX_SCORE_NAMES_PER_TYPE,} from "../lib/observed-options";-import { buildFilterSystemPrompt } from "./buildFilterPrompt";+import {+ buildFilterContextMessage,+ buildFilterSystemPrompt,+} from "./buildFilterPrompt";import { parseGeneratedFilters } from "./parseFilterCompletion";import {generateLangfuseAIText,@@ -123,8 +127,13 @@ export const searchBarRouter = createTRPCRouter({const now = new Date();const dayOfWeek = now.toLocaleDateString("en-US", { weekday: "long" });const currentDatetime = `${dayOfWeek}, ${now.toISOString()}`;- const systemPrompt = buildFilterSystemPrompt(- currentDatetime,+ const systemPrompt = buildFilterSystemPrompt(currentDatetime);+ // The current query being refined and the observed project data are+ // injected DATA, not instructions β sent as their own user message so+ // a trace shows the prompt and the data it was handed as distinct+ // messages. Omitted entirely (not sent as an empty message) when+ // there's neither.+ const contextMessage = buildFilterContextMessage(input.currentQuery,input.dataContext,);@@ -138,19 +147,32 @@ export const searchBarRouter = createTRPCRouter({});}+ // Built imperatively (rather than a conditional-spread array literal)+ // so each push is checked against `ChatMessage` individually β a+ // ternary-spread literal loses the enum-member literal types TS needs+ // to match the discriminated union.+ const messages: ChatMessage[] = [+ {+ role: ChatMessageRole.System,+ content: systemPrompt,+ type: ChatMessageType.PublicAPICreated,+ },+ ];+ if (contextMessage !== null) {+ messages.push({+ role: ChatMessageRole.User,+ content: contextMessage,+ type: ChatMessageType.PublicAPICreated,+ });+ }+ messages.push({+ role: ChatMessageRole.User,+ content: input.prompt,+ type: ChatMessageType.PublicAPICreated,+ });+const llmCompletion = await generateLangfuseAIText({- messages: [- {- role: ChatMessageRole.System,- content: systemPrompt,- type: ChatMessageType.PublicAPICreated,- },- {- role: ChatMessageRole.User,- content: input.prompt,- type: ChatMessageType.PublicAPICreated,- },- ],+ messages,model,maxTokens: 2048,traceSinkParams: aiTelemetryEnabled