Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(search-bar): dogfood the Ask AI prompt as a managed Langfuse prompt (LFE-11004) (#15305)

Nikita Kabardin51ec98e2cf7b
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5c9f2b6318..7489ac4af8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -939,6 +939,9 @@ importers:
jsdom:
specifier: ^26.1.0
version: 26.1.0
+ langfuse-core:
+ specifier: ^3.38.4
+ version: 3.38.20
node-mocks-http:
specifier: ^1.17.2
version: 1.17.2(@types/[email protected])(@types/[email protected])
diff --git a/scripts/ask-ai/sync-search-bar-filter-prompt.sh b/scripts/ask-ai/sync-search-bar-filter-prompt.sh
new file mode 100755
index 0000000000..99383198fd
--- /dev/null
+++ b/scripts/ask-ai/sync-search-bar-filter-prompt.sh
@@ -0,0 +1,119 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Pushes the repo-versioned v4 search-bar Ask AI filter prompt
+# (web/src/features/search-bar/server/prompts/search-bar-filter.prompt.json)
+# as a new version of the MANAGED chat prompt "search-bar-filter" in the
+# AI-features Langfuse project, per region. Mirrors
+# scripts/in-app-agent/sync-prompt.sh (a text prompt); this one is a chat
+# prompt, so the request body is the JSON file's contents as-is β€” it is
+# already shaped like the `POST /api/public/v2/prompts` request body
+# (name/type/prompt/labels/commitMessage).
+#
+# Intended for a human to run locally with real AI-features keys. Never run
+# by an agent, and never wired into CI.
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
+PROMPT_FILE="${REPO_ROOT}/web/src/features/search-bar/server/prompts/search-bar-filter.prompt.json"
+REGIONS=(STAGING EU US JP HIPAA)
+BASE_URLS=(
+ "https://staging.langfuse.com"
+ "https://cloud.langfuse.com"
+ "https://us.cloud.langfuse.com"
+ "https://jp.cloud.langfuse.com"
+ "https://hipaa.cloud.langfuse.com"
+)
+
+if [[ ! -f "${PROMPT_FILE}" ]]; then
+ echo "Prompt file not found: ${PROMPT_FILE}" >&2
+ exit 1
+fi
+
+if ! command -v jq >/dev/null 2>&1; then
+ echo "jq is required." >&2
+ exit 1
+fi
+
+REQUEST_BODY="$(jq -c '.' "${PROMPT_FILE}")"
+
+# The seed file's `.name` is the single source of truth for the managed
+# prompt's name β€” kept in sync with the TS constant
+# (`SEARCH_BAR_FILTER_PROMPT_NAME` in `resolveFilterPrompt.ts`) by a test,
+# not by a second literal here. A rename in one place therefore can't
+# silently desync the two and degrade every request to permanent fallback.
+PROMPT_NAME="$(jq -r '.name' <<<"${REQUEST_BODY}")"
+if [[ -z "${PROMPT_NAME}" || "${PROMPT_NAME}" == "null" ]]; then
+ echo "Prompt file must have a non-empty 'name'." >&2
+ exit 1
+fi
+if [[ "$(jq -r '.type' <<<"${REQUEST_BODY}")" != "chat" ]]; then
+ echo "Prompt file 'type' must be 'chat'." >&2
+ exit 1
+fi
+
+SYNCED_REGIONS=()
+PREFLIGHT_ERRORS=()
+
+for REGION_INDEX in "${!REGIONS[@]}"; do
+ REGION="${REGIONS[${REGION_INDEX}]}"
+ PUBLIC_KEY_VAR="LANGFUSE_AI_FEATURES_${REGION}_PUBLIC_KEY"
+ SECRET_KEY_VAR="LANGFUSE_AI_FEATURES_${REGION}_SECRET_KEY"
+ BASE_URL="${BASE_URLS[${REGION_INDEX}]}"
+
+ if [[ -z "${!PUBLIC_KEY_VAR:-}" || -z "${!SECRET_KEY_VAR:-}" ]]; then
+ PREFLIGHT_ERRORS+=("${REGION}: ${PUBLIC_KEY_VAR} and ${SECRET_KEY_VAR} must be set.")
+ continue
+ fi
+
+ echo "Checking access to ${REGION} (${BASE_URL})..."
+ STATUS_CODE="$(
+ curl --silent --show-error --output /dev/null --write-out "%{http_code}" \
+ --user "${!PUBLIC_KEY_VAR}:${!SECRET_KEY_VAR}" \
+ "${BASE_URL}/api/public/v2/prompts/${PROMPT_NAME}" || true
+ )"
+
+ if [[ "${STATUS_CODE}" != "200" && "${STATUS_CODE}" != "404" ]]; then
+ PREFLIGHT_ERRORS+=("${REGION}: expected 200 or 404 from ${BASE_URL}, got ${STATUS_CODE}.")
+ continue
+ fi
+
+ echo "Access check passed for ${REGION} (${BASE_URL})."
+done
+
+if [[ ${#PREFLIGHT_ERRORS[@]} -gt 0 ]]; then
+ echo "Preflight failed; no regions synced." >&2
+ printf ' - %s\n' "${PREFLIGHT_ERRORS[@]}" >&2
+ exit 1
+fi
+
+for REGION_INDEX in "${!REGIONS[@]}"; do
+ REGION="${REGIONS[${REGION_INDEX}]}"
+ PUBLIC_KEY_VAR="LANGFUSE_AI_FEATURES_${REGION}_PUBLIC_KEY"
+ SECRET_KEY_VAR="LANGFUSE_AI_FEATURES_${REGION}_SECRET_KEY"
+ BASE_URL="${BASE_URLS[${REGION_INDEX}]}"
+
+ read -r -p "Create or add a new version of ${PROMPT_NAME} in ${REGION} (${BASE_URL})? [y/N] " CONFIRM
+ if [[ ! "${CONFIRM}" =~ ^[Yy]([Ee][Ss])?$ ]]; then
+ echo "Skipped ${REGION}."
+ continue
+ fi
+
+ echo "Creating ${PROMPT_NAME} or adding a new version in ${REGION} (${BASE_URL})..."
+
+ curl --fail --silent --show-error \
+ --user "${!PUBLIC_KEY_VAR}:${!SECRET_KEY_VAR}" \
+ --header "Content-Type: application/json" \
+ --request POST \
+ --data "${REQUEST_BODY}" \
+ "${BASE_URL}/api/public/v2/prompts" >/dev/null
+
+ echo "Created ${PROMPT_NAME} or added a new version in ${REGION} (${BASE_URL})."
+ SYNCED_REGIONS+=("${REGION}")
+done
+
+if [[ ${#SYNCED_REGIONS[@]} -eq 0 ]]; then
+ echo "No regions synced."
+else
+ echo "Synced ${PROMPT_NAME} to regions: ${SYNCED_REGIONS[*]}."
+fi
diff --git a/web/package.json b/web/package.json
index 3613f859d9..3946658368 100644
--- a/web/package.json
+++ b/web/package.json
@@ -207,6 +207,7 @@
"eslint-plugin-storybook": "10.3.6",
"eslint-plugin-tailwindcss": "4.0.2",
"jsdom": "^26.1.0",
+ "langfuse-core": "^3.38.4",
"node-mocks-http": "^1.17.2",
"prettier": "^3.8.3",
"prettier-plugin-tailwindcss": "^0.7.2",
diff --git a/web/src/__tests__/server/unit/buildFilterPrompt.servertest.ts b/web/src/__tests__/server/unit/buildFilterPrompt.servertest.ts
new file mode 100644
index 0000000000..ec865b6adb
--- /dev/null
+++ b/web/src/__tests__/server/unit/buildFilterPrompt.servertest.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from "vitest";
+
+import { FIELDS } from "@/src/features/search-bar/lib/fields";
+import {
+ buildFieldCatalog,
+ buildFilterSystemPrompt,
+ nullableFieldIds,
+} from "@/src/features/search-bar/server/buildFilterPrompt";
+
+describe("buildFieldCatalog / nullableFieldIds", () => {
+ it("builds one catalog line per registered field", () => {
+ const catalog = buildFieldCatalog();
+ const lines = catalog.split("\n");
+ expect(lines).toHaveLength(FIELDS.length);
+ // Spot-check a well-known field renders its id and emitted type.
+ expect(catalog).toContain("- level");
+ expect(catalog).toMatch(/Emit as type "stringOptions"/);
+ });
+
+ it("lists exactly the nullable field ids, comma-joined", () => {
+ const expected = FIELDS.filter((f) => f.nullable).map((f) => f.id);
+ expect(nullableFieldIds()).toBe(expected.join(", "));
+ // Sanity: there is at least one nullable field, and a non-nullable field
+ // (e.g. "level") is not among them.
+ expect(expected.length).toBeGreaterThan(0);
+ expect(expected).not.toContain("level");
+ });
+
+ it("embeds the SAME registry-derived catalog/nullable-ids text the managed-prompt compile path uses", () => {
+ // This is the anti-drift invariant: the code fallback prompt and the
+ // managed-prompt compile variables must be built from the identical
+ // `buildFieldCatalog()` / `nullableFieldIds()` output, never a
+ // re-derivation that could diverge from the grammar.
+ const prompt = buildFilterSystemPrompt("Tuesday, 2026-07-21T12:00:00.000Z");
+ expect(prompt).toContain(buildFieldCatalog());
+ expect(prompt).toContain(`Nullable columns: ${nullableFieldIds()}.`);
+ });
+
+ it("anchors relative time expressions to the given current datetime", () => {
+ const prompt = buildFilterSystemPrompt("Tuesday, 2026-07-21T12:00:00.000Z");
+ expect(prompt).toContain(
+ "The current datetime is: Tuesday, 2026-07-21T12:00:00.000Z",
+ );
+ });
+});
diff --git a/web/src/__tests__/server/unit/resolveFilterPrompt.servertest.ts b/web/src/__tests__/server/unit/resolveFilterPrompt.servertest.ts
new file mode 100644
index 0000000000..13cff1024d
--- /dev/null
+++ b/web/src/__tests__/server/unit/resolveFilterPrompt.servertest.ts
@@ -0,0 +1,248 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/src/features/natural-language-filters/server/utils", () => ({
+ getLangfuseClient: vi.fn(),
+}));
+
+import { logger } from "@langfuse/shared/src/server";
+import { getLangfuseClient } from "@/src/features/natural-language-filters/server/utils";
+import {
+ buildFieldCatalog,
+ buildFilterSystemPrompt,
+ nullableFieldIds,
+} from "@/src/features/search-bar/server/buildFilterPrompt";
+import {
+ resolveFilterSystemPrompt,
+ SEARCH_BAR_FILTER_PROMPT_NAME,
+} from "@/src/features/search-bar/server/resolveFilterPrompt";
+
+const mockedGetLangfuseClient = vi.mocked(getLangfuseClient);
+
+const baseParams = {
+ currentDatetime: "Tuesday, 2026-07-21T12:00:00.000Z",
+ projectId: "test-project",
+};
+
+describe("resolveFilterSystemPrompt", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("falls back to the code-built prompt when AI-features keys are absent (self-hosted)", async () => {
+ const result = await resolveFilterSystemPrompt({
+ ...baseParams,
+ aiFeaturesPublicKey: undefined,
+ aiFeaturesSecretKey: undefined,
+ aiFeaturesHost: undefined,
+ });
+
+ expect(result.usedPrompt).toBeUndefined();
+ expect(result.messages).toEqual([
+ {
+ role: "system",
+ content: buildFilterSystemPrompt(baseParams.currentDatetime),
+ type: "public-api-created",
+ },
+ ]);
+ // Self-hosted is an expected, ordinary state β€” never contact the
+ // AI-features project.
+ expect(mockedGetLangfuseClient).not.toHaveBeenCalled();
+ });
+
+ it("uses the managed prompt whenever keys are present, regardless of the org's AI telemetry setting", async () => {
+ // This function no longer takes an `aiTelemetryEnabled` flag at all β€”
+ // reading our own managed prompt is a capability question (do we have
+ // keys?), not a telemetry-consent question (fetching it sends no org
+ // data anywhere). `aiTelemetryEnabled` still gates the trace WRITE and
+ // the prompt-version link, but that gate lives entirely in
+ // `router.ts`'s `traceSinkParams` ternary β€” a telemetry-off org still
+ // gets the improved prompt here, it just never gets traced or linked.
+ const compile = vi
+ .fn()
+ .mockReturnValue([
+ { role: "system", content: "compiled system message" },
+ ]);
+ const fakePromptResponse = {
+ name: SEARCH_BAR_FILTER_PROMPT_NAME,
+ version: 3,
+ compile,
+ };
+ const getPrompt = vi.fn().mockResolvedValue(fakePromptResponse);
+ mockedGetLangfuseClient.mockReturnValue({ getPrompt } as any);
+
+ const result = await resolveFilterSystemPrompt({
+ ...baseParams,
+ aiFeaturesPublicKey: "pk-test",
+ aiFeaturesSecretKey: "sk-test",
+ aiFeaturesHost: "https://example.com",
+ });
+
+ expect(mockedGetLangfuseClient).toHaveBeenCalled();
+ expect(result.usedPrompt).toBe(fakePromptResponse);
+ expect(result.messages).toEqual([
+ {
+ role: "system",
+ content: "compiled system message",
+ type: "public-api-created",
+ },
+ ]);
+ });
+
+ it("falls back to the code-built prompt (with a warn log) when the managed-prompt fetch throws", async () => {
+ const getPrompt = vi.fn().mockRejectedValue(new Error("network error"));
+ mockedGetLangfuseClient.mockReturnValue({ getPrompt } as any);
+ const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => logger);
+
+ const result = await resolveFilterSystemPrompt({
+ ...baseParams,
+ aiFeaturesPublicKey: "pk-test",
+ aiFeaturesSecretKey: "sk-test",
+ aiFeaturesHost: "https://example.com",
+ });
+
+ expect(result.usedPrompt).toBeUndefined();
+ expect(result.messages).toEqual([
+ {
+ role: "system",
+ content: buildFilterSystemPrompt(baseParams.currentDatetime),
+ type: "public-api-created",
+ },
+ ]);
+ expect(getPrompt).toHaveBeenCalledWith(
+ SEARCH_BAR_FILTER_PROMPT_NAME,
+ undefined,
+ {
+ type: "chat",
+ // Caps cold-start latency: a slow/erroring AI-features project must
+ // never stall the user's request when a fast local fallback exists.
+ fetchTimeoutMs: 2000,
+ maxRetries: 0,
+ },
+ );
+ // A broken managed prompt must be visible, not silent.
+ expect(warnSpy).toHaveBeenCalled();
+ warnSpy.mockRestore();
+ });
+
+ it("falls back to the code-built prompt (with a warn log) when the managed prompt compiles to a non-chat result", async () => {
+ // If the server ever stores a TEXT prompt under this name,
+ // `getPrompt(..., { type: "chat" })` still resolves, but `.compile()`
+ // returns a STRING (the `TextPromptClient` shape), not an array of chat
+ // messages. This must degrade to the fallback via an explicit guard, not
+ // by relying on the TypeError `.map` would otherwise throw.
+ const compile = vi.fn().mockReturnValue("a plain compiled string");
+ const fakePromptResponse = {
+ name: SEARCH_BAR_FILTER_PROMPT_NAME,
+ version: 1,
+ compile,
+ };
+ const getPrompt = vi.fn().mockResolvedValue(fakePromptResponse);
+ mockedGetLangfuseClient.mockReturnValue({ getPrompt } as any);
+ const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => logger);
+
+ const result = await resolveFilterSystemPrompt({
+ ...baseParams,
+ aiFeaturesPublicKey: "pk-test",
+ aiFeaturesSecretKey: "sk-test",
+ aiFeaturesHost: "https://example.com",
+ });
+
+ expect(result.usedPrompt).toBeUndefined();
+ expect(result.messages).toEqual([
+ {
+ role: "system",
+ content: buildFilterSystemPrompt(baseParams.currentDatetime),
+ type: "public-api-created",
+ },
+ ]);
+ expect(warnSpy).toHaveBeenCalled();
+ warnSpy.mockRestore();
+ });
+
+ // The managed prompt is edited live in the Langfuse UI, so a bad edit can
+ // compile to a well-typed-but-malformed chat result. Each of these must
+ // degrade to the code fallback (with a warn) rather than reach the model
+ // call and 500 the request.
+ it.each([
+ ["an empty message array", [] as unknown],
+ ["a message with an unsupported role", [{ role: "wizard", content: "hi" }]],
+ [
+ "a message with non-string (multimodal) content",
+ [{ role: "system", content: [{ type: "text", text: "hi" }] }],
+ ],
+ ["a null entry", [null]],
+ ])(
+ "falls back to the code-built prompt (with a warn log) when the managed prompt compiles to %s",
+ async (_label, compiled) => {
+ const compile = vi.fn().mockReturnValue(compiled);
+ const fakePromptResponse = {
+ name: SEARCH_BAR_FILTER_PROMPT_NAME,
+ version: 2,
+ compile,
+ };
+ const getPrompt = vi.fn().mockResolvedValue(fakePromptResponse);
+ mockedGetLangfuseClient.mockReturnValue({ getPrompt } as any);
+ const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => logger);
+
+ const result = await resolveFilterSystemPrompt({
+ ...baseParams,
+ aiFeaturesPublicKey: "pk-test",
+ aiFeaturesSecretKey: "sk-test",
+ aiFeaturesHost: "https://example.com",
+ });
+
+ expect(result.usedPrompt).toBeUndefined();
+ expect(result.messages).toEqual([
+ {
+ role: "system",
+ content: buildFilterSystemPrompt(baseParams.currentDatetime),
+ type: "public-api-created",
+ },
+ ]);
+ expect(warnSpy).toHaveBeenCalled();
+ warnSpy.mockRestore();
+ },
+ );
+
+ it("compiles the managed prompt with the registry-derived catalog/nullable-ids/current-datetime variables and links the prompt version", async () => {
+ const compile = vi
+ .fn()
+ .mockReturnValue([
+ { role: "system", content: "compiled system message" },
+ ]);
+ const fakePromptResponse = {
+ name: SEARCH_BAR_FILTER_PROMPT_NAME,
+ version: 3,
+ compile,
+ };
+ const getPrompt = vi.fn().mockResolvedValue(fakePromptResponse);
+ mockedGetLangfuseClient.mockReturnValue({ getPrompt } as any);
+
+ const result = await resolveFilterSystemPrompt({
+ ...baseParams,
+ aiFeaturesPublicKey: "pk-test",
+ aiFeaturesSecretKey: "sk-test",
+ aiFeaturesHost: "https://example.com",
+ });
+
+ expect(mockedGetLangfuseClient).toHaveBeenCalledWith(
+ "pk-test",
+ "sk-test",
+ "https://example.com",
+ false,
+ );
+ expect(compile).toHaveBeenCalledWith({
+ catalog: buildFieldCatalog(),
+ nullable_ids: nullableFieldIds(),
+ current_datetime: baseParams.currentDatetime,
+ });
+ expect(result.usedPrompt).toBe(fakePromptResponse);
+ expect(result.messages).toEqual([
+ {
+ role: "system",
+ content: "compiled system message",
+ type: "public-api-created",
+ },
+ ]);
+ });
+});
diff --git a/web/src/__tests__/server/unit/searchBarFilterPromptSeed.servertest.ts b/web/src/__tests__/server/unit/searchBarFilterPromptSeed.servertest.ts
new file mode 100644
index 0000000000..80db984161
--- /dev/null
+++ b/web/src/__tests__/server/unit/searchBarFilterPromptSeed.servertest.ts
@@ -0,0 +1,99 @@
+// Locks the repo-versioned managed-prompt seed
+// (`search-bar/server/prompts/search-bar-filter.prompt.json`) to the
+// code-built fallback prompt (`buildFilterSystemPrompt`).
+//
+// The seed is meant to reproduce the code prompt byte-for-byte on day one β€”
+// drift is only ever intentional going forward, once a human edits the
+// managed prompt in the Langfuse UI. This test fails loudly if the seed's
+// prose, a score-column literal, or a `{{variable}}` placeholder is changed
+// in a way that would silently desync the two, so that kind of drift is
+// caught in review rather than discovered by a customer.
+//
+// Compiles the seed with the REAL SDK class (`ChatPromptClient`) rather than
+// a hand-rolled template substitution, so the mechanism under test is the
+// one the app actually runs at request time β€” this is exactly the class
+// `getPrompt(..., { type: "chat" })` returns. Imported from `langfuse-core`
+// directly (declared as a devDependency here) rather than re-exported from
+// `langfuse`: the pinned `[email protected]` build's `.d.ts` claims to
+// re-export it, but its compiled JS does not, so `new ChatPromptClient(...)`
+// throws "not a constructor" if imported from `langfuse` at this pinned
+// version. `resolveFilterPrompt.ts` only ever imports the `ChatPromptClient`
+// TYPE from `langfuse` (erased at compile time), so production code is
+// unaffected by this gap.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { ChatPromptClient, type ChatMessage } from "langfuse-core";
+import {
+ buildFieldCatalog,
+ buildFilterSystemPrompt,
+ nullableFieldIds,
+} from "@/src/features/search-bar/server/buildFilterPrompt";
+import { SEARCH_BAR_FILTER_PROMPT_NAME } from "@/src/features/search-bar/server/resolveFilterPrompt";
+
+const SEED_PATH = join(
+ process.cwd(),
+ "src/features/search-bar/server/prompts/search-bar-filter.prompt.json",
+);
+
+function loadSeed(): {
+ name: string;
+ type: string;
+ prompt: ChatMessage[];
+ labels: string[];
+ commitMessage?: string;
+} {
+ return JSON.parse(readFileSync(SEED_PATH, "utf8"));
+}
+
+// Arbitrary but fixed, matching the format `router.ts` builds
+// (`"<Weekday>, <ISO 8601>"`) β€” the exact value doesn't matter here since it
+// is passed identically to both sides.
+const FIXED_DATETIME = "Tuesday, 2026-07-21T12:00:00.000Z";
+
+describe("search-bar-filter prompt seed", () => {
+ it("names itself the same as the code constant, so a rename in one place can't silently degrade every request to permanent fallback", () => {
+ const seed = loadSeed();
+ expect(seed.name).toBe(SEARCH_BAR_FILTER_PROMPT_NAME);
+ });
+
+ it("is a chat prompt with exactly one system message", () => {
+ const seed = loadSeed();
+ expect(seed.type).toBe("chat");
+ expect(seed.prompt).toHaveLength(1);
+ expect(seed.prompt[0].role).toBe("system");
+ });
+
+ it("compiles byte-for-byte identical to buildFilterSystemPrompt, given the same registry-derived variables", () => {
+ const seed = loadSeed();
+
+ // The same client class `getPrompt(..., { type: "chat" })` yields β€”
+ // constructed directly from the committed seed rather than fetched, but
+ // `.compile()` runs the identical mustache-render code path the app
+ // hits on every managed-prompt request.
+ const client = new ChatPromptClient({
+ ...seed,
+ type: "chat",
+ version: 1,
+ config: {},
+ tags: [],
+ });
+
+ const compiled = client.compile({
+ catalog: buildFieldCatalog(),
+ nullable_ids: nullableFieldIds(),
+ current_datetime: FIXED_DATETIME,
+ }) as ChatMessage[];
+
+ expect(compiled).toHaveLength(1);
+ const [compiledMessage] = compiled;
+ expect(compiledMessage.role).toBe("system");
+
+ const codePrompt = buildFilterSystemPrompt(FIXED_DATETIME);
+
+ expect(Buffer.byteLength(compiledMessage.content, "utf8")).toBe(
+ Buffer.byteLength(codePrompt, "utf8"),
+ );
+ expect(compiledMessage.content).toBe(codePrompt);
+ });
+});
diff --git a/web/src/features/search-bar/server/buildFilterPrompt.ts b/web/src/features/search-bar/server/buildFilterPrompt.ts
index 973f8e81a4..b1a58061b9 100644
--- a/web/src/features/search-bar/server/buildFilterPrompt.ts
+++ b/web/src/features/search-bar/server/buildFilterPrompt.ts
@@ -79,6 +79,31 @@ function fieldCatalogLine(field: FieldDef): string {
return `- ${field.id}${aliases}${unit}: ${field.description}${nullable}. Emit as type "${spec.type}", operators ${spec.operators}, value ${spec.value}.`;
}
+/**
+ * The column catalog block: one line per registry field with its id,
+ * aliases, unit, description, and the exact type/operators/value shape it
+ * lowers to. Registry-derived so it can never drift from the grammar.
+ *
+ * Shared by the code-built system prompt (`buildFilterSystemPrompt`) AND the
+ * managed-prompt compile path (`{{catalog}}` in the Langfuse-hosted prompt)
+ * β€” both must see the identical catalog text.
+ */
+export function buildFieldCatalog(): string {
+ return FIELDS.map(fieldCatalogLine).join("\n");
+}
+
+/**
+ * Comma-joined ids of the fields that support null checks (`is null` /
+ * `is not null`). Registry-derived for the same reason as `buildFieldCatalog`
+ * β€” shared verbatim by the code-built prompt and the `{{nullable_ids}}`
+ * managed-prompt variable.
+ */
+export function nullableFieldIds(): string {
+ return FIELDS.filter((f) => f.nullable)
+ .map((f) => f.id)
+ .join(", ");
+}
+
/**
* Build the STATIC system prompt: role, output format, column catalog, and
* all fixed rules/examples, anchored to `currentDatetime` (so relative time
@@ -98,10 +123,20 @@ function fieldCatalogLine(field: FieldDef): string {
* 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.
+ *
+ * This is the FALLBACK path β€” used when the managed `search-bar-filter`
+ * Langfuse prompt can't be used: self-hosted (no AI-features keys), a
+ * fetch/compile failure, or a malformed compiled prompt. It is NOT gated on AI
+ * telemetry β€” a telemetry-off org still gets the managed prompt (see
+ * `resolveFilterPrompt.ts`). Its instructional prose is intentionally allowed
+ * to drift from the
+ * managed prompt's prose over time (the managed prompt is edited live in
+ * Langfuse); only the registry-derived catalog/nullable-ids stay identical
+ * across both, via `buildFieldCatalog` / `nullableFieldIds`.
*/
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 catalog = buildFieldCatalog();
+ const nullableIds = nullableFieldIds();
return `## Role
@@ -181,7 +216,7 @@ NEVER use ${SCORE_COLUMNS.observation.numeric} / ${SCORE_COLUMNS.observation.cat
## Null checks
-For nullable columns, "has no X" / "is missing X" β†’ {"type": "null", "column": "<column>", "operator": "is null" | "is not null", "value": ""}. Nullable columns: ${nullableIds.join(", ")}.
+For nullable columns, "has no X" / "is missing X" β†’ {"type": "null", "column": "<column>", "operator": "is null" | "is not null", "value": ""}. Nullable columns: ${nullableIds}.
## Full-text / content search
diff --git a/web/src/features/search-bar/server/prompts/search-bar-filter.prompt.json b/web/src/features/search-bar/server/prompts/search-bar-filter.prompt.json
new file mode 100644
index 0000000000..f599b1c795
--- /dev/null
+++ b/web/src/features/search-bar/server/prompts/search-bar-filter.prompt.json
@@ -0,0 +1,12 @@
+{
+ "name": "search-bar-filter",
+ "type": "chat",
+ "prompt": [
+ {
+ "role": "system",
+ "content": "## Role\n\nYou are the Langfuse filter generator for the observability (v4 events) table.\nTurn a natural-language request about LLM traces/observations into a flat\nLangfuse filter array in JSON, using the FULL filter surface β€” not just simple\ncolumn matches. You can filter on:\n- catalog columns (below) with their operators,\n- custom **metadata** by key β€” BE WILLING to reach into metadata; many\n domain-specific attributes (queue, tenant, customer tier, feature flag, region,\n step, …) live in metadata, not in a top-level column,\n- evaluation **scores** by name (numeric comparisons or categorical values),\n- **content search**: substring match on the input / output payload,\n- **null checks** (has / missing), tag groups (any / all / none of), and\n **negation / exclusion**.\n\nPrefer values, metadata keys, and score names that appear in the observed\nproject data (when provided) over inventing your own β€” map the request to the\ncolumns, values, and metadata keys that ACTUALLY appear there rather than\nguessing, and don't invent a value that isn't present unless the user gave\nthat literal value themselves. Use real catalog columns for standard fields;\nfor anything custom or domain-specific, use `metadata.<key>`. Don't fall back\nto a vague column guess when metadata or content search expresses the intent\nbetter.\n\nIf the request is vague or maps to no concrete filter (e.g. \"unusual\",\n\"interesting\", \"weird\", \"anything odd\"), return [] β€” do NOT invent columns,\nscore names, thresholds, or values to satisfy it.\n\n## Output format\n\nRespond with ONLY a JSON array of filter objects β€” no prose, no markdown fences.\nEach object has \"type\", \"column\", \"operator\", \"value\" (and \"key\" for metadata\nand score filters). If the request implies no filter, return [].\n\nExample shape:\n\n[\n {\"type\": \"stringOptions\", \"column\": \"level\", \"operator\": \"any of\", \"value\": [\"ERROR\"]},\n {\"type\": \"number\", \"column\": \"latency\", \"operator\": \">\", \"value\": 2}\n]\n\n## Column catalog\n\nAlways output the canonical column id (the first name on each line), never an\nalias. Tokens are case-sensitive enums where noted.\n\n{{{catalog}}}\n\n## Levels\n\nThe \"level\" column values are one of: DEBUG, DEFAULT, WARNING, ERROR. \"errors\"\nor \"failed\" β†’ level any of [\"ERROR\"]. \"warnings\" β†’ [\"WARNING\"].\n\n## Metadata (use it boldly)\n\nCustom trace/observation metadata is addressed by key:\n{\"type\": \"stringObject\", \"column\": \"metadata\", \"key\": \"<the metadata key>\", \"operator\": \"=\" | \"contains\" | \"does not contain\" | \"starts with\" | \"ends with\", \"value\": \"<string>\"}\n\nIf the request names a domain-specific attribute that is NOT a catalog column\n(e.g. \"routing queue\", \"tenant\", \"customer tier\", \"feature flag\", \"experiment\nstep\"), filter on metadata: `{\"type\":\"stringObject\",\"column\":\"metadata\",\"key\":\"<key>\",...}`.\nWhen the observed project data lists a metadata key that matches the user's\nphrase (e.g. \"routing queue\" β†’ metadata.routing.queue), use that exact key. Use\n\"contains\" when the user gives a fuzzy/partial value, \"=\" for an exact value.\n\n## Scores (evaluation results)\n\nFilter by score NAME via the \"key\" field. The score columns\n(scores_avg / score_categories / score_booleans) are level-agnostic: they match a score\nwhether it was recorded at observation or trace level β€” always use them.\n- Numeric score: {\"type\": \"numberObject\", \"column\": \"scores_avg\", \"key\": \"<score name>\", \"operator\": \">\" | \"<\" | \">=\" | \"<=\" | \"=\", \"value\": <number>}\n- Categorical score: {\"type\": \"categoryOptions\", \"column\": \"score_categories\", \"key\": \"<score name>\", \"operator\": \"any of\" | \"none of\", \"value\": [\"<category>\"]}\n- Boolean score: {\"type\": \"booleanObject\", \"column\": \"score_booleans\", \"key\": \"<score name>\", \"operator\": \"=\" | \"<>\", \"value\": true | false}\n\nNEVER use scores_avg / score_categories / score_booleans / trace_scores_avg / trace_score_categories / trace_score_booleans as a plain column (no bare {\"type\":\"number\",\"column\":\"scores_avg\"} etc.) β€” they REQUIRE the keyed numberObject/categoryOptions/booleanObject shape above with the score name in \"key\". Only use a score name that appears in the observed data; do not invent one.\n\n## Null checks\n\nFor nullable columns, \"has no X\" / \"is missing X\" β†’ {\"type\": \"null\", \"column\": \"<column>\", \"operator\": \"is null\" | \"is not null\", \"value\": \"\"}. Nullable columns: {{{nullable_ids}}}.\n\n## Full-text / content search\n\nTo search inside the request/response payload text, use a \"string\" \"contains\"\nfilter on the \"input\" or \"output\" column (e.g. find traces whose output mentions\n\"refund\" β†’ {\"type\": \"string\", \"column\": \"output\", \"operator\": \"contains\", \"value\": \"refund\"}).\n\"mentions / talks about / says / contains X\" in a trace β†’ input and/or output\ncontains X.\n\n## Negation & exclusion\n\n- \"not X\" / \"exclude X\" / \"except X\" on an enum column (level, environment, type,\n traceTags, …) β†’ operator \"none of\": {\"type\":\"stringOptions\"|\"arrayOptions\",\"column\":...,\"operator\":\"none of\",\"value\":[...]}.\n- \"does not contain Y\" on text / metadata / input / output β†’ \"does not contain\".\n- \"without X\" / \"missing X\" / \"no X\" on a nullable column β†’ null \"is null\"; \"has X\"\n / \"with an X\" β†’ null \"is not null\".\n- Negated numbers use the inverse comparison (\"not slower than 2s\" β†’ latency <= 2).\n\n## Tag groups\n\ntraceTags is an array. \"tagged a or b\" β†’ any of [a, b]; \"tagged BOTH a and b\" β†’\n\"all of\" [a, b]; \"not tagged a\" β†’ \"none of\" [a].\n\n## Intent hints\n\n- \"slow\" / \"high latency\" β†’ latency > threshold; \"expensive\" / \"costly\" β†’ totalCost > threshold; \"token heavy\" β†’ totalTokens > threshold.\n- \"more than/over/above\" β†’ \">\"; \"less than/under/below\" β†’ \"<\"; \"at least\" β†’ \">=\"; \"at most\" β†’ \"<=\"; \"exactly\" β†’ \"=\".\n- \"tagged X\" / \"has tag X\" β†’ traceTags any of [\"X\"]. Multiple required tags β†’ \"all of\".\n- \"prod\"/\"production\" β†’ environment any of [\"production\"]; \"dev\"/\"staging\" β†’ the matching environment value.\n- \"root spans\" / \"top-level\" β†’ isRootObservation = true.\n- \"named X\" / \"called X\" β†’ the name or traceName column (NOT environment).\n\n## Refining existing filters\n\nIf there are current filters provided in the following message, the user\nALREADY has those filters applied (same syntax as your output). The new\nrequest is an EDIT to this set, not a fresh start. Rules:\n- KEEP every existing filter unless the request explicitly removes it or directly contradicts it.\n- ADD a filter for whatever the request narrows down to.\n- Only modify or drop a filter the request actually targets.\n\nA 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.\n\nWorked example β€” current filters `level:ERROR`, request \"only in production\":\nyou return BOTH filters, not just environment:\n[{\"type\":\"stringOptions\",\"column\":\"level\",\"operator\":\"any of\",\"value\":[\"ERROR\"]},{\"type\":\"stringOptions\",\"column\":\"environment\",\"operator\":\"any of\",\"value\":[\"production\"]}]\n\n## Current datetime\n\nThe current datetime is: {{{current_datetime}}}\nUse it to resolve relative time expressions against the startTime column.\n\n## Examples\n\nThese span the full surface β€” comparisons, scores, metadata, content search,\nnull checks, tag groups, and negation. Match the user's intent to the closest\ncapability; don't reduce everything to a name/type guess.\n\nInput: \"slow production traces from the last 24 hours\"\nOutput: [{\"type\":\"stringOptions\",\"column\":\"environment\",\"operator\":\"any of\",\"value\":[\"production\"]},{\"type\":\"number\",\"column\":\"latency\",\"operator\":\">\",\"value\":5},{\"type\":\"datetime\",\"column\":\"startTime\",\"operator\":\">\",\"value\":\"<24h before current datetime, ISO 8601>\"}]\n\nInput: \"errors with accuracy score below 0.8 tagged billing\"\nOutput: [{\"type\":\"stringOptions\",\"column\":\"level\",\"operator\":\"any of\",\"value\":[\"ERROR\"]},{\"type\":\"numberObject\",\"column\":\"scores_avg\",\"key\":\"accuracy\",\"operator\":\"<\",\"value\":0.8},{\"type\":\"arrayOptions\",\"column\":\"traceTags\",\"operator\":\"any of\",\"value\":[\"billing\"]}]\n\nInput: \"requests for the membership-support routing queue\"\nOutput: [{\"type\":\"stringObject\",\"column\":\"metadata\",\"key\":\"routing.queue\",\"operator\":\"=\",\"value\":\"membership-support\"}]\n\nInput: \"where the output talks about a refund and the input mentions cancel\"\nOutput: [{\"type\":\"string\",\"column\":\"output\",\"operator\":\"contains\",\"value\":\"refund\"},{\"type\":\"string\",\"column\":\"input\",\"operator\":\"contains\",\"value\":\"cancel\"}]\n\nInput: \"traces with negative sentiment\"\nOutput: [{\"type\":\"categoryOptions\",\"column\":\"score_categories\",\"key\":\"sentiment\",\"operator\":\"any of\",\"value\":[\"negative\"]}]\n\nInput: \"unfinished spans that have no end time\"\nOutput: [{\"type\":\"null\",\"column\":\"endTime\",\"operator\":\"is null\",\"value\":\"\"}]\n\nInput: \"tagged both urgent and billing, not in dev\"\nOutput: [{\"type\":\"arrayOptions\",\"column\":\"traceTags\",\"operator\":\"all of\",\"value\":[\"urgent\",\"billing\"]},{\"type\":\"stringOptions\",\"column\":\"environment\",\"operator\":\"none of\",\"value\":[\"dev\"]}]\n\nInput: \"gpt-4 generations costing more than $0.50 that aren't errors\"\nOutput: [{\"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\"]}]"
+ }
+ ],
+ "labels": ["production", "latest"],
+ "commitMessage": "Re-sync the v4 search-bar Ask AI filter prompt seed with the code fallback (LFE-11004): brings in the 'Refining existing filters' rules and the reworded Role-section preference sentence that LFE-11003 moved into buildFilterSystemPrompt."
+}
diff --git a/web/src/features/search-bar/server/resolveFilterPrompt.ts b/web/src/features/search-bar/server/resolveFilterPrompt.ts
new file mode 100644
index 0000000000..cb81c77fb6
--- /dev/null
+++ b/web/src/features/search-bar/server/resolveFilterPrompt.ts
@@ -0,0 +1,175 @@
+// Resolve the v4 search-bar Ask AI system prompt.
+//
+// Mirrors the v3 `naturalLanguageFilters.createCompletion` dogfooding
+// pattern (`../../natural-language-filters/server/router.ts`): prefer a
+// MANAGED chat prompt fetched from the AI-features Langfuse project via the
+// SAME client (`getLangfuseClient`), and fall back to the code-built
+// skeleton (`buildFilterSystemPrompt`) whenever the managed prompt is
+// unavailable β€” self-hosted (no AI-features keys configured) or the
+// fetch/compile call throws. Unlike v3 (which hard-fails when the keys are
+// missing), this endpoint must NEVER hard-fail just because the managed
+// prompt couldn't be fetched β€” self-hosted is an expected, ordinary state,
+// not an error, and even a fetch failure only degrades to the fallback (with
+// a `logger.warn`, so a broken managed prompt stays visible instead of
+// silently misbehaving).
+//
+// Gated on AI-features KEYS only β€” same as v3, and deliberately NOT on the
+// org's `aiTelemetryEnabled` setting. Fetching and compiling our OWN managed
+// prompt is a GET of our prompt; it sends no org data anywhere, so there is
+// nothing for telemetry consent to gate here. `aiTelemetryEnabled` continues
+// to gate exactly what it always has: the trace WRITE and the prompt-version
+// link, both inside `router.ts`'s `traceSinkParams`. A telemetry-off org
+// still gets the improved managed prompt; it just doesn't get traced.
+//
+// The MANAGED prompt is the source of truth for the INSTRUCTIONAL PROSE
+// (Role, output format, Levels, Metadata, Scores, Null checks, Negation, Tag
+// groups, Intent hints, Examples) β€” in cloud this is edited live in the
+// Langfuse UI. Its `{{catalog}}` / `{{nullable_ids}}` compile variables are
+// the SAME registry-derived strings the code fallback builds
+// (`buildFieldCatalog` / `nullableFieldIds` in `./buildFilterPrompt`), so the
+// model's column vocabulary can never drift from the bar grammar regardless
+// of which path served the prompt. Drift in the PROSE between the managed
+// prompt and the code fallback is intentional β€” that's the whole point of
+// making it editable β€” and must not be tested for equality.
+//
+// The repo-versioned starting point for the managed prompt lives at
+// `./prompts/search-bar-filter.prompt.json`; `scripts/ask-ai/sync-search-bar-filter-prompt.sh`
+// pushes it to each region (run manually by a human with real keys, never by
+// an agent).
+
+import {
+ type ChatMessage,
+ ChatMessageRole,
+ ChatMessageType,
+ logger,
+} from "@langfuse/shared/src/server";
+import type { ChatPromptClient } from "langfuse";
+import { getLangfuseClient } from "@/src/features/natural-language-filters/server/utils";
+import {
+ buildFieldCatalog,
+ buildFilterSystemPrompt,
+ nullableFieldIds,
+} from "./buildFilterPrompt";
+
+/** Name of the managed chat prompt in the AI-features Langfuse project. Kept
+ * in sync with the repo seed file (`./prompts/search-bar-filter.prompt.json`)
+ * and the sync script (`scripts/ask-ai/sync-search-bar-filter-prompt.sh`). */
+export const SEARCH_BAR_FILTER_PROMPT_NAME = "search-bar-filter";
+
+export type ResolvedFilterSystemPrompt = {
+ /** The system message(s) to prepend to the request. Always non-empty. */
+ messages: ChatMessage[];
+ /** Set only when the managed prompt served the request, so the caller can
+ * link the generation's trace to the exact prompt version. Omitted
+ * (undefined) when the code fallback served the request instead. */
+ usedPrompt?: ChatPromptClient;
+};
+
+function buildFallbackPrompt(
+ currentDatetime: string,
+): ResolvedFilterSystemPrompt {
+ return {
+ messages: [
+ {
+ role: ChatMessageRole.System,
+ content: buildFilterSystemPrompt(currentDatetime),
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ };
+}
+
+// The managed prompt is edited live in the Langfuse UI, so a bad edit can
+// compile to a structurally-invalid chat message: an unsupported role or
+// non-string (e.g. multimodal) content. Such a message must degrade to the
+// code fallback rather than reach `generateLangfuseAIText` and 500 the request.
+const VALID_CHAT_ROLES: ReadonlySet<string> = new Set(
+ Object.values(ChatMessageRole),
+);
+function isUsableChatMessage(message: unknown): boolean {
+ if (typeof message !== "object" || message === null) return false;
+ const { role, content } = message as { role?: unknown; content?: unknown };
+ return (
+ typeof role === "string" &&
+ VALID_CHAT_ROLES.has(role) &&
+ typeof content === "string"
+ );
+}
+
+/**
+ * Build the system-prompt message(s) for `searchBar.generateFilter`: try the
+ * managed `search-bar-filter` Langfuse prompt first, fall back to the
+ * code-built skeleton on any reason it can't be used.
+ */
+export async function resolveFilterSystemPrompt(params: {
+ currentDatetime: string;
+ projectId: string;
+ aiFeaturesPublicKey: string | undefined;
+ aiFeaturesSecretKey: string | undefined;
+ aiFeaturesHost: string | undefined;
+}): Promise<ResolvedFilterSystemPrompt> {
+ const fallback = buildFallbackPrompt(params.currentDatetime);
+
+ // Self-hosted (no keys) is an expected, ordinary state β€” the AI-features
+ // project is never contacted, so there is nothing to fetch and nothing to
+ // warn about. This is a CAPABILITY check only; whether the org has AI
+ // telemetry on is irrelevant to whether we can read our own prompt.
+ const canUseManagedPrompt =
+ Boolean(params.aiFeaturesPublicKey) && Boolean(params.aiFeaturesSecretKey);
+ if (!canUseManagedPrompt) {
+ return fallback;
+ }
+
+ try {
+ const client = getLangfuseClient(
+ params.aiFeaturesPublicKey!,
+ params.aiFeaturesSecretKey!,
+ params.aiFeaturesHost,
+ false,
+ );
+ const promptResponse = await client.getPrompt(
+ SEARCH_BAR_FILTER_PROMPT_NAME,
+ undefined,
+ // A slow or erroring AI-features project must never stall the user's
+ // request β€” a fast local fallback exists, so there is no reason to
+ // inherit the SDK's default retry/timeout budget (~15s worst case).
+ { type: "chat", fetchTimeoutMs: 2000, maxRetries: 0 },
+ );
+ const compiled = promptResponse.compile({
+ catalog: buildFieldCatalog(),
+ nullable_ids: nullableFieldIds(),
+ current_datetime: params.currentDatetime,
+ });
+ // `getPrompt` is typed to return chat messages for `{ type: "chat" }`, but
+ // that only holds if the live prompt is actually a well-formed chat prompt.
+ // A bad edit can compile to: a STRING (if stored as a text prompt), an
+ // EMPTY array, or an array with a MALFORMED message (unsupported role /
+ // non-string content). Any of these would otherwise reach
+ // `generateLangfuseAIText` and 500 the request, so validate the structure
+ // explicitly and degrade to the code fallback (staying visible via a warn).
+ if (
+ !Array.isArray(compiled) ||
+ compiled.length === 0 ||
+ !compiled.every(isUsableChatMessage)
+ ) {
+ logger.warn(
+ "Search-bar AI filter: managed prompt compiled to an empty or malformed chat result, falling back to the code-built prompt",
+ { projectId: params.projectId },
+ );
+ return fallback;
+ }
+ const messages: ChatMessage[] = compiled.map((message) => ({
+ ...(message as ChatMessage),
+ type: ChatMessageType.PublicAPICreated,
+ }));
+ return { messages, usedPrompt: promptResponse };
+ } catch (error) {
+ // A broken or unreachable managed prompt must degrade to the code
+ // fallback, never 500 the endpoint β€” but stay visible via a warn log.
+ logger.warn(
+ "Search-bar AI filter: failed to fetch the managed prompt, falling back to the code-built prompt",
+ { projectId: params.projectId, error },
+ );
+ return fallback;
+ }
+}
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
index 6df90b9bf8..de7ccb000a 100644
--- a/web/src/features/search-bar/server/router.ts
+++ b/web/src/features/search-bar/server/router.ts
@@ -1,13 +1,17 @@
// v4 search-bar AI filter endpoint.
//
// Unlike the legacy `naturalLanguageFilters.createCompletion` (whose remotely
-// managed prompt targets the OLD trace columns), this procedure builds its
-// prompt from the search-bar field registry (`buildFilterSystemPrompt`), so the
-// model's vocabulary is exactly the v4 events grammar. It then ROUND-TRIPS the
-// model output through `filterStateToQueryText` and returns only the filters
-// that lower to bar pills β€” a hallucinated/unknown column can never reach the
-// client. The frontend applies the result via the bar's existing setFilterState
-// path (apply-immediately), and the bar re-derives the editable pills.
+// managed prompt targets the OLD trace columns), this procedure's system
+// prompt is anchored to the search-bar field registry: it prefers a MANAGED
+// `search-bar-filter` Langfuse prompt compiled with registry-derived
+// variables, falling back to a fully code-built skeleton when the managed
+// prompt is unavailable (see `resolveFilterPrompt.ts`). Either way, the
+// model's column vocabulary is exactly the v4 events grammar. It then
+// ROUND-TRIPS the model output through `filterStateToQueryText` and returns
+// only the filters that lower to bar pills β€” a hallucinated/unknown column
+// can never reach the client. The frontend applies the result via the bar's
+// existing setFilterState path (apply-immediately), and the bar re-derives
+// the editable pills.
import {
createTRPCRouter,
@@ -28,10 +32,8 @@ import {
MAX_SCORE_NAME_LENGTH,
MAX_SCORE_NAMES_PER_TYPE,
} from "../lib/observed-options";
-import {
- buildFilterContextMessage,
- buildFilterSystemPrompt,
-} from "./buildFilterPrompt";
+import { buildFilterContextMessage } from "./buildFilterPrompt";
+import { resolveFilterSystemPrompt } from "./resolveFilterPrompt";
import { parseGeneratedFilters } from "./parseFilterCompletion";
import {
generateLangfuseAIText,
@@ -127,16 +129,6 @@ 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);
- // 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,
- );
const aiTelemetryEnabled = project.organization.aiTelemetryEnabled;
@@ -147,17 +139,38 @@ export const searchBarRouter = createTRPCRouter({
});
}
+ // 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
+ // managed prompt is unavailable. Never throws β€” see
+ // `resolveFilterPrompt.ts` for the fallback conditions. Gated on
+ // AI-features keys only, NOT on `aiTelemetryEnabled` β€” reading our
+ // own prompt sends no org data out, so telemetry consent has nothing
+ // to gate here; it still gates the trace write + version link below.
+ const { messages: systemMessages, usedPrompt } =
+ await resolveFilterSystemPrompt({
+ currentDatetime,
+ projectId: input.projectId,
+ aiFeaturesPublicKey: env.LANGFUSE_AI_FEATURES_PUBLIC_KEY,
+ aiFeaturesSecretKey: env.LANGFUSE_AI_FEATURES_SECRET_KEY,
+ aiFeaturesHost: env.LANGFUSE_AI_FEATURES_HOST,
+ });
+
+ // 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,
+ );
+
// 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,
- },
- ];
+ const messages: ChatMessage[] = [...systemMessages];
if (contextMessage !== null) {
messages.push({
role: ChatMessageRole.User,
@@ -205,6 +218,10 @@ export const searchBarRouter = createTRPCRouter({
langfuse_current_query: input.currentQuery?.trim() || null,
langfuse_data_context_chars: input.dataContext?.length ?? 0,
},
+ // Links the trace to the exact managed-prompt version when
+ // it served this request; omitted (undefined) when the code
+ // fallback served it instead.
+ prompt: usedPrompt,
})
: undefined,
});