Skip to content

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

feat(search-bar): move AI filter generation into the bar (Tab β†’ AI) (#14443)

Nikita Kabardinee54f20bc17b
diff --git a/.env.dev.example b/.env.dev.example
index 6926510938..5b74c7b3c8 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -184,6 +184,10 @@ AWS_ACCESS_KEY_ID="A123456789"
AWS_SECRET_ACCESS_KEY="SAK123456789"
LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY="1234567890abcdef"
LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"
+# Model for AI features (e.g. the search-bar AI filter generator). Cloud/prod uses
+# `eu.anthropic.claude-opus-4-8`. Set that here to match prod exactly. Weak/old
+# models (e.g. `eu.anthropic.claude-3-haiku-20240307-v1:0`) degrade refine quality
+# β€” they tend to ignore the existing filters and replace instead of narrowing.
LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-haiku-4-5-20251001-v1:0"
LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"
diff --git a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
new file mode 100644
index 0000000000..74f6b8788d
--- /dev/null
+++ b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it } from "vitest";
+
+import { parseGeneratedFilters } from "@/src/features/search-bar/server/parseFilterCompletion";
+
+describe("parseGeneratedFilters", () => {
+ it("parses a plain JSON array of v4 filters and derives query text", () => {
+ const completion = JSON.stringify([
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ { type: "number", column: "latency", operator: ">", value: 2 },
+ ]);
+ const { filters, queryText, droppedCount } =
+ parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(2);
+ expect(droppedCount).toBe(0);
+ expect(queryText).toContain("level");
+ expect(queryText).toContain("latency");
+ });
+
+ it("tolerates a { filters: [...] } wrapper", () => {
+ const completion = JSON.stringify({
+ filters: [
+ {
+ type: "stringOptions",
+ column: "environment",
+ operator: "any of",
+ value: ["production"],
+ },
+ ],
+ });
+ const { filters, droppedCount } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]?.column).toBe("environment");
+ expect(droppedCount).toBe(0);
+ });
+
+ it("extracts the JSON array out of surrounding prose", () => {
+ const completion = [
+ "Here are the filters you asked for:",
+ '[{"type":"number","column":"totalCost","operator":">","value":0.5}]',
+ "Hope that helps!",
+ ].join("\n");
+ const { filters } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]?.column).toBe("totalCost");
+ });
+
+ it("drops hallucinated / non-v4 columns and keeps the representable ones", () => {
+ const completion = JSON.stringify([
+ // legacy trace columns the v4 grammar can't express:
+ { type: "boolean", column: "bookmarked", operator: "=", value: true },
+ {
+ type: "datetime",
+ column: "timestamp",
+ operator: ">",
+ value: "2026-06-01T00:00:00.000Z",
+ },
+ // a valid v4 filter:
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ ]);
+ const { filters, droppedCount } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]?.column).toBe("level");
+ expect(droppedCount).toBe(2);
+ });
+
+ it("keeps metadata and score filters (representable in the grammar)", () => {
+ const completion = JSON.stringify([
+ {
+ type: "stringObject",
+ column: "metadata",
+ key: "region",
+ operator: "=",
+ value: "eu",
+ },
+ {
+ type: "numberObject",
+ column: "scores_avg",
+ key: "accuracy",
+ operator: ">",
+ value: 0.8,
+ },
+ ]);
+ const { filters, droppedCount } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(2);
+ expect(droppedCount).toBe(0);
+ });
+
+ it("drops a filter whose type is incompatible with the column's contract", () => {
+ // The model emitted a plain `number` filter on the score column (it needs
+ // `numberObject` with a key) β€” events.all 500s on this. Drop it; keep the
+ // valid sibling.
+ const completion = JSON.stringify([
+ { type: "number", column: "scores_avg", operator: ">", value: 90 },
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ ]);
+ const { filters, droppedCount } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]?.column).toBe("level");
+ expect(droppedCount).toBe(1);
+ });
+
+ it("keeps a structurally-valid filter when a sibling element is malformed", () => {
+ // Weaker models drift on shape. Here element 2 has an operator that isn't in
+ // the stringOptions enum ("equals" is not "any of"/"none of"), so it fails
+ // `singleFilter`. The whole array must NOT be discarded β€” the valid
+ // level:ERROR filter survives, and the malformed one counts as dropped.
+ const completion = JSON.stringify([
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ {
+ type: "stringOptions",
+ column: "environment",
+ operator: "equals",
+ value: "production",
+ },
+ ]);
+ const { filters, droppedCount } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]?.column).toBe("level");
+ expect(droppedCount).toBe(1);
+ });
+
+ it("returns no filters for non-JSON / refusal output", () => {
+ const { filters, queryText, droppedCount } = parseGeneratedFilters(
+ "I'm sorry, I can't help with that.",
+ );
+ expect(filters).toHaveLength(0);
+ expect(queryText).toBe("");
+ expect(droppedCount).toBe(0);
+ });
+
+ it("returns no filters for an empty array", () => {
+ const { filters, droppedCount } = parseGeneratedFilters("[]");
+ expect(filters).toHaveLength(0);
+ expect(droppedCount).toBe(0);
+ });
+});
diff --git a/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts b/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts
new file mode 100644
index 0000000000..6490bc8cb8
--- /dev/null
+++ b/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it } from "vitest";
+
+import { type FilterState } from "@langfuse/shared";
+import {
+ FIELDS,
+ SCORE_COLUMNS,
+ type FieldDef,
+} from "@/src/features/search-bar/lib/fields";
+import {
+ buildFilterSystemPrompt,
+ specForField,
+} from "@/src/features/search-bar/server/buildFilterPrompt";
+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";
+
+// A representative `singleFilter` for the FilterState `type` the prompt tells
+// the model to emit for this field. Used to assert the prompt's per-field
+// recommendation lowers back to bar grammar β€” i.e. it can't drift from the
+// reverse adapter.
+function sampleFilterFor(field: FieldDef): FilterState[number] {
+ const { type } = specForField(field);
+ switch (type) {
+ case "number":
+ return { type: "number", column: field.id, operator: ">", value: 1 };
+ case "datetime":
+ return {
+ type: "datetime",
+ column: field.id,
+ operator: ">",
+ value: new Date("2026-06-01T00:00:00.000Z"),
+ };
+ case "boolean":
+ return { type: "boolean", column: field.id, operator: "=", value: true };
+ case "stringOptions":
+ return {
+ type: "stringOptions",
+ column: field.id,
+ operator: "any of",
+ value: ["x"],
+ };
+ case "arrayOptions":
+ return {
+ type: "arrayOptions",
+ column: field.id,
+ operator: "any of",
+ value: ["x"],
+ };
+ default:
+ return {
+ type: "string",
+ column: field.id,
+ operator: "contains",
+ value: "x",
+ };
+ }
+}
+
+describe("buildFilterSystemPrompt", () => {
+ const prompt = buildFilterSystemPrompt("Monday, 2026-06-15T00:00:00.000Z");
+
+ it("lists every registry field id", () => {
+ for (const f of FIELDS) expect(prompt).toContain(f.id);
+ });
+
+ it("anchors relative time to the current datetime", () => {
+ expect(prompt).toContain("2026-06-15T00:00:00.000Z");
+ });
+
+ it("documents metadata and observation/trace score columns", () => {
+ expect(prompt).toContain("metadata");
+ expect(prompt).toContain(SCORE_COLUMNS.observation.numeric);
+ expect(prompt).toContain(SCORE_COLUMNS.observation.categorical);
+ expect(prompt).toContain(SCORE_COLUMNS.trace.numeric);
+ expect(prompt).toContain(SCORE_COLUMNS.trace.categorical);
+ });
+
+ it("omits the refine section without a current query", () => {
+ expect(prompt).not.toContain("Current filters");
+ });
+
+ it("includes the current query as refine context when provided", () => {
+ const refinePrompt = buildFilterSystemPrompt(
+ "Monday, 2026-06-15T00:00:00.000Z",
+ "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");
+ });
+});
+
+describe("prompt field specs round-trip to bar grammar", () => {
+ it.each(FIELDS.map((f) => [f.id, f] as const))(
+ "%s lowers to a representable filter (no drift vs reverse adapter)",
+ (_id, field) => {
+ const { skippedFilters } = filterStateToQueryText([
+ sampleFilterFor(field),
+ ]);
+ expect(skippedFilters).toHaveLength(0);
+ },
+ );
+});
+
+describe("metadata and score filters are representable", () => {
+ it("metadata stringObject", () => {
+ const { skippedFilters } = filterStateToQueryText([
+ {
+ type: "stringObject",
+ column: "metadata",
+ key: "region",
+ operator: "=",
+ value: "eu",
+ },
+ ]);
+ expect(skippedFilters).toHaveLength(0);
+ });
+
+ it("numeric observation score", () => {
+ const { skippedFilters } = filterStateToQueryText([
+ {
+ type: "numberObject",
+ column: SCORE_COLUMNS.observation.numeric,
+ key: "accuracy",
+ operator: ">",
+ value: 0.8,
+ },
+ ]);
+ expect(skippedFilters).toHaveLength(0);
+ });
+
+ it("categorical observation score", () => {
+ const { skippedFilters } = filterStateToQueryText([
+ {
+ type: "categoryOptions",
+ column: SCORE_COLUMNS.observation.categorical,
+ key: "sentiment",
+ operator: "any of",
+ value: ["positive"],
+ },
+ ]);
+ expect(skippedFilters).toHaveLength(0);
+ });
+});
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 8bdb106770..5c04da3103 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -104,6 +104,7 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"
import { useSearchBarEnabled } from "@/src/features/search-bar/hooks/useSearchBarEnabled";
import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";
import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";
+import { buildAiContext } from "@/src/features/search-bar/lib/ai-context";
import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";
export type EventsTableRow = {
@@ -444,19 +445,21 @@ export default function ObservationsEventsTable({
[filterOptions, isFilterOptionsPending],
);
- const { store: searchBarStore, commit: searchBarCommit } = useEventsSearchBar(
- {
- projectId,
- enabled: searchBarMode,
- filterState: queryFilter.explicitFilterState,
- searchQuery,
- searchType,
- observed: observedOptions,
- setFilterState: setFiltersWrapper,
- setSearchQuery,
- setSearchType,
- },
- );
+ const {
+ store: searchBarStore,
+ commit: searchBarCommit,
+ applyFilters: searchBarApplyFilters,
+ } = useEventsSearchBar({
+ projectId,
+ enabled: searchBarMode,
+ filterState: queryFilter.explicitFilterState,
+ searchQuery,
+ searchType,
+ observed: observedOptions,
+ setFilterState: setFiltersWrapper,
+ setSearchQuery,
+ setSearchType,
+ });
// Disabled for now because perhaps confusing
// const viewModeFilter: FilterState =
@@ -549,6 +552,27 @@ export default function ObservationsEventsTable({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [observations.status, observations.rows]);
+ // Project data context for the AI filter prompt: observed values (from
+ // filterOptions) + metadata keys sampled from the visible rows + the current
+ // result count, so the model maps NL onto real columns/values rather than
+ // guessing (e.g. `type:chat`). Reuses already-loaded data; only when the bar
+ // is active.
+ const aiDataContext = useMemo(() => {
+ if (!searchBarMode) return undefined;
+ // totalCount is only computed on "select all"; use the loaded/visible row
+ // count for the empty-vs-nonempty signal instead.
+ return buildAiContext({
+ observed: observedOptions,
+ sampleMetadata: (observations.rows ?? [])
+ .slice(0, 30)
+ .map((o) => o.metadata),
+ resultCount:
+ observations.status === "success"
+ ? (observations.rows?.length ?? 0)
+ : null,
+ });
+ }, [searchBarMode, observedOptions, observations.rows, observations.status]);
+
const { scoreColumns, isLoading: isColumnLoading } =
useScoreColumns<EventsTableRow>({
scoreColumnKey: "scores",
@@ -1496,6 +1520,8 @@ export default function ObservationsEventsTable({
store={searchBarStore}
commit={searchBarCommit}
observed={observedOptions}
+ onApplyFilters={searchBarApplyFilters}
+ aiDataContext={aiDataContext}
/>
)}
{/* Toolbar spanning full width */}
@@ -1605,7 +1631,9 @@ export default function ObservationsEventsTable({
pageSize: paginationState.limit,
pageIndex: paginationState.page - 1,
}}
- filterWithAI
+ // In bar mode AI filtering lives in the search bar ("Ask AI"),
+ // so the legacy wand is only offered when the bar is absent.
+ filterWithAI={!searchBarMode}
/>
</div>
)}
@@ -1618,7 +1646,9 @@ export default function ObservationsEventsTable({
// Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.
key={viewControllers.selectedViewId ?? "no-view"}
queryFilter={queryFilter}
- filterWithAI
+ // In bar mode AI filtering lives in the search bar; only offer the
+ // sidebar wand on non-bar surfaces (embedded scoped tables).
+ filterWithAI={!searchBarMode}
/>
)}
diff --git a/web/src/features/search-bar/AI_FILTER_PLAN.md b/web/src/features/search-bar/AI_FILTER_PLAN.md
new file mode 100644
index 0000000000..5c01fdc437
--- /dev/null
+++ b/web/src/features/search-bar/AI_FILTER_PLAN.md
@@ -0,0 +1,269 @@
+# AI Filter β€” Improvement & Dogfooding Plan (search bar, v4)
+
+What the AI filter is, what's wrong with it today, and how we'll tune it **using
+Langfuse itself** β€” prompt management, prompt versions, tracing, datasets, and
+evals.
+
+> **Scope:** the **v4** search-bar AI filter only (`searchBar.generateFilter`,
+> prompt built in `server/buildFilterPrompt.ts`). The legacy **v3**
+> natural-language filter (`naturalLanguageFilters.createCompletion`, remote
+> prompt `get-filter-conditions-from-query`) is a separate code path and is **not**
+> changed by anything here. See `README.md` β†’ "AI filter mode".
+
+## Status β€” two pieces
+
+- **Piece 1 (MVP, mergeable now).** Make the v4 AI filter genuinely usable and
+ ship it. Prod was fully broken β€” every call 500'd on a `temperature`
+ ValidationException (Opus 4.8 rejects `temperature`/`top_p`; fixed by dropping
+ them) β€” and nobody noticed, so the bar is "clearly works," not "perfectly
+ tuned." Local experiments show the prompt is **good on the prod model** (see
+ "Local prompt experiments"), and **trace-awareness** (observed values +
+ metadata keys + result count injected into the prompt) is now in the MVP, so
+ the model maps onto the project's real columns/values instead of guessing.
+ Ship it.
+- **Piece 2 (the real tuning, dogfooded on Langfuse).** Prompt management +
+ versions, enriched tracing, dataset + evals β€” the disciplined loop, and a
+ Langfuse workshop in its own right. Everything from "Why dogfood Langfuse"
+ onward is Piece 2.
+
+Note: the UX findings below were first measured on **local `claude-3-haiku`**;
+Piece 1 re-measured on the **prod model (Opus 4.8)** and most resolve there.
+
+## 1. What it is
+
+The bar's "Ask AI" mode turns a natural-language request into a `FilterState`
+applied to the v4 observations/events table:
+
+```
+prompt (+ current filters as refine context)
+ β†’ searchBar.generateFilter β†’ LLM β†’ JSON singleFilter[]
+ β†’ parseGeneratedFilters (validate + drop non-representable)
+ β†’ applied via setFilterState β†’ re-derived as editable grammar pills
+```
+
+Opt-in (org `aiFeaturesEnabled`, Cloud-only; server- and client-gated). Refine
+mode sends the current bar query text so the model updates the existing filters.
+
+## 2. What's wrong (UX session 2026-06-23)
+
+Quality is **bimodal and driven by the model** (`claude-3-haiku`), not the
+plumbing. Specific prompts are accurate; terse/refine prompts fall back to the
+prompt's few-shot example.
+
+| Sev | Finding | Repro |
+| --- | --- | --- |
+| πŸ”΄ Major | **Refine silently corrupts existing filters on terse instructions.** The model regurgitates the prompt's few-shot example and ignores both the request and the visible refine context. | From `level:ERROR` + last-hour, "only in production" β†’ `environment:production` + `latency:>5` (hallucinated) + `startTime:>24h` (wrong window); `level:ERROR` **dropped**. Reproduced with "also only errors" too. |
+| πŸ”΄ Major | **Blind to the project's data** (no knowledge of actual metadata keys / observed values). | "routing queue should be membership-support" β†’ `traceName:membership-support` (should be `metadata.routing.queue:*membership-support*`). |
+| 🟠 Mod | **Focus dropped after a generation.** `disabled={pending}` blurs the input to `<body>` and it's never refocused; after a failed/empty generation, Esc no longer cancels and you must re-click to retype. | After a failed generate, `document.activeElement === body`. |
+| 🟠 Mod | **Datetime pills are cryptic.** "last hour" renders as `startTime:>"2026-06-23T11:12:37.255Z"` (ms-precision ISO). Bar-wide rendering issue, surfaced by AI. | β€” |
+| 🟑 Minor | Refine context shows as a flat grey monospace string (truncates), not the colored pills used elsewhere. | β€” |
+| 🟑 Minor | Discoverability β€” "Ask AI" is a small muted button while the placeholder pushes the DSL; no cue that the AI produced the pills. | β€” |
+
+**Works well (keep):** specific builds are accurate ("errors in the last hour",
+"user alice slower than 10s", multi-filter); results are transparent editable
+pills; keyboard path (Tab→button→Enter, Esc, back); empty-result error is clean;
+apply is lossless (skipped filters preserved); v3/v4 isolation holds.
+
+## 2b. Local prompt experiments (Opus 4.8) β€” Piece 1 (2026-06-23)
+
+Ran the v4 prompt against the **prod model** (`eu.anthropic.claude-opus-4-8`, via
+the playground SSO profile) over a scenario set, parsed with the production
+`parseGeneratedFilters`, scored against expected filter-column sets. **12/13,
+stable across runs.**
+
+**Key finding:** the refine-leakage in Β§2 was a `claude-3-haiku` weakness β€”
+**Opus 4.8 (what prod uses) handles refine correctly** (add / remove / change,
+preserving context). Since prod runs Opus 4.8, the MVP prompt is good as-is; no
+tuning needed to ship.
+
+| Scenario | Prompt (+ refine ctx) | Expected cols | Opus 4.8 |
+| --- | --- | --- | --- |
+| build | errors in the last hour | level, startTime | βœ… |
+| build | slow traces in production | latency, environment | βœ… |
+| build | failed traces from user alice | level, userId | βœ… |
+| build | traces tagged billing | traceTags | βœ… |
+| build | accuracy score below 0.8 | scores_avg | βœ… |
+| build | output mentions refund | output | βœ… |
+| build | root observations only | isRootObservation | βœ… |
+| build | expensive gpt-4 calls over $0.5 | totalCost, providedModelName | βœ… |
+| refine (add) | `level:ERROR startTime:>…` + "also only in production" | level, startTime, environment | βœ… preserved + added |
+| refine (remove) | `latency:>2` + "drop latency, show only errors" | level | βœ… removed + added |
+| refine (change) | `environment:production` + "make it staging instead" | environment | βœ… value changed |
+| edge | gibberish | (none) | βœ… empty |
+| **gap** | routing queue is membership-support | metadata.routing.queue | ❌ guesses traceName/sessionId |
+
+The one failure was the **data-awareness gap**: the model didn't know the
+project's metadata keys (or actual `type`/name values), so it guessed a column.
+
+**RESOLVED (now in the MVP).** A "project data context" block is injected into
+the prompt β€” observed values per column + metadata keys (flattened dot-paths
+sampled from the visible rows) + the current result count β€” built on the client
+from already-loaded `filterOptions` + visible rows (`lib/ai-context.ts`), capped
+for cost. Re-validated on Opus 4.8 with that context:
+
+| Prompt | Before | After (with context) |
+| --- | --- | --- |
+| only support chat sessions | `type:chat` β†’ 0 rows | `traceName:SupportChatSession` βœ… |
+| routing queue is membership-support | `traceName:…` / `sessionId:…` | `metadata.routing.queue:membership-support` βœ… |
+| errors in the last hour (control) | βœ… | still βœ… |
+
+The scenario set above is the seed for the Piece-2 eval dataset. Remaining
+Piece-2 work: a sample of visible-row *content* (input/output) for even richer
+grounding, and the full managed-prompt + dataset/eval loop.
+
+### Full-surface capability coverage (also in the MVP)
+
+The prompt was expanded to teach the **whole** v4 grammar β€” not just simple
+column matches β€” and to be **brave with metadata**. Validated on Opus 4.8 with
+*variations* (not the verbatim examples), 7/7:
+
+| Request | Generated |
+| --- | --- |
+| filter to the acme tenant | `metadata.tenant:acme` |
+| mention 'password reset' in the response | `output:"password reset"` |
+| where the sentiment is positive | `scores.sentiment:positive` |
+| traces missing a user id | `-has:userId` |
+| exclude debug and warning levels | `-level:(DEBUG OR WARNING)` |
+| tagged with both experiment and baseline | `traceTags:(experiment AND baseline)` |
+| expensive claude calls in staging that aren't errors | `providedModelName:claude totalCost:>0.5 environment:staging -level:ERROR` |
+
+So the generator now reaches into metadata, content (input/output) search,
+numeric + categorical scores, null/has checks, tag any/all/none groups, and
+negation β€” the full surface, generalized from diverse examples.
+
+Harness: throwaway tsx that shells `aws bedrock-runtime converse --profile
+playground` per scenario (needs Bedrock creds). **Caveat:** quality is
+model-dependent β€” local `claude-3-haiku` fails the refine cases, so self-hosters
+on a weak model see worse output; the Piece-2 eval will quantify model choice.
+
+## 3. Why dogfood Langfuse for this
+
+These are LLM-quality problems. Hand-tuning the prompt by eye is guesswork and
+regresses silently (the example-leakage is exactly that). The disciplined fix is
+a **dataset + evals + versioned prompts**, measuring every change β€” which is the
+product we sell. Tuning our own AI feature on Langfuse is both the correct
+engineering loop and authentic dogfooding.
+
+## 4. Current instrumentation (baseline)
+
+- βœ… **Tracing is wired.** `searchBar.generateFilter` sends each call to the
+ AI-features Langfuse project via `traceSinkParams` (env
+ `langfuse-natural-language-filter`, traceName `search-bar-filter`,
+ `targetProjectId = LANGFUSE_AI_FEATURES_PROJECT_ID`), gated on org
+ `aiTelemetryEnabled`. `fetchLLMCompletion` records the system+user messages and
+ the raw completion.
+- ❌ **Prompt is in-code** (`buildFilterPrompt.ts`, registry-derived) β†’ no
+ versions, no deploy-free iteration, no prompt↔trace linkage, nothing to eval.
+- ❌ **No structured trace capture** of mode (build/refine), `currentQuery`,
+ parsed filters, `droppedCount`, applied-vs-empty.
+- ❌ **No dataset, no evals.**
+
+## 5. Architecture decision β€” hybrid prompt
+
+Don't choose between "registry-derived in code" and "managed in Langfuse" β€”
+**split it**:
+
+- **Managed template** (Langfuse Prompt Management, new prompt `search-bar-filter`
+ in the AI-features project, separate from v3's): the human-tunable parts β€” role,
+ output format, intent hints, **examples**, the **refine instruction** β€” with
+ variables: `{{fieldCatalog}}`, `{{currentDatetime}}`, `{{currentFilters}}`,
+ `{{observedContext}}`.
+- **Code-injected variables** (`buildFilterPrompt.ts` shrinks to a
+ `buildFilterVariables()`): the field catalog still **generated from `FIELDS`**
+ (so it can't drift from the grammar), plus the observed-context (metadata keys +
+ values) for the data-awareness fix.
+
+The endpoint fetches the prompt by label, compiles with those variables, and
+**links the prompt version to every trace** (`prompt:` in `traceSinkParams`, as
+the v3 path already does). This is the lynchpin: it makes the example and the
+refine instruction *versioned data we can A/B*, which is precisely where the
+leakage lives.
+
+## 6. The dogfood loop
+
+- **Prompt management + labels** β€” fetch by `production`; iterate on `latest`,
+ promote when evals improve. SDK caches by TTL to keep request latency low.
+- **Dataset** `search-bar-filter-evals` (AI-features project). Items:
+ `{ input: { prompt, currentQuery? }, expected_output: { queryText } }`. Seed
+ with the spread that works **plus the failures**: terse refine that must
+ preserve context, `routing queue β†’ metadata.routing.queue`, time expressions,
+ scores, multi-filter.
+- **Deterministic scorer** (no LLM judge needed β€” output is structured): parse
+ expected + actual into normalized `FilterState` (reuse
+ `parseGeneratedFilters` + `filterStateToQueryText`), then score: exact-set
+ match, filter-level precision/recall/F1, and a **`context_preserved`** flag for
+ refine items. Reuses code we already have + tested.
+- **Dataset runs** across prompt versions **and models** (haiku vs sonnet);
+ compare in the experiments UI. This is how we kill the leakage measurably:
+ change the example β†’ run β†’ watch `context_preserved` go 0β†’1 β†’ promote.
+- **Close the loop** β€” curate real failing production traces into the dataset;
+ optionally an **online implicit-feedback score**: did the user keep the AI
+ filters, or clear/edit them within a few seconds? That ranks prompt versions on
+ real usage.
+
+The data-awareness fix (#2) folds in as the `{{observedContext}}` variable, and
+the dataset lets us **prove** it helps (ablate with/without on the routing-queue
+case).
+
+## 7. TODO
+
+**Phase 0 β€” enrich tracing (small, parallelizable)**
+- [ ] Add to each trace: mode (build/refine), `currentQuery`, parsed filters,
+ `droppedCount`, applied-vs-empty; tag traces.
+- [ ] Confirm traces land in the AI-features project and are queryable by env.
+
+**Phase 1 β€” prompt β†’ Prompt Management (hybrid)**
+- [ ] Create managed prompt `search-bar-filter` (chat) in the AI-features project
+ with the variables above; seed it from the current in-code prompt.
+- [ ] Refactor `buildFilterPrompt.ts` β†’ `buildFilterVariables()` (catalog from
+ `FIELDS` + observed context).
+- [ ] `generateFilter`: fetch prompt by label, compile, link version to the trace.
+- [ ] Label-based rollout (`production`/`latest`); keep a code fallback if the
+ fetch fails.
+
+**Phase 2 β€” eval harness + baseline**
+- [ ] Build the `search-bar-filter-evals` dataset (seed cases incl. the failures).
+- [ ] Implement the deterministic scorer (reuse `parseGeneratedFilters` +
+ `filterStateToQueryText`): exact-set, F1, `context_preserved`.
+- [ ] Dataset-run script via the Langfuse SDK; record a **baseline** for the
+ current prompt+model before changing anything.
+
+**Phase 3 β€” tune with data**
+- [ ] Iterate prompt versions: de-sticky / abstract the few-shot example;
+ strengthen "preserve current filters; change only what's asked" for refine.
+- [ ] Add `{{observedContext}}` (metadata keys + observed values); ablate to prove
+ the routing-queue fix.
+- [ ] Eval model choices (haiku vs sonnet); pick on score/cost.
+- [ ] Consider a server-side guard for refine: don't drop context filters unless
+ the request clearly removes them; or surface a before→after diff so any
+ silent loss is visible.
+
+**Phase 4 β€” close the loop (ongoing)**
+- [ ] Curate failing production traces into the dataset.
+- [ ] Online implicit-feedback score (kept vs cleared/edited within N seconds).
+
+**Quick UX fixes (independent of the eval loop)**
+- [ ] Restore focus after a generation (don't leave the input blurred to body).
+- [ ] Render the refine context as read-only pills, not a flat truncated string.
+- [ ] Friendlier datetime pill rendering (bar-wide; separate workstream).
+- [ ] Discoverability polish for the "Ask AI" entry.
+
+## 8. Open decisions
+
+- **Hybrid prompt** (managed template + code-injected catalog/observed vars) β€”
+ the lynchpin; everything hangs off it.
+- **Scorer**: deterministic set-match (start here, reuses our code) vs LLM-judge
+ for "semantic intent" vs both.
+- **Model**: stay on Bedrock haiku vs move to a stronger model for this feature
+ (decide via the eval, not by feel).
+
+## 9. Key files
+
+- `server/router.ts` β€” `searchBar.generateFilter` (gating, LLM call, tracing).
+- `server/buildFilterPrompt.ts` β€” in-code prompt β†’ becomes `buildFilterVariables()`.
+- `server/parseFilterCompletion.ts` β€” `parseGeneratedFilters` (reuse in the scorer).
+- `lib/fields.ts` β€” `FIELDS` (catalog source).
+- `lib/filter-state-to-query.ts` β€” `filterStateToQueryText` (scorer normalization).
+- `components/SearchBarAiPrompt.tsx` β€” AI sub-mode UI.
+- `../natural-language-filters/server/router.ts` β€” v3 reference: already uses
+ Prompt Management + the AI-features trace sink (the model for the hybrid).
diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.md
index e8e07f92b7..ca3e033210 100644
--- a/web/src/features/search-bar/README.md
+++ b/web/src/features/search-bar/README.md
@@ -247,6 +247,46 @@ encode/decode round-trip. The flat URL contract (`FilterState` + `searchQuery`
interleave is preserved only in the recent-searches entry (`planCommit`'s
`canonical`), not in the live bar.
+## AI filter mode (the "Ask AI" button)
+
+The bar is also the home of AI-assisted filtering on v4 (it replaces the legacy
+sidebar "✨ wand" β€” `EventsTable` now passes `filterWithAI={!searchBarMode}`, so
+the wand only survives on non-bar/embedded surfaces and the v3 traces table).
+
+- **Entry.** The **"Ask AI"** affordance opens AI mode β€” a plain button placed
+ AFTER the field in DOM order, always available (build from scratch OR refine
+ existing filters). Tab is deliberately NOT a shortcut: while typing it belongs
+ to autocomplete navigation, so forward-tab just moves focus from the field
+ onto the button. `EventsSearchBarRow` owns the `'grammar' | 'ai'` mode and
+ gates availability on `isLangfuseCloud && organization.aiFeaturesEnabled` (the
+ server enforces it too). `SearchComposer` only takes an `onActivateAi` callback
+ - renders the affordance; it stays grammar-only.
+- **The component.** `components/SearchBarAiPrompt.tsx` β€” a plain NL input (not
+ the contenteditable). Enter generates; Esc or the back arrow exits (no
+ blur-to-exit β€” leaving is explicit so a stray click never loses your prompt).
+- **The endpoint.** `server/router.ts` (`searchBar.generateFilter`), NOT the
+ legacy `naturalLanguageFilters.createCompletion`. Its prompt is built from
+ THIS registry (`server/buildFilterPrompt.ts`, derived from `FIELDS` +
+ `SCORE_COLUMNS`), so the model's vocabulary IS the grammar. It asks for a flat
+ `FilterState` (an array of `singleFilter`), then **round-trips it through
+ `filterStateToQueryText` server-side and returns only the filters that lower
+ to bar pills** β€” a hallucinated/non-v4 column lands in `skippedFilters` and is
+ dropped before it reaches the client. A unit test
+ (`__tests__/server/unit/searchBarFilterPrompt.servertest.ts`) asserts every
+ field's prompt-recommended `type` round-trips, so the prompt can't drift from
+ the reverse adapter.
+- **Apply-immediately.** The result is applied via `useEventsSearchBar`'s
+ `applyFilters` (it preserves grammar-less `skippedFilters` like a commit, then
+ writes `setFilterState`), so on returning to grammar mode `resetTo` re-derives
+ the generated filters as editable pills. There is no separate AI→bar sync path.
+- **Refine clears the free-text lane.** When opened with filters present, the
+ bar's full committed text (free text rendered inline) is the refine context
+ sent to the model, which returns the COMPLETE updated `FilterState`. So
+ `applyFilters` also clears `searchQuery` and resets `searchType` to
+ `DEFAULT_SEARCH_TYPE` β€” anything the model didn't re-emit is dropped, including
+ free text the user asked to remove. Without this, a stale `searchQuery` would
+ survive and `resetTo` would re-derive the dropped text back into the bar.
+
## Extending to other views (the universality contract)
The bar is intended to become the primary filter interface for **every**
diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
index d4524e8f17..b4e2ccd3d0 100644
--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx
+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
@@ -1,11 +1,26 @@
-// Search-bar row: the query composer at full width. EventsTable owns the
-// sticky stack around this row + the toolbar so the toolbar cannot scroll under
-// the composer. Time-range + refresh controls live in the toolbar row below
-// (next to the filter toggle and views), not here. Left padding matches the
-// toolbar row below so the bar's left edge aligns with it.
+// Search-bar row: the query composer at full width, with an AI sub-mode.
+// EventsTable owns the sticky stack around this row + the toolbar so the toolbar
+// cannot scroll under the composer. Time-range + refresh controls live in the
+// toolbar row below (next to the filter toggle and views), not here. Left
+// padding matches the toolbar row below so the bar's left edge aligns with it.
+//
+// AI mode (the "Ask AI" affordance) swaps the grammar composer for a
+// natural-language prompt. The generated filters are applied
+// through `setFilterState` β€” the SAME path the facet sidebar uses β€” so the
+// composer re-derives them as editable pills when we switch back. When opened
+// with filters present, the bar's live draft is the refine context, so the
+// model updates the existing filters instead of starting from scratch β€” read
+// live from the store (not snapshotted), since the sidebar can change the
+// filters while AI mode is open.
+import * as React from "react";
+
+import { type FilterState } from "@langfuse/shared";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import { useQueryProject } from "@/src/features/projects/hooks";
import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";
import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";
+import { SearchBarAiPrompt } from "@/src/features/search-bar/components/SearchBarAiPrompt";
import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";
import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStore";
@@ -14,17 +29,52 @@ export function EventsSearchBarRow({
store,
commit,
observed,
+ onApplyFilters,
+ aiDataContext,
}: {
projectId: string;
store: SearchBarStore;
commit: () => string | null;
observed: ObservedOptions | undefined;
+ /**
+ * Applies AI-generated filters (apply-immediately); the bar re-derives them.
+ * Preserves filters the grammar can't represent (no-silent-drop contract) β€”
+ * comes from `useEventsSearchBar.applyFilters`, not a raw `setFilterState`.
+ */
+ onApplyFilters: (filters: FilterState) => void;
+ /** Project data context (observed values + metadata keys + result count) for
+ * the AI prompt β€” built by EventsTable from filterOptions + visible rows. */
+ aiDataContext?: string;
}) {
+ const [aiOpen, setAiOpen] = React.useState(false);
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const { organization } = useQueryProject();
+ // Mirror the legacy wand gate: Cloud + org-level AI features. The server
+ // enforces it too, so this only governs whether the affordance is offered.
+ const aiAvailable =
+ isLangfuseCloud && Boolean(organization?.aiFeaturesEnabled);
+
+ const activateAi = React.useCallback(() => setAiOpen(true), []);
+
return (
<div className="min-w-0 px-2 pt-2 pb-1">
- <SearchBarStoreProvider store={store} commit={commit}>
- <SearchComposer projectId={projectId} observed={observed} />
- </SearchBarStoreProvider>
+ {aiOpen && aiAvailable ? (
+ <SearchBarAiPrompt
+ projectId={projectId}
+ store={store}
+ dataContext={aiDataContext}
+ onApply={onApplyFilters}
+ onExit={() => setAiOpen(false)}
+ />
+ ) : (
+ <SearchBarStoreProvider store={store} commit={commit}>
+ <SearchComposer
+ projectId={projectId}
+ observed={observed}
+ onActivateAi={aiAvailable ? activateAi : undefined}
+ />
+ </SearchBarStoreProvider>
+ )}
</div>
);
}
diff --git a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
new file mode 100644
index 0000000000..e1a94eb81a
--- /dev/null
+++ b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
@@ -0,0 +1,245 @@
+// AI sub-mode for the search bar: a natural-language prompt that replaces the
+// grammar composer when active (entered via the "Ask AI" affordance; Esc or the
+// back arrow exits). On submit it calls `searchBar.generateFilter`, applies
+// the returned filters through the bar's normal setFilterState path
+// (apply-immediately), and exits back to the grammar composer β€” which then
+// re-derives the generated filters as editable pills.
+//
+// When opened with filters already applied, the bar's live draft is the refine
+// context: it is shown (so the user sees what's being refined) AND sent to the
+// model, which REFINES it (add / change / remove) and returns the complete
+// updated set. We read it from the store (reactively for the chip, and fresh at
+// submit time) rather than a snapshot, because the sidebar and saved-view
+// selector stay mounted next to the prompt and can change the filters while AI
+// mode is open β€” a frozen snapshot would show stale text and drop the
+// just-added filter on apply.
+
+import * as React from "react";
+import { ArrowLeft, ArrowRight, Loader2 } from "lucide-react";
+import { useStore } from "zustand";
+
+import { type FilterState } from "@langfuse/shared";
+import { KeyboardShortcut } from "@/src/components/ui/keyboard-shortcut";
+import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStore";
+import { api } from "@/src/utils/api";
+import { cn } from "@/src/utils/tailwind";
+
+export function SearchBarAiPrompt({
+ projectId,
+ store,
+ dataContext,
+ onApply,
+ onExit,
+}: {
+ projectId: string;
+ /** The bar store; its `draft` is read as the live refine context. */
+ store: SearchBarStore;
+ /** Observed values + metadata keys + result count, so the model maps to the
+ * project's real columns/values instead of guessing. */
+ dataContext?: string;
+ /** Apply generated filters via the bar's setFilterState (apply-immediately). */
+ onApply: (filters: FilterState) => void;
+ /** Leave AI mode and restore the grammar composer. */
+ onExit: () => void;
+}) {
+ const [value, setValue] = React.useState("");
+ const [error, setError] = React.useState<string | null>(null);
+ const inputRef = React.useRef<HTMLInputElement>(null);
+ // Set on unmount (e.g. Back clicked mid-generation). `mutateAsync` keeps
+ // running after unmount, so we check this before applying β€” otherwise a
+ // generation the user cancelled would silently replace their filters when it
+ // resolves a few seconds later. Reset to false in setup (NOT just the initial
+ // useRef): React StrictMode runs setup β†’ cleanup β†’ setup on mount in dev and
+ // the ref persists across that cycle, so without the reset it would stay
+ // `true` after mount and silently swallow the first (and every) generation.
+ const cancelledRef = React.useRef(false);
+ React.useEffect(() => {
+ cancelledRef.current = false;
+ return () => {
+ cancelledRef.current = true;
+ };
+ }, []);
+
+ // Reactive: the chip re-renders if the draft changes via another surface
+ // (sidebar/saved view) while AI mode is open. (`s.draft` is a stable ref until
+ // it changes, so trimming outside the selector doesn't churn renders.)
+ const refineContext = useStore(store, (s) => s.draft).trim();
+ const refining = refineContext.length > 0;
+ const placeholder = refining
+ ? "Refine your filters β€” e.g. only errors, or drop the env filter"
+ : "Describe the filters you want β€” e.g. slow production errors from today";
+
+ const generateFilter = api.searchBar.generateFilter.useMutation();
+ const pending = generateFilter.isPending;
+
+ // Refocus after every request settles. `disabled={pending}` blurs the input
+ // to <body> during the call; on a failed/empty generation (AI mode stays
+ // open) Esc and typing would otherwise be dead until you re-click. Runs on
+ // mount too (pending starts false). On success the component unmounts, so the
+ // focus is a harmless no-op.
+ React.useEffect(() => {
+ if (!pending) inputRef.current?.focus();
+ }, [pending]);
+
+ const submit = async () => {
+ const prompt = value.trim();
+ if (prompt.length === 0 || pending) return;
+ setError(null);
+ // Snapshot the committed draft at submit (mirrors how commit() always reads
+ // store.getState().draft). It serves two no-silent-drop guards: it's the
+ // refine context sent to the model, AND the baseline we re-check on resolve.
+ // The sidebar/saved-view selector stay mounted and can change the filters
+ // mid-request; the model returns the COMPLETE set based on this snapshot.
+ const refine = store.getState().draft.trim();
+ try {
+ const result = await generateFilter.mutateAsync({
+ projectId,
+ prompt,
+ currentQuery: refine.length > 0 ? refine : undefined,
+ dataContext,
+ });
+ // Cancelled mid-flight (Back clicked while generating): don't apply.
+ if (cancelledRef.current) return;
+ // Filters changed externally (e.g. a sidebar facet click) while the
+ // request was in flight: the model's COMPLETE set is now stale, so
+ // applying it would silently drop that change (it's grammar-representable,
+ // so mergeWithSkipped won't preserve it). Bail and let the user retry
+ // against the updated filters instead.
+ if (store.getState().draft.trim() !== refine) {
+ setError("Filters changed while generating β€” try again.");
+ return;
+ }
+ if (result.filters.length === 0) {
+ setError("Couldn't build filters from that β€” try rephrasing.");
+ return;
+ }
+ onApply(result.filters as FilterState);
+ onExit();
+ } catch {
+ if (cancelledRef.current) return;
+ // Never surface raw server messages: a TRPCClientError is an Error, so its
+ // message could leak internal state, and the tRPC formatter masks 500s to
+ // an unhelpful "we have been notified" string anyway. The auth/precondition
+ // cases are unreachable behind the cloud + aiFeaturesEnabled gate. Show one
+ // generic, actionable message instead.
+ setError("Couldn't reach the AI service. Please try again.");
+ }
+ };
+
+ return (
+ <div className="relative w-full">
+ <div
+ className={cn(
+ "border-input bg-background rounded-md border px-2 py-1.5",
+ "focus-within:ring-ring focus-within:ring-1",
+ error && "border-destructive focus-within:ring-destructive/40",
+ )}
+ >
+ {/* Refine context: the filters being refined are shown here AND sent to
+ the model, so what's applied is never hidden while you edit it. */}
+ {refining && (
+ <div
+ // preventDefault so clicking the shown filter keeps the input focused
+ // β€” it never drops you back to the grammar bar or loses your prompt.
+ onMouseDown={(event) => event.preventDefault()}
+ className="text-muted-foreground mb-1.5 flex min-w-0 items-center gap-1.5 pl-1 text-xs"
+ >
+ <span className="shrink-0">Refining</span>
+ <code className="bg-muted text-foreground/80 min-w-0 truncate rounded px-1.5 py-0.5 font-mono text-[11px]">
+ {refineContext}
+ </code>
+ </div>
+ )}
+ <div className="flex min-h-6 items-center gap-2">
+ {/* Back affordance (Raycast-style) β€” clearer than a static icon that
+ you're in a sub-mode you can leave. */}
+ <button
+ type="button"
+ aria-label="Back to search"
+ title="Back (Esc)"
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={onExit}
+ className="text-muted-foreground hover:text-foreground hover:bg-accent -ml-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md"
+ >
+ <ArrowLeft className="h-4 w-4" aria-hidden="true" />
+ </button>
+ <input
+ ref={inputRef}
+ type="text"
+ value={value}
+ disabled={pending}
+ placeholder={placeholder}
+ aria-label="Ask AI to build filters"
+ data-testid="search-bar-ai-input"
+ spellCheck={false}
+ autoComplete="off"
+ // @tailwindcss/forms styles `input:focus` with a blue border + a 1px
+ // ring box-shadow (the "blue box"). border-0 + focus:ring-0 drop both
+ // (it's `:focus`, not `:focus-visible`), so the only focus indicator
+ // is the container's subtle focus-within ring, matching the grammar bar.
+ className="placeholder:text-muted-foreground min-w-0 flex-1 border-0 bg-transparent text-xs leading-6 outline-none focus:ring-0 focus:outline-none disabled:opacity-60"
+ onChange={(event) => {
+ setValue(event.target.value);
+ if (error) setError(null);
+ }}
+ onKeyDown={(event) => {
+ // Don't treat Enter/Escape as submit/exit while an IME is
+ // composing (CJK/Pinyin/Kana/Hangul): there Enter commits the
+ // composed glyph and Escape cancels composition. Same guard the
+ // grammar bar uses (SearchComposer onKeyDown).
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ submit();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ onExit();
+ }
+ }}
+ // No blur-to-exit: leaving AI mode is explicit (the back button or
+ // Esc), so a stray click never drops you back to the bar or loses the
+ // prompt you typed.
+ />
+ {pending ? (
+ <span className="text-muted-foreground flex shrink-0 items-center gap-1.5 pr-1 text-xs">
+ <Loader2
+ className="h-3.5 w-3.5 animate-spin"
+ aria-hidden="true"
+ />
+ Generating…
+ </span>
+ ) : (
+ <div className="flex shrink-0 items-center gap-1.5">
+ {value.trim().length > 0 && (
+ <KeyboardShortcut title="Press Enter to generate">
+ ↡
+ </KeyboardShortcut>
+ )}
+ <KeyboardShortcut>esc</KeyboardShortcut>
+ <button
+ type="button"
+ aria-label="Generate filters"
+ title="Generate filters (Enter)"
+ data-testid="search-bar-ai-submit"
+ disabled={value.trim().length === 0}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => submit()}
+ className={cn(
+ "text-muted-foreground hover:text-foreground hover:bg-accent inline-flex h-5 w-5 items-center justify-center rounded-sm",
+ "disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent",
+ )}
+ >
+ <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ {error && (
+ <div className="text-destructive mt-1 px-1 font-sans text-xs">
+ {error}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsx
index dd121f9405..2838307fe8 100644
--- a/web/src/features/search-bar/components/SearchComposer.tsx
+++ b/web/src/features/search-bar/components/SearchComposer.tsx
@@ -16,7 +16,7 @@
import * as React from "react";
import { useShallow } from "zustand/react/shallow";
-import { AlertCircle, X } from "lucide-react";
+import { AlertCircle, WandSparkles, X } from "lucide-react";
import { Layer } from "@/src/components/ui/layer";
import { cn } from "@/src/utils/tailwind";
@@ -286,10 +286,13 @@ function useLatest<T>(value: T) {
export function SearchComposer({
projectId,
observed,
+ onActivateAi,
}: {
projectId: string;
/** Observed facet values for value suggestions; undefined = loading. */
observed: ObservedOptions | undefined;
+ /** When set, a clickable "Ask AI" button is shown to build / refine filters. */
+ onActivateAi?: () => void;
}) {
const storeApi = useSearchBarStoreApi();
const commitToFilterState = useSearchBarCommit();
@@ -1298,15 +1301,24 @@ export function SearchComposer({
// break across a wrap. Balanced padding: a small, even gutter on all
// sides (the left no longer dwarfs the inter-pill gap and top), py
// centers a single line near min-h-9 and the box grows when wrapped.
- // pr-8 keeps the top-right error icon clear of the last token.
- "border-input bg-background relative min-h-9 rounded-md border px-2 py-1.5 pr-8",
+ // Right gutter keeps the last token clear of the top-right control:
+ // the "Ask AI" button (pr-20), or the error icon (pr-8).
+ "border-input bg-background relative min-h-9 rounded-md border px-2 py-1.5",
+ onActivateAi !== undefined && !showGlobalDiagnostics
+ ? "pr-20"
+ : "pr-8",
"focus-within:ring-ring focus-within:ring-1",
showGlobalDiagnostics &&
"border-destructive focus-within:ring-destructive/40",
)}
>
{draft.length === 0 && (
- <div className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 truncate pr-8 font-mono text-xs">
+ <div
+ className={cn(
+ "text-muted-foreground pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 truncate font-mono text-xs",
+ onActivateAi !== undefined ? "pr-20" : "pr-8",
+ )}
+ >
{COMPOSER_PLACEHOLDER}
</div>
)}
@@ -1364,6 +1376,41 @@ export function SearchComposer({
scoreTypes={scoreTypes}
/>
</div>
+ {/* "Ask AI" affordance β€” a plain button, always available so filters can
+ be built from scratch OR refined. Placed AFTER the field in the DOM so
+ forward Tab moves from the field onto this button (not past the bar).
+ Deliberately NOT a Tab shortcut: while typing, Tab belongs to
+ autocomplete navigation. Hidden while the error icon occupies the
+ corner. bg-background keeps it legible; onMouseDown preventDefault so a
+ click doesn't blur the editor first. */}
+ {onActivateAi !== undefined && !showGlobalDiagnostics && (
+ <button
+ type="button"
+ data-testid="search-bar-ask-ai"
+ aria-label="Ask AI to build or refine filters"
+ title={
+ draft.trim().length === 0
+ ? "Describe filters in natural language"
+ : "Refine these filters with AI"
+ }
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onActivateAi();
+ }}
+ className={cn(
+ "absolute top-1.5 right-2 z-20 inline-flex items-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5",
+ "bg-background text-muted-foreground font-sans text-xs",
+ "hover:border-border hover:text-foreground hover:bg-accent transition-colors",
+ // Match the app's focus ring (ring-ring) instead of the browser's
+ // default blue outline, like the shared Button used elsewhere.
+ "ring-offset-background focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden",
+ )}
+ >
+ <WandSparkles className="h-3.5 w-3.5" aria-hidden="true" />
+ <span>Ask AI</span>
+ </button>
+ )}
{/* Bar-local overlay stacking ladder: token text (base) < remove-X
(z-20) < autocomplete popover (z-50). Both the X and the popover drop
BELOW the bar, staying in-flow inside the table. The error tooltip is
diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx b/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx
new file mode 100644
index 0000000000..94f68c7f61
--- /dev/null
+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx
@@ -0,0 +1,60 @@
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+import type { FilterState } from "@langfuse/shared";
+
+import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";
+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";
+
+const NEW_FILTERS: FilterState = [
+ { type: "string", column: "name", operator: "contains", value: "checkout" },
+];
+
+function setup(
+ overrides: Partial<Parameters<typeof useEventsSearchBar>[0]> = {},
+) {
+ const setFilterState = vi.fn();
+ const setSearchQuery = vi.fn();
+ const setSearchType = vi.fn();
+ const { result } = renderHook(() =>
+ useEventsSearchBar({
+ projectId: "p",
+ enabled: true,
+ filterState: [],
+ searchQuery: "refund",
+ searchType: DEFAULT_SEARCH_TYPE,
+ observed: undefined,
+ setFilterState,
+ setSearchQuery,
+ setSearchType,
+ ...overrides,
+ }),
+ );
+ return { result, setFilterState, setSearchQuery, setSearchType };
+}
+
+describe("useEventsSearchBar.applyFilters", () => {
+ it("clears the free-text lane so refine actually drops it", () => {
+ // The model gets the full bar text (with `refund` rendered inline) as
+ // refine context and returns the COMPLETE updated FilterState. Applying it
+ // must clear searchQuery, else the dropped free text re-derives back in.
+ const { result, setFilterState, setSearchQuery } = setup();
+ act(() => result.current.applyFilters(NEW_FILTERS));
+ expect(setFilterState).toHaveBeenCalledWith(NEW_FILTERS);
+ expect(setSearchQuery).toHaveBeenCalledWith(null);
+ });
+
+ it("resets a non-default searchType to the default on apply", () => {
+ const { result, setSearchType } = setup({ searchType: ["id"] });
+ act(() => result.current.applyFilters(NEW_FILTERS));
+ expect(setSearchType).toHaveBeenCalledWith(DEFAULT_SEARCH_TYPE);
+ });
+
+ it("skips the redundant searchType write when already default", () => {
+ const { result, setSearchType } = setup({
+ searchType: DEFAULT_SEARCH_TYPE,
+ });
+ act(() => result.current.applyFilters(NEW_FILTERS));
+ expect(setSearchType).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.ts b/web/src/features/search-bar/hooks/useEventsSearchBar.ts
index 8aefd11ac5..de506c4095 100644
--- a/web/src/features/search-bar/hooks/useEventsSearchBar.ts
+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.ts
@@ -17,7 +17,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { FilterState, TracingSearchType } from "@langfuse/shared";
-import { planCommit } from "@/src/features/search-bar/lib/commit";
+import {
+ DEFAULT_SEARCH_TYPE,
+ planCommit,
+} from "@/src/features/search-bar/lib/commit";
import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";
import {
type ObservedOptions,
@@ -78,7 +81,11 @@ export function useEventsSearchBar({
setFilterState: (filters: FilterState) => void;
setSearchQuery: (query: string | null) => void;
setSearchType: (type: TracingSearchType[]) => void;
-}): { store: SearchBarStore; commit: () => string | null } {
+}): {
+ store: SearchBarStore;
+ commit: () => string | null;
+ applyFilters: (filters: FilterState) => void;
+} {
// Latest observed options, read inside commit and by the store's draft
// validation so both route `scores.<name>` by the same observed score type.
const observedRef = useRef(observed);
@@ -130,6 +137,40 @@ export function useEventsSearchBar({
const searchTypeRef = useRef(searchType);
searchTypeRef.current = searchType;
+ // Re-attach the filters the grammar can't represent so neither a grammar
+ // commit nor an AI apply ever drops them (no-silent-drop contract) β€” but drop
+ // any skipped filter whose (column, key) the new set just produced, so an
+ // explicit edit replaces it instead of duplicating the column in URL state.
+ const mergeWithSkipped = useCallback((filters: FilterState): FilterState => {
+ const producedKeys = new Set(filters.map((f) => filterIdentity(f)));
+ const preserved = skippedFiltersRef.current.filter(
+ (f) => !producedKeys.has(filterIdentity(f)),
+ );
+ return preserved.length > 0 ? [...filters, ...preserved] : filters;
+ }, []);
+
+ // Apply an externally-produced filter set (the AI filter generator) the same
+ // way a commit does β€” preserving skipped filters β€” instead of a raw replace
+ // that would silently drop them. The model receives the bar's full committed
+ // text as refine context (free text rendered inline) and returns the COMPLETE
+ // updated FilterState, so applying it must write all three URL lanes like a
+ // grammar commit does: anything the model didn't re-emit is dropped, including
+ // the free text. Clearing searchQuery / resetting searchType to the default is
+ // what makes "drop the free text" actually stick β€” otherwise the stale
+ // searchQuery survives and resetTo re-derives it back into the bar.
+ const applyFilters = useCallback(
+ (filters: FilterState) => {
+ const { setFilterState, setSearchQuery, setSearchType } =
+ applyRef.current;
+ setFilterState(mergeWithSkipped(filters));
+ setSearchQuery(null);
+ if (!sameScopes(DEFAULT_SEARCH_TYPE, searchTypeRef.current)) {
+ setSearchType(DEFAULT_SEARCH_TYPE);
+ }
+ },
+ [mergeWithSkipped],
+ );
+
const commit = useCallback((): string | null => {
const result = planCommit(
store.getState().draft,
@@ -141,15 +182,8 @@ export function useEventsSearchBar({
}
const { setFilterState, setSearchQuery, setSearchType } = applyRef.current;
// Re-attach the filters the grammar can't represent so the commit never
- // drops them (no-silent-drop contract) β€” but drop any skipped filter whose
- // (column, key) the bar just produced, so an explicit bar edit replaces it
- // instead of duplicating the column in URL state.
- const producedKeys = new Set(result.filters.map((f) => filterIdentity(f)));
- const preserved = skippedFiltersRef.current.filter(
- (f) => !producedKeys.has(filterIdentity(f)),
- );
- const committedFilters =
- preserved.length > 0 ? [...result.filters, ...preserved] : result.filters;
+ // drops them (no-silent-drop contract; shared with the AI apply path).
+ const committedFilters = mergeWithSkipped(result.filters);
setFilterState(committedFilters);
setSearchQuery(result.searchQuery);
// Only write searchType when it actually changed. planCommit coerces a
@@ -174,7 +208,7 @@ export function useEventsSearchBar({
searchType: result.searchType,
}).text,
);
- }, [store, projectId]);
+ }, [store, projectId, mergeWithSkipped]);
- return { store, commit };
+ return { store, commit, applyFilters };
}
diff --git a/web/src/features/search-bar/lib/ai-context.clienttest.ts b/web/src/features/search-bar/lib/ai-context.clienttest.ts
new file mode 100644
index 0000000000..fb47d620c9
--- /dev/null
+++ b/web/src/features/search-bar/lib/ai-context.clienttest.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+
+import { buildAiContext } from "./ai-context";
+
+describe("buildAiContext", () => {
+ it("renders observed values and flattens nested metadata keys with examples", () => {
+ const ctx = buildAiContext({
+ observed: {
+ type: [{ value: "GENERATION" }, { value: "SPAN" }],
+ traceName: [{ value: "SupportChatSession" }],
+ },
+ sampleMetadata: [
+ { routing: { queue: "membership-support" }, region: "eu" },
+ ],
+ resultCount: 1234,
+ });
+ expect(ctx).toContain("type: GENERATION, SPAN");
+ expect(ctx).toContain("traceName");
+ expect(ctx).toContain("metadata.routing.queue");
+ expect(ctx).toContain("membership-support"); // example leaf value
+ expect(ctx).toContain("showing 1234 row");
+ });
+
+ it("warns when the current view is empty", () => {
+ const ctx =
+ buildAiContext({
+ observed: { level: [{ value: "ERROR" }] },
+ sampleMetadata: [],
+ resultCount: 0,
+ }) ?? "";
+ expect(ctx).toContain("no visible rows");
+ expect(ctx).toContain("too strict");
+ });
+
+ it("returns undefined when there is nothing useful", () => {
+ expect(
+ buildAiContext({
+ observed: undefined,
+ sampleMetadata: [],
+ resultCount: null,
+ }),
+ ).toBeUndefined();
+ expect(
+ buildAiContext({ observed: {}, sampleMetadata: [{}], resultCount: null }),
+ ).toBeUndefined();
+ });
+
+ it("caps the number of metadata keys", () => {
+ const big: Record<string, number> = {};
+ for (let i = 0; i < 100; i++) big[`k${i}`] = i;
+ const ctx =
+ buildAiContext({
+ observed: undefined,
+ sampleMetadata: [big],
+ resultCount: null,
+ }) ?? "";
+ const count = (ctx.match(/- metadata\./g) ?? []).length;
+ expect(count).toBeGreaterThan(0);
+ expect(count).toBeLessThanOrEqual(30);
+ });
+
+ it("ignores non-JSON metadata (plain strings/null/arrays)", () => {
+ const ctx = buildAiContext({
+ observed: undefined,
+ sampleMetadata: ["a string", null, [1, 2, 3]],
+ resultCount: null,
+ });
+ expect(ctx).toBeUndefined();
+ });
+
+ it("parses JSON-string metadata (Langfuse's row shape) with dotted keys", () => {
+ const ctx =
+ buildAiContext({
+ observed: undefined,
+ sampleMetadata: [
+ '{"routing.queue":"membership-support","customer.plan":"free","flags.beta":true}',
+ ],
+ resultCount: null,
+ }) ?? "";
+ expect(ctx).toContain("metadata.routing.queue");
+ expect(ctx).toContain("membership-support");
+ expect(ctx).toContain("metadata.customer.plan");
+ });
+
+ it("caps observed value length and total context size", () => {
+ const ctx =
+ buildAiContext({
+ observed: {
+ traceName: [{ value: "x".repeat(200) }],
+ environment: Array.from({ length: 60 }, (_, i) => ({
+ value: `env-${i}-${"y".repeat(120)}`,
+ })),
+ },
+ sampleMetadata: [],
+ resultCount: null,
+ }) ?? "";
+ // individual values truncated to MAX_VALUE_LEN (40)
+ expect(ctx).not.toContain("x".repeat(41));
+ // total stays under the endpoint's 16k input cap
+ expect(ctx.length).toBeLessThanOrEqual(12000);
+ });
+});
diff --git a/web/src/features/search-bar/lib/ai-context.ts b/web/src/features/search-bar/lib/ai-context.ts
new file mode 100644
index 0000000000..bccddba70f
--- /dev/null
+++ b/web/src/features/search-bar/lib/ai-context.ts
@@ -0,0 +1,131 @@
+// Builds the "project data context" block injected into the v4 AI-filter prompt
+// so the model maps natural language onto the project's ACTUAL columns, values,
+// and metadata keys β€” instead of guessing (e.g. `type:chat` or
+// `traceName:membership-support`). Reuses data already loaded for the bar:
+// observed filter values (from `filterOptions`) + metadata keys sampled from the
+// currently visible rows + the current result count (empty-state awareness).
+//
+// Everything is capped so the added context stays small (window/cost).
+
+import type { ObservedOptions } from "./observed-options";
+
+// Columns whose observed values help map a phrase to the right column/value.
+// High-cardinality ids (userId/sessionId/id) are excluded β€” too many to list and
+// the user types those verbatim anyway.
+const VALUE_COLUMNS: Array<{ col: string; label: string }> = [
+ { col: "type", label: "type" },
+ { col: "level", label: "level" },
+ { col: "environment", label: "environment" },
+ { col: "traceName", label: "traceName" },
+ { col: "name", label: "name" },
+ { col: "traceTags", label: "traceTags (tags)" },
+ { col: "providedModelName", label: "providedModelName (model)" },
+ { col: "promptName", label: "promptName" },
+ { col: "scores_avg", label: "scores.<name> (numeric)" },
+ { col: "score_categories", label: "scores.<name> (categorical)" },
+ { col: "trace_scores_avg", label: "traceScores.<name> (numeric)" },
+ { col: "trace_score_categories", label: "traceScores.<name> (categorical)" },
+];
+
+const MAX_VALUES_PER_COL = 25;
+const MAX_METADATA_KEYS = 30;
+const MAX_VALUE_LEN = 40;
+// Stay well under the endpoint's `dataContext: z.string().max(16000)` cap.
+const MAX_CONTEXT_CHARS = 12000;
+
+function safeJsonParse(s: string): unknown {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return undefined;
+ }
+}
+
+/** Flatten nested metadata into dot-path keys with one example leaf value. */
+function collectMetadataKeys(
+ md: unknown,
+ prefix: string,
+ out: Map<string, string>,
+ depth: number,
+): void {
+ if (depth > 3 || out.size >= MAX_METADATA_KEYS) return;
+ if (md === null || typeof md !== "object" || Array.isArray(md)) return;
+ for (const [k, v] of Object.entries(md as Record<string, unknown>)) {
+ if (out.size >= MAX_METADATA_KEYS) break;
+ const path = prefix ? `${prefix}.${k}` : k;
+ if (v !== null && typeof v === "object" && !Array.isArray(v)) {
+ collectMetadataKeys(v, path, out, depth + 1);
+ } else if (!out.has(path)) {
+ const example =
+ v === null || v === undefined || Array.isArray(v)
+ ? ""
+ : String(v).slice(0, MAX_VALUE_LEN);
+ out.set(path, example);
+ }
+ }
+}
+
+export function buildAiContext(args: {
+ observed: ObservedOptions | undefined;
+ /** Metadata objects from the currently visible rows (sampled by the caller). */
+ sampleMetadata: unknown[];
+ /** Number of currently-loaded/visible rows (so the model can warn when 0). */
+ resultCount: number | null;
+}): string | undefined {
+ const { observed, sampleMetadata, resultCount } = args;
+ const sections: string[] = [];
+
+ if (observed) {
+ const valueLines: string[] = [];
+ for (const { col, label } of VALUE_COLUMNS) {
+ const vals = (observed[col] ?? [])
+ .map((o) => o.value)
+ .filter((v) => v.length > 0)
+ .slice(0, MAX_VALUES_PER_COL)
+ .map((v) => v.slice(0, MAX_VALUE_LEN));
+ if (vals.length > 0) valueLines.push(`- ${label}: ${vals.join(", ")}`);
+ }
+ if (valueLines.length > 0) {
+ sections.push(
+ [
+ "Observed values per column (use these exact values; lists may be truncated):",
+ ...valueLines,
+ ].join("\n"),
+ );
+ }
+ }
+
+ const mdKeys = new Map<string, string>();
+ for (const md of sampleMetadata) {
+ // Langfuse returns row metadata as a JSON-encoded string; parse it first.
+ const parsed = typeof md === "string" ? safeJsonParse(md) : md;
+ collectMetadataKeys(parsed, "", mdKeys, 0);
+ if (mdKeys.size >= MAX_METADATA_KEYS) break;
+ }
+ if (mdKeys.size > 0) {
+ const keyLines = [...mdKeys.entries()].map(
+ ([k, ex]) => `- metadata.${k}${ex ? ` (e.g. "${ex}")` : ""}`,
+ );
+ sections.push(
+ [
+ "Observed metadata keys (filter as metadata.<key>; match the user's phrase to one of these):",
+ ...keyLines,
+ ].join("\n"),
+ );
+ }
+
+ if (resultCount !== null) {
+ sections.push(
+ resultCount === 0
+ ? "The current filters match no visible rows β€” they may be too strict; consider broadening."
+ : `The current view is showing ${resultCount} row(s).`,
+ );
+ }
+
+ if (sections.length === 0) return undefined;
+ // Hard cap so the context can never exceed the endpoint's input limit
+ // (router `dataContext: z.string().max(16000)`) and trigger a Zod 400, even
+ // with many columns/keys. Per-value/per-key caps above keep us well under this.
+ const out = sections.join("\n\n");
+ return out.length > MAX_CONTEXT_CHARS ? out.slice(0, MAX_CONTEXT_CHARS) : out;
+}
diff --git a/web/src/features/search-bar/server/buildFilterPrompt.ts b/web/src/features/search-bar/server/buildFilterPrompt.ts
new file mode 100644
index 0000000000..a27f2ab7f4
--- /dev/null
+++ b/web/src/features/search-bar/server/buildFilterPrompt.ts
@@ -0,0 +1,261 @@
+// Registry-derived system prompt for the v4 search-bar AI filter generator.
+//
+// v4 ONLY. This prompt is consumed solely by `searchBar.generateFilter`. The v3
+// natural-language filter (`naturalLanguageFilters.createCompletion`) uses a
+// SEPARATE, remotely-managed prompt (`get-filter-conditions-from-query`) and is
+// unaffected by changes here β€” keep the two prompts separate.
+//
+// The prompt is generated from the SAME field registry the grammar, validator,
+// and reverse adapter use (`../lib/fields`), so the model's entire vocabulary IS
+// the bar grammar β€” it can only be told to emit columns/operators the bar can
+// render as pills. This is why a v4-native endpoint beats the legacy
+// trace-column prompt: there is no separate column list to drift out of sync.
+//
+// The model is asked for a flat Langfuse `FilterState` (an array of
+// `singleFilter` objects). Each field's allowed `type`/operators/value shape is
+// DERIVED from its `kind`/`syncMode` here, mirroring `lowerSingle` in
+// `../lib/filter-state-to-query.ts` (the reverse direction), so the two cannot
+// diverge.
+
+import { FIELDS, SCORE_COLUMNS, type FieldDef } from "../lib/fields";
+
+/** The flat-FilterState `type`, operators, and value shape a field lowers to. */
+type FilterSpec = {
+ type: string;
+ operators: string;
+ value: string;
+};
+
+export function specForField(field: FieldDef): FilterSpec {
+ switch (field.kind) {
+ case "number":
+ return {
+ type: "number",
+ operators: `"=", ">", "<", ">=", "<="`,
+ value: "a number (not a string)",
+ };
+ case "datetime":
+ return {
+ type: "datetime",
+ operators: `">", "<", ">=", "<="`,
+ value: "an ISO 8601 datetime string",
+ };
+ case "boolean":
+ return {
+ type: "boolean",
+ operators: `"=", "<>"`,
+ value: "true or false (a JSON boolean)",
+ };
+ case "text":
+ if (field.syncMode === "exactOption") {
+ return {
+ type: "stringOptions",
+ operators: `"any of", "none of"`,
+ value: "an array of strings",
+ };
+ }
+ if (field.syncMode === "arrayOption") {
+ return {
+ type: "arrayOptions",
+ operators: `"any of", "none of", "all of"`,
+ value: "an array of strings",
+ };
+ }
+ // textSearch β€” substring / exact match on a free-text column.
+ return {
+ type: "string",
+ operators: `"=", "contains", "does not contain", "starts with", "ends with"`,
+ value: "a single string",
+ };
+ }
+}
+
+function fieldCatalogLine(field: FieldDef): string {
+ const spec = specForField(field);
+ const aliases =
+ field.aliases.length > 0 ? ` [aliases: ${field.aliases.join(", ")}]` : "";
+ const unit = field.unit ? ` (unit: ${field.unit})` : "";
+ const nullable = field.nullable ? " β€” nullable, supports null checks" : "";
+ return `- ${field.id}${aliases}${unit}: ${field.description}${nullable}. Emit as type "${spec.type}", operators ${spec.operators}, value ${spec.value}.`;
+}
+
+/**
+ * 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.
+ */
+export function buildFilterSystemPrompt(
+ currentDatetime: string,
+ currentQuery?: string,
+ dataContext?: 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
+
+You are the Langfuse filter generator for the observability (v4 events) table.
+Turn a natural-language request about LLM traces/observations into a flat
+Langfuse filter array in JSON, using the FULL filter surface β€” not just simple
+column matches. You can filter on:
+- catalog columns (below) with their operators,
+- custom **metadata** by key β€” BE WILLING to reach into metadata; many
+ domain-specific attributes (queue, tenant, customer tier, feature flag, region,
+ step, …) live in metadata, not in a top-level column,
+- evaluation **scores** by name (numeric comparisons or categorical values),
+- **content search**: substring match on the input / output payload,
+- **null checks** (has / missing), tag groups (any / all / none of), and
+ **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.
+
+If the request is vague or maps to no concrete filter (e.g. "unusual",
+"interesting", "weird", "anything odd"), return [] β€” do NOT invent columns,
+score names, thresholds, or values to satisfy it.
+
+## Output format
+
+Respond with ONLY a JSON array of filter objects β€” no prose, no markdown fences.
+Each object has "type", "column", "operator", "value" (and "key" for metadata
+and score filters). If the request implies no filter, return [].
+
+Example shape:
+
+[
+ {"type": "stringOptions", "column": "level", "operator": "any of", "value": ["ERROR"]},
+ {"type": "number", "column": "latency", "operator": ">", "value": 2}
+]
+
+## Column catalog
+
+Always output the canonical column id (the first name on each line), never an
+alias. Tokens are case-sensitive enums where noted.
+
+${catalog}
+
+## Levels
+
+The "level" column values are one of: DEBUG, DEFAULT, WARNING, ERROR. "errors"
+or "failed" β†’ level any of ["ERROR"]. "warnings" β†’ ["WARNING"].
+
+## Metadata (use it boldly)
+
+Custom trace/observation metadata is addressed by key:
+{"type": "stringObject", "column": "metadata", "key": "<the metadata key>", "operator": "=" | "contains" | "does not contain" | "starts with" | "ends with", "value": "<string>"}
+
+If the request names a domain-specific attribute that is NOT a catalog column
+(e.g. "routing queue", "tenant", "customer tier", "feature flag", "experiment
+step"), filter on metadata: \`{"type":"stringObject","column":"metadata","key":"<key>",...}\`.
+When the observed project data lists a metadata key that matches the user's
+phrase (e.g. "routing queue" β†’ metadata.routing.queue), use that exact key. Use
+"contains" when the user gives a fuzzy/partial value, "=" for an exact value.
+
+## Scores (evaluation results)
+
+Filter by score NAME via the "key" field. Default to OBSERVATION-level scores
+unless the request clearly means trace-level scores.
+- Numeric score: {"type": "numberObject", "column": "${SCORE_COLUMNS.observation.numeric}" (observation) or "${SCORE_COLUMNS.trace.numeric}" (trace), "key": "<score name>", "operator": ">" | "<" | ">=" | "<=" | "=", "value": <number>}
+- Categorical score: {"type": "categoryOptions", "column": "${SCORE_COLUMNS.observation.categorical}" (observation) or "${SCORE_COLUMNS.trace.categorical}" (trace), "key": "<score name>", "operator": "any of" | "none of", "value": ["<category>"]}
+
+NEVER use ${SCORE_COLUMNS.observation.numeric} / ${SCORE_COLUMNS.observation.categorical} / ${SCORE_COLUMNS.trace.numeric} / ${SCORE_COLUMNS.trace.categorical} as a plain column (no bare {"type":"number","column":"${SCORE_COLUMNS.observation.numeric}"} etc.) β€” they REQUIRE the keyed numberObject/categoryOptions shape above with the score name in "key". Only use a score name that appears in the observed data; do not invent one.
+
+## 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(", ")}.
+
+## Full-text / content search
+
+To search inside the request/response payload text, use a "string" "contains"
+filter on the "input" or "output" column (e.g. find traces whose output mentions
+"refund" β†’ {"type": "string", "column": "output", "operator": "contains", "value": "refund"}).
+"mentions / talks about / says / contains X" in a trace β†’ input and/or output
+contains X.
+
+## Negation & exclusion
+
+- "not X" / "exclude X" / "except X" on an enum column (level, environment, type,
+ traceTags, …) β†’ operator "none of": {"type":"stringOptions"|"arrayOptions","column":...,"operator":"none of","value":[...]}.
+- "does not contain Y" on text / metadata / input / output β†’ "does not contain".
+- "without X" / "missing X" / "no X" on a nullable column β†’ null "is null"; "has X"
+ / "with an X" β†’ null "is not null".
+- Negated numbers use the inverse comparison ("not slower than 2s" β†’ latency <= 2).
+
+## Tag groups
+
+traceTags is an array. "tagged a or b" β†’ any of [a, b]; "tagged BOTH a and b" β†’
+"all of" [a, b]; "not tagged a" β†’ "none of" [a].
+
+## Intent hints
+
+- "slow" / "high latency" β†’ latency > threshold; "expensive" / "costly" β†’ totalCost > threshold; "token heavy" β†’ totalTokens > threshold.
+- "more than/over/above" β†’ ">"; "less than/under/below" β†’ "<"; "at least" β†’ ">="; "at most" β†’ "<="; "exactly" β†’ "=".
+- "tagged X" / "has tag X" β†’ traceTags any of ["X"]. Multiple required tags β†’ "all of".
+- "prod"/"production" β†’ environment any of ["production"]; "dev"/"staging" β†’ the matching environment value.
+- "root spans" / "top-level" β†’ isRootObservation = true.
+- "named X" / "called X" β†’ the name or traceName column (NOT environment).
+
+## Current datetime
+
+The current datetime is: ${currentDatetime}
+Use it to resolve relative time expressions against the startTime column.
+${refineSection}${dataSection}
+## Examples
+
+These span the full surface β€” comparisons, scores, metadata, content search,
+null checks, tag groups, and negation. Match the user's intent to the closest
+capability; don't reduce everything to a name/type guess.
+
+Input: "slow production traces from the last 24 hours"
+Output: [{"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>"}]
+
+Input: "errors with accuracy score below 0.8 tagged billing"
+Output: [{"type":"stringOptions","column":"level","operator":"any of","value":["ERROR"]},{"type":"numberObject","column":"${SCORE_COLUMNS.observation.numeric}","key":"accuracy","operator":"<","value":0.8},{"type":"arrayOptions","column":"traceTags","operator":"any of","value":["billing"]}]
+
+Input: "requests for the membership-support routing queue"
+Output: [{"type":"stringObject","column":"metadata","key":"routing.queue","operator":"=","value":"membership-support"}]
+
+Input: "where the output talks about a refund and the input mentions cancel"
+Output: [{"type":"string","column":"output","operator":"contains","value":"refund"},{"type":"string","column":"input","operator":"contains","value":"cancel"}]
+
+Input: "traces with negative sentiment"
+Output: [{"type":"categoryOptions","column":"${SCORE_COLUMNS.observation.categorical}","key":"sentiment","operator":"any of","value":["negative"]}]
+
+Input: "unfinished spans that have no end time"
+Output: [{"type":"null","column":"endTime","operator":"is null","value":""}]
+
+Input: "tagged both urgent and billing, not in dev"
+Output: [{"type":"arrayOptions","column":"traceTags","operator":"all of","value":["urgent","billing"]},{"type":"stringOptions","column":"environment","operator":"none of","value":["dev"]}]
+
+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"]}]`;
+}
diff --git a/web/src/features/search-bar/server/parseFilterCompletion.ts b/web/src/features/search-bar/server/parseFilterCompletion.ts
new file mode 100644
index 0000000000..4c12fd0a6b
--- /dev/null
+++ b/web/src/features/search-bar/server/parseFilterCompletion.ts
@@ -0,0 +1,123 @@
+// Pure post-processing for the v4 AI filter endpoint: turn a raw LLM completion
+// string into the `FilterState` the bar can apply. Kept separate from the tRPC
+// procedure (which owns auth, gating, telemetry, and the LLM call) so this β€” the
+// part with real branching logic β€” is unit-testable without a live model. This
+// mirrors the search-bar feature's own lib/ (pure) vs I/O split.
+
+import {
+ eventsTableCols,
+ type FilterState,
+ singleFilter,
+} from "@langfuse/shared";
+
+import { filterStateToQueryText } from "../lib/filter-state-to-query";
+
+// Mirrors COMPATIBLE_FILTER_TYPES in
+// packages/shared/src/server/queries/clickhouse-sql/filterTypeCompatibility.ts β€”
+// the column-type β†’ allowed-filter-type map that `events.all` enforces (and
+// 500s on mismatch, e.g. a plain `number` filter on the `scores_avg`
+// numberObject column). Kept local so this stays free of the heavy server barrel.
+const COMPATIBLE_FILTER_TYPES: Record<string, readonly string[]> = {
+ string: ["string", "stringOptions"],
+ stringOptions: ["string", "stringOptions"],
+ arrayOptions: ["arrayOptions", "stringOptions"],
+ datetime: ["datetime"],
+ number: ["number"],
+ boolean: ["boolean"],
+ stringObject: ["stringObject"],
+ numberObject: ["numberObject"],
+ categoryOptions: ["categoryOptions", "stringOptions"],
+};
+
+/**
+ * Guardrail: a filter whose type is incompatible with its column's contract
+ * (e.g. `{type:"number", column:"scores_avg"}` β€” scores need `numberObject`
+ * with a key) renders to text but is rejected by `events.all` with a 500. Drop
+ * those. Unknown columns return true here and are dropped by the reverse-adapter
+ * round-trip instead.
+ */
+function isEventsContractCompatible(f: FilterState[number]): boolean {
+ if (f.type === "null" || f.type === "positionInTrace") return true;
+ const col = f.column.toLowerCase();
+ const def = eventsTableCols.find(
+ (c) => c.id.toLowerCase() === col || c.name.toLowerCase() === col,
+ );
+ if (!def) return true;
+ const allowed = COMPATIBLE_FILTER_TYPES[def.type];
+ return allowed === undefined || allowed.includes(f.type);
+}
+
+/**
+ * Extract a `FilterState` from the model's completion. Tries the whole string,
+ * then the widest bracketed array (greedy, so it survives nested objects), and
+ * tolerates a `{ "filters": [...] }` wrapper. Returns the structurally-valid
+ * filters plus `rawCount` (how many elements the model actually emitted), so
+ * the caller can count the malformed ones as dropped. `rawCount` is 0 when
+ * nothing parses.
+ */
+function parseFilterArray(completion: string): {
+ filters: FilterState;
+ rawCount: number;
+} {
+ const arrayMatch = completion.match(/\[[\s\S]*\]/)?.[0];
+ const candidates = [completion, arrayMatch].filter((c): c is string =>
+ Boolean(c),
+ );
+ for (const candidate of candidates) {
+ try {
+ const parsed = JSON.parse(candidate);
+ const raw = Array.isArray(parsed) ? parsed : parsed.filters;
+ if (!Array.isArray(raw)) continue;
+ // Parse PER ELEMENT, not the whole array: `z.array(singleFilter).parse`
+ // is all-or-nothing, so one off-spec element (wrong operator, missing
+ // key, value-as-string, unknown type β€” common on weaker models) would
+ // discard the valid siblings and surface a misleading "couldn't build
+ // filters". Keep the structurally-valid ones; the rejects show up in the
+ // dropped count below, mirroring the per-element keep/drop the two
+ // downstream guardrails already use.
+ const kept: FilterState = [];
+ for (const item of raw) {
+ const result = singleFilter.safeParse(item);
+ if (result.success) kept.push(result.data);
+ }
+ return { filters: kept, rawCount: raw.length };
+ } catch {
+ // try the next candidate
+ }
+ }
+ return { filters: [], rawCount: 0 };
+}
+
+export type GeneratedFilters = {
+ /** Filters that round-trip to bar grammar β€” safe to apply and show as pills. */
+ filters: FilterState;
+ /** The derived bar query text (for display / telemetry). */
+ queryText: string;
+ /** How many model filters were dropped β€” malformed shape, hallucinated, or
+ * non-v4 columns (i.e. emitted by the model but not applied). */
+ droppedCount: number;
+};
+
+/**
+ * Parse the model completion and keep only the filters that round-trip to bar
+ * grammar. A hallucinated or non-v4 column lands in `skippedFilters` and is
+ * dropped here, so a caller can never apply a filter the bar can't show as an
+ * editable pill.
+ */
+export function parseGeneratedFilters(completion: string): GeneratedFilters {
+ // `rawCount` is what the model emitted; `parsed` already excludes elements
+ // that failed `singleFilter`, so the drop count is measured against rawCount.
+ const { filters: parsed, rawCount } = parseFilterArray(completion);
+ // Guardrail 1: drop filters whose type the events contract would reject.
+ const compatible = parsed.filter(isEventsContractCompatible);
+ // Guardrail 2: drop anything that doesn't round-trip to bar grammar (unknown /
+ // non-representable columns land in skippedFilters).
+ const { text, skippedFilters } = filterStateToQueryText(compatible);
+ const skipped = new Set(skippedFilters);
+ const filters = compatible.filter((f) => !skipped.has(f));
+ return {
+ filters,
+ queryText: text,
+ droppedCount: rawCount - filters.length,
+ };
+}
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
new file mode 100644
index 0000000000..901c170772
--- /dev/null
+++ b/web/src/features/search-bar/server/router.ts
@@ -0,0 +1,210 @@
+// 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.
+
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { TRPCError } from "@trpc/server";
+import {
+ ChatMessageRole,
+ ChatMessageType,
+ fetchLLMCompletion,
+ LangfuseInternalTraceEnvironment,
+ LLMAdapter,
+ logger,
+} from "@langfuse/shared/src/server";
+import { env } from "@/src/env.mjs";
+import { z } from "zod";
+import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "@langfuse/shared";
+import { encrypt } from "@langfuse/shared/encryption";
+import { randomBytes } from "crypto";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { buildFilterSystemPrompt } from "./buildFilterPrompt";
+import { parseGeneratedFilters } from "./parseFilterCompletion";
+
+const GenerateFilterInput = z.object({
+ projectId: z.string(),
+ prompt: z.string().min(1).max(2048),
+ /** Existing bar query text, so the model refines the current filters. */
+ currentQuery: z.string().max(4096).optional(),
+ /** Project data context (observed values, metadata keys, result count) built
+ * on the client from already-loaded filterOptions + visible rows. */
+ dataContext: z.string().max(16000).optional(),
+});
+
+export const searchBarRouter = createTRPCRouter({
+ generateFilter: protectedProjectProcedure
+ .input(GenerateFilterInput)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "AI filter generation is not available in self-hosted deployments.",
+ });
+ }
+
+ const project = await ctx.prisma.project.findUnique({
+ where: { id: input.projectId },
+ select: {
+ organization: {
+ select: { aiFeaturesEnabled: true, aiTelemetryEnabled: true },
+ },
+ },
+ });
+
+ if (!project) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Project not found.",
+ });
+ }
+
+ if (!project.organization.aiFeaturesEnabled) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "AI features are not enabled for this organization.",
+ });
+ }
+
+ if (!env.LANGFUSE_AWS_BEDROCK_MODEL) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Bedrock environment variables not configured. Please set LANGFUSE_AWS_BEDROCK_* variables.",
+ });
+ }
+
+ // Anchor relative time expressions ("today", "last 24h") to now.
+ const now = new Date();
+ const dayOfWeek = now.toLocaleDateString("en-US", { weekday: "long" });
+ const currentDatetime = `${dayOfWeek}, ${now.toISOString()}`;
+ const systemPrompt = buildFilterSystemPrompt(
+ currentDatetime,
+ input.currentQuery,
+ input.dataContext,
+ );
+
+ const aiTelemetryEnabled = project.organization.aiTelemetryEnabled;
+ const targetProjectId = aiTelemetryEnabled
+ ? env.LANGFUSE_AI_FEATURES_PROJECT_ID
+ : undefined;
+
+ if (aiTelemetryEnabled && !targetProjectId) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Langfuse AI Features not configured.",
+ });
+ }
+
+ const traceSinkParams = targetProjectId
+ ? {
+ environment:
+ LangfuseInternalTraceEnvironment.NaturalLanguageFilter,
+ traceName: "search-bar-filter",
+ traceId: randomBytes(16).toString("hex"),
+ targetProjectId,
+ userId: ctx.session.user.id,
+ metadata: {
+ langfuse_ai_feature: "search-bar-filter",
+ langfuse_user_id: ctx.session.user.id,
+ langfuse_project_id: ctx.session.projectId,
+ // Debugging context for prompt iteration: a trace alone should
+ // explain WHY the model produced what it did. refine_mode marks
+ // refine vs. from-scratch; current_query is the filters being
+ // refined (the #1 thing to inspect when refine misbehaves);
+ // data_context_chars is how much observed-project context we
+ // injected. (Model + token usage are auto-captured on the
+ // generation.)
+ langfuse_refine_mode: Boolean(input.currentQuery?.trim()),
+ langfuse_current_query: input.currentQuery?.trim() || null,
+ langfuse_data_context_chars: input.dataContext?.length ?? 0,
+ },
+ }
+ : undefined;
+
+ const llmCompletion = await fetchLLMCompletion({
+ messages: [
+ {
+ role: ChatMessageRole.System,
+ content: systemPrompt,
+ type: ChatMessageType.PublicAPICreated,
+ },
+ {
+ role: ChatMessageRole.User,
+ content: input.prompt,
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "bedrock",
+ adapter: LLMAdapter.Bedrock,
+ model: env.LANGFUSE_AWS_BEDROCK_MODEL,
+ // Intentionally NO temperature/top_p: newer Bedrock models (e.g.
+ // Claude Opus 4.8, the prod AI-features model) reject them with
+ // `ValidationException: '<param>' is deprecated for this model`,
+ // which 500s the whole request. Filter generation is fine at model
+ // defaults, and omitting them is robust across model changes.
+ max_tokens: 2048,
+ },
+ llmConnection: {
+ secretKey: encrypt(BEDROCK_USE_DEFAULT_CREDENTIALS),
+ },
+ streaming: false,
+ traceSinkParams,
+ shouldUseLangfuseAPIKey: true,
+ });
+
+ if (typeof llmCompletion !== "string") {
+ throw new Error("Expected LLM completion to be a string");
+ }
+
+ // Parse the model output and keep only the filters that round-trip to
+ // bar grammar β€” a hallucinated/non-v4 column is dropped, never applied.
+ const { filters, queryText, droppedCount } =
+ parseGeneratedFilters(llmCompletion);
+
+ if (droppedCount > 0) {
+ logger.warn(
+ "Search-bar AI filter dropped non-representable filters",
+ {
+ projectId: input.projectId,
+ droppedCount,
+ },
+ );
+ }
+
+ return { filters, queryText };
+ } catch (error) {
+ // Already-shaped rejections (auth / precondition / not-found) are
+ // expected control flow, not backend faults β€” rethrow them without
+ // ERROR-level noise. Reserve `logger.error` for the unexpected, so it
+ // stays a signal for genuine failures.
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+ logger.error("Failed to generate search-bar AI filter", error);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "The AI backend currently appears to be unavailable. Please try again later.",
+ });
+ }
+ }),
+});
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 4e4b539d5a..ee4da42661 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -55,6 +55,7 @@ import { supportRouter } from "@/src/features/support-chat/trpc/supportRouter";
import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/annotationQueueAssignmentsRouter";
import { surveysRouter } from "@/src/server/api/routers/surveys";
import { naturalLanguageFilterRouter } from "@/src/features/natural-language-filters/server/router";
+import { searchBarRouter } from "@/src/features/search-bar/server/router";
import { notificationPreferencesRouter } from "@/src/server/api/routers/notificationPreferences";
import { onboardingRouter } from "@/src/features/onboarding/server/onboardingRouter";
import { webCalloutsRouter } from "@/src/features/web-callouts/server/router";
@@ -123,6 +124,7 @@ export const appRouter = createTRPCRouter({
surveys: surveysRouter,
onboarding: onboardingRouter,
naturalLanguageFilters: naturalLanguageFilterRouter,
+ searchBar: searchBarRouter,
notificationPreferences: notificationPreferencesRouter,
webCallouts: webCalloutsRouter,
inAppAgent: inAppAgentRouter,