Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(tables-ui): support full text search targeting input/ouput directly (#11999)

marliessophie7939cabc30af
diff --git a/packages/shared/src/interfaces/search.ts b/packages/shared/src/interfaces/search.ts
index bb7ad65592..f7206fa436 100644
--- a/packages/shared/src/interfaces/search.ts
+++ b/packages/shared/src/interfaces/search.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-export const TracingSearchType = z.enum(["id", "content"]);
+export const TracingSearchType = z.enum(["id", "content", "input", "output"]);
// id: for searching smaller columns like IDs, types, and other metadata
// content: for searching input/output text of functions traced via OpenTelemetry
export type TracingSearchType = z.infer<typeof TracingSearchType>;
diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.ts
index c74da012f8..b93006ab19 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts
@@ -23,6 +23,12 @@ export const clickhouseSearchCondition = (
searchType && searchType.includes("content")
? `${prefix}input ILIKE {searchString: String} OR ${prefix}output ILIKE {searchString: String}`
: null,
+ searchType && searchType.includes("input")
+ ? `${prefix}input ILIKE {searchString: String}`
+ : null,
+ searchType && searchType.includes("output")
+ ? `${prefix}output ILIKE {searchString: String}`
+ : null,
].filter(Boolean);
return {
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index 7985ba051c..4309063faf 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -25,6 +25,7 @@ export {
} from "./clickhouse-sql/orderby-factory";
export { createFilterFromFilterState } from "./clickhouse-sql/factory";
export { clickhouseSearchCondition } from "./clickhouse-sql/search";
+export { postgresSearchCondition } from "./postgres-sql/search";
export {
convertApiProvidedFilterToClickhouseFilter,
createPublicApiObservationsColumnMapping,
diff --git a/packages/shared/src/server/queries/postgres-sql/search.ts b/packages/shared/src/server/queries/postgres-sql/search.ts
new file mode 100644
index 0000000000..b5c5acf25e
--- /dev/null
+++ b/packages/shared/src/server/queries/postgres-sql/search.ts
@@ -0,0 +1,92 @@
+import { Prisma } from "@prisma/client";
+import { TracingSearchType } from "../../../interfaces/search";
+
+/**
+ * Builds PostgreSQL search condition for full-text search using ILIKE.
+ * Returns Prisma.sql for use in raw queries, or Prisma.empty if no search query provided.
+ *
+ * Missing column definitions make it obvious which search types are NOT supported:
+ * - If `contentColumns.content` is missing/empty → "content" search is not supported
+ * - If `contentColumns.input` is undefined → "input" search is not supported
+ * - If `contentColumns.output` is undefined → "output" search is not supported
+ *
+ * @param searchQuery - The search string to match against
+ * @param searchType - Array of search types: "id", "content", "input", "output"
+ * @param tablePrefix - Optional table alias/prefix (e.g., "p" for prompts, "di" for dataset items)
+ * @param metadataColumns - Array of column names to search when searchType includes "id" (e.g., ["name"])
+ * @param contentColumns - Column mappings that define which search types are supported
+ * @param additionalConditions - Optional additional Prisma.Sql conditions to OR with the main search
+ *
+ */
+export function postgresSearchCondition(params: {
+ searchQuery?: string | null;
+ searchType?: TracingSearchType[];
+ tablePrefix?: string;
+ metadataColumns: string[];
+ contentColumns: {
+ content?: string[]; // Optional - if missing, content search not supported
+ input?: string; // Optional - if missing, input search not supported
+ output?: string; // Optional - if missing, output search not supported
+ };
+ additionalConditions?: Prisma.Sql[];
+}): Prisma.Sql {
+ const {
+ searchQuery,
+ searchType,
+ tablePrefix = "",
+ metadataColumns = [],
+ contentColumns,
+ additionalConditions = [],
+ } = params;
+
+ if (searchQuery === undefined || searchQuery === null || searchQuery === "") {
+ return Prisma.empty;
+ }
+
+ const prefix = tablePrefix ? `${tablePrefix}.` : "";
+ const types = searchType ?? ["id"];
+ const searchConditions: Prisma.Sql[] = [];
+
+ // Search metadata columns (id, name, etc.)
+ if (types.includes("id")) {
+ for (const column of metadataColumns) {
+ searchConditions.push(
+ Prisma.sql`${Prisma.raw(`${prefix}${column}`)} ILIKE ${`%${searchQuery}%`}`,
+ );
+ }
+ }
+
+ // Search content - both input and output (only if columns are defined)
+ if (
+ types.includes("content") &&
+ contentColumns.content &&
+ contentColumns.content.length > 0
+ ) {
+ for (const column of contentColumns.content) {
+ searchConditions.push(
+ Prisma.sql`${Prisma.raw(`${prefix}${column}`)}::text ILIKE ${`%${searchQuery}%`}`,
+ );
+ }
+ }
+
+ // Search input only (only if column is defined)
+ if (types.includes("input") && contentColumns.input) {
+ searchConditions.push(
+ Prisma.sql`${Prisma.raw(`${prefix}${contentColumns.input}`)}::text ILIKE ${`%${searchQuery}%`}`,
+ );
+ }
+
+ // Search output only (only if column is defined)
+ if (types.includes("output") && contentColumns.output) {
+ searchConditions.push(
+ Prisma.sql`${Prisma.raw(`${prefix}${contentColumns.output}`)}::text ILIKE ${`%${searchQuery}%`}`,
+ );
+ }
+
+ // Add any additional custom conditions
+ searchConditions.push(...additionalConditions);
+
+ return searchConditions.length > 0
+ ? Prisma.sql` AND (${Prisma.join(searchConditions, " OR ")})`
+ : Prisma.empty;
+}
diff --git a/packages/shared/src/server/repositories/dataset-items.ts b/packages/shared/src/server/repositories/dataset-items.ts
index aab0829968..5830e40763 100644
--- a/packages/shared/src/server/repositories/dataset-items.ts
+++ b/packages/shared/src/server/repositories/dataset-items.ts
@@ -20,6 +20,8 @@ import {
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
} from "./clickhouse";
+import { postgresSearchCondition } from "../queries";
+import { TracingSearchType } from "../../interfaces/search";
const emptyNormalizeOpts: { sanitizeControlChars?: boolean } = {};
const emptyValidateOpts: { normalizeUndefinedToNull?: boolean } = {};
@@ -927,48 +929,6 @@ function buildPrismaWhereFromFilterState(filterState: FilterState): any {
return where;
}
-/**
- * Builds SQL search filter for full-text search on dataset items.
- * Applies ILIKE search on id, input, expectedOutput, and metadata fields.
- * Returns Prisma.empty if no search query provided.
- *
- * @param tableAlias - The table alias to use (default 'di' for dataset items)
- */
-function buildDatasetItemSearchCondition(
- searchQuery?: string,
- searchType?: ("id" | "content")[],
- tableAlias: string = "di",
-): Prisma.Sql {
- if (!searchQuery || searchQuery === "") {
- return Prisma.empty;
- }
-
- const types = searchType ?? ["content"];
- const searchConditions: Prisma.Sql[] = [];
-
- if (types.includes("id")) {
- searchConditions.push(
- Prisma.sql`${Prisma.raw(tableAlias)}.id ILIKE ${`%${searchQuery}%`}`,
- );
- }
-
- if (types.includes("content")) {
- searchConditions.push(
- Prisma.sql`${Prisma.raw(tableAlias)}.input::text ILIKE ${`%${searchQuery}%`}`,
- );
- searchConditions.push(
- Prisma.sql`${Prisma.raw(tableAlias)}.expected_output::text ILIKE ${`%${searchQuery}%`}`,
- );
- searchConditions.push(
- Prisma.sql`${Prisma.raw(tableAlias)}.metadata::text ILIKE ${`%${searchQuery}%`}`,
- );
- }
-
- return searchConditions.length > 0
- ? Prisma.sql` AND (${Prisma.join(searchConditions, " OR ")})`
- : Prisma.empty;
-}
-
/**
* Builds SQL query for STATEFUL dataset items with search support.
* Simple direct query without version logic.
@@ -979,7 +939,7 @@ function buildStatefulDatasetItemsQuery(
includeDatasetName: boolean,
filter: FilterState,
searchQuery?: string,
- searchType?: ("id" | "content")[],
+ searchType?: TracingSearchType[],
limit?: number,
offset?: number,
): Prisma.Sql {
@@ -1001,11 +961,17 @@ function buildStatefulDatasetItemsQuery(
"dataset_item_events",
);
- const searchCondition = buildDatasetItemSearchCondition(
+ const searchCondition = postgresSearchCondition({
searchQuery,
- searchType,
- "di",
- );
+ searchType: searchType ?? ["content"],
+ tablePrefix: "di",
+ metadataColumns: ["id"],
+ contentColumns: {
+ content: ["input", "expected_output", "metadata"],
+ input: "input",
+ output: "expected_output",
+ },
+ });
const paginationClause =
limit !== undefined
@@ -1042,7 +1008,7 @@ function buildStatefulDatasetItemsCountQuery(
projectId: string,
filter: FilterState,
searchQuery?: string,
- searchType?: ("id" | "content")[],
+ searchType?: TracingSearchType[],
): Prisma.Sql {
const filterCondition = tableColumnsToSqlFilterAndPrefix(
filter,
@@ -1050,11 +1016,17 @@ function buildStatefulDatasetItemsCountQuery(
"dataset_item_events",
);
- const searchCondition = buildDatasetItemSearchCondition(
+ const searchCondition = postgresSearchCondition({
searchQuery,
- searchType,
- "di",
- );
+ searchType: searchType ?? ["content"],
+ tablePrefix: "di",
+ metadataColumns: ["id"],
+ contentColumns: {
+ content: ["input", "expected_output", "metadata"],
+ input: "input",
+ output: "expected_output",
+ },
+ });
return Prisma.sql`
SELECT COUNT(*) as count
@@ -1087,7 +1059,7 @@ function buildDatasetItemsAtVersionQuery(
filter: FilterState,
version: Date | undefined,
searchQuery?: string,
- searchType?: ("id" | "content")[],
+ searchType?: TracingSearchType[],
limit?: number,
offset?: number,
): Prisma.Sql {
@@ -1109,10 +1081,16 @@ function buildDatasetItemsAtVersionQuery(
"dataset_item_events",
);
- const searchCondition = buildDatasetItemSearchCondition(
+ const searchCondition = postgresSearchCondition({
searchQuery,
- searchType,
- );
+ searchType: searchType ?? ["content"],
+ metadataColumns: ["id"],
+ contentColumns: {
+ content: ["input", "expected_output", "metadata"],
+ input: "input",
+ output: "expected_output",
+ },
+ });
const paginationClause =
limit !== undefined
@@ -1161,7 +1139,7 @@ function buildDatasetItemsCountQuery(
filter: FilterState,
version?: Date,
searchQuery?: string,
- searchType?: ("id" | "content")[],
+ searchType?: TracingSearchType[],
): Prisma.Sql {
const filterCondition = tableColumnsToSqlFilterAndPrefix(
filter,
@@ -1169,10 +1147,16 @@ function buildDatasetItemsCountQuery(
"dataset_item_events",
);
- const searchCondition = buildDatasetItemSearchCondition(
+ const searchCondition = postgresSearchCondition({
searchQuery,
- searchType,
- );
+ searchType: searchType ?? ["content"],
+ metadataColumns: ["id"],
+ contentColumns: {
+ content: ["input", "expected_output", "metadata"],
+ input: "input",
+ output: "expected_output",
+ },
+ });
// New temporal query using valid_from and valid_to
// Much simpler and more performant - no DISTINCT ON or CTE needed!
@@ -1273,7 +1257,7 @@ async function getDatasetItemsInternal<
filter: FilterState;
version?: Date;
searchQuery?: string;
- searchType?: ("id" | "content")[];
+ searchType?: TracingSearchType[];
limit?: number;
offset?: number;
}): Promise<
@@ -1329,7 +1313,7 @@ async function getDatasetItemsCountAtVersionInternal(params: {
filterState: FilterState;
version?: Date;
searchQuery?: string;
- searchType?: ("id" | "content")[];
+ searchType?: TracingSearchType[];
}): Promise<number> {
const query = buildDatasetItemsCountQuery(
params.projectId,
@@ -1457,7 +1441,7 @@ export async function getDatasetItems<
filterState: FilterState;
version?: Date;
searchQuery?: string;
- searchType?: ("id" | "content")[];
+ searchType?: TracingSearchType[];
includeIO?: IncludeIO;
includeDatasetName?: IncludeDatasetName;
limit?: number;
@@ -1574,7 +1558,7 @@ export async function getDatasetItemsCount(props: {
filterState: FilterState;
version?: Date;
searchQuery?: string;
- searchType?: ("id" | "content")[];
+ searchType?: TracingSearchType[];
}): Promise<number> {
return executeWithDatasetServiceStrategy(OperationType.READ, {
[Implementation.STATEFUL]: async () => {
diff --git a/web/src/__tests__/server/observations-trpc.servertest.ts b/web/src/__tests__/server/observations-trpc.servertest.ts
index be63bbeb09..67398a50da 100644
--- a/web/src/__tests__/server/observations-trpc.servertest.ts
+++ b/web/src/__tests__/server/observations-trpc.servertest.ts
@@ -123,5 +123,83 @@ describe("traces trpc", () => {
expect(generations.generations).toBeDefined();
});
+
+ it("should search generations by input only", async () => {
+ const traceId = randomUUID();
+ const generationId = randomUUID();
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ name: "input-search-trace",
+ });
+
+ await createTracesCh([trace]);
+
+ // Create generation with distinct input and output
+ const generation = createObservation({
+ id: generationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "input-search-generation",
+ input: "unique_input_keyword for search testing",
+ output: "different output without the keyword",
+ });
+
+ await createObservationsCh([generation]);
+
+ // Search for keyword that only exists in input
+ const inputSearchResults = await caller.generations.all({
+ projectId,
+ searchQuery: "unique_input_keyword",
+ searchType: ["input"], // Search only in input
+ filter: [],
+ orderBy: null,
+ limit: 50,
+ page: 0,
+ });
+
+ expect(inputSearchResults.generations).toBeDefined();
+ });
+
+ it("should search generations by output only", async () => {
+ const traceId = randomUUID();
+ const generationId = randomUUID();
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ name: "output-search-trace",
+ });
+
+ await createTracesCh([trace]);
+
+ // Create generation with distinct input and output
+ const generation = createObservation({
+ id: generationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "output-search-generation",
+ input: "simple input without special keywords",
+ output: "unique_output_keyword for search testing",
+ });
+
+ await createObservationsCh([generation]);
+
+ // Search for keyword that only exists in output
+ const outputSearchResults = await caller.generations.all({
+ projectId,
+ searchQuery: "unique_output_keyword",
+ searchType: ["output"], // Search only in output
+ filter: [],
+ orderBy: null,
+ limit: 50,
+ page: 0,
+ });
+
+ expect(outputSearchResults.generations).toBeDefined();
+ });
});
});
diff --git a/web/src/__tests__/server/repositories/dataset-items-repository.servertest.ts b/web/src/__tests__/server/repositories/dataset-items-repository.servertest.ts
index 6092b9ec1b..de7abf3fcd 100644
--- a/web/src/__tests__/server/repositories/dataset-items-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/dataset-items-repository.servertest.ts
@@ -1690,4 +1690,52 @@ describe("Dataset Items Repository - Versioning Tests", () => {
expect(allVersions[1].isDeleted).toBe(true);
});
});
+
+ describe("getDatasetItems() with search", () => {
+ it("should search dataset items by expected output only", async () => {
+ const datasetId = v4();
+ await prisma.dataset.create({
+ data: { id: datasetId, name: v4(), projectId },
+ });
+
+ // Create dataset items with distinct input and expected output
+ const item1 = await createDatasetItem({
+ projectId,
+ datasetId,
+ input: { query: "simple input text" },
+ expectedOutput: { result: "unique_output_search_keyword" },
+ normalizeOpts: {},
+ validateOpts: {},
+ });
+
+ const item2 = await createDatasetItem({
+ projectId,
+ datasetId,
+ input: { query: "another input with keyword" },
+ expectedOutput: { result: "different output" },
+ normalizeOpts: {},
+ validateOpts: {},
+ });
+
+ if (!item1.success || !item2.success) {
+ throw new Error("Failed to create items");
+ }
+
+ // Search for keyword that only exists in expected output
+ const searchResults = await getDatasetItems({
+ projectId,
+ filterState: createDatasetItemFilterState({ datasetIds: [datasetId] }),
+ limit: 100,
+ page: 0,
+ searchQuery: "unique_output_search_keyword",
+ searchType: ["output"], // Search only in expected output
+ });
+
+ expect(searchResults.length).toBe(1);
+ expect(searchResults[0].id).toBe(item1.datasetItem.id);
+ expect(searchResults[0].expectedOutput).toEqual({
+ result: "unique_output_search_keyword",
+ });
+ });
+ });
});
diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.ts
index 0c891c88d6..902070e619 100644
--- a/web/src/__tests__/server/traces-trpc.servertest.ts
+++ b/web/src/__tests__/server/traces-trpc.servertest.ts
@@ -204,6 +204,74 @@ describe("traces trpc", () => {
expect(traces.traces.length).toBe(0);
});
+
+ it("should search traces by input only", async () => {
+ const trace = createTrace({
+ project_id: projectId,
+ input: { query: "unique_trace_input_keyword" },
+ output: { result: "different output" },
+ name: "input-search-trace",
+ });
+
+ await createTracesCh([trace]);
+
+ const traces = await caller.traces.all({
+ projectId,
+ filter: [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: new Date(new Date().getTime() - 1000).toISOString(),
+ },
+ ],
+ searchQuery: "unique_trace_input_keyword",
+ searchType: ["input"], // Search only in input
+ page: 0,
+ limit: 50,
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ });
+
+ expect(traces.traces.length).toBeGreaterThan(0);
+ expect(traces.traces.some((t) => t.id === trace.id)).toBe(true);
+ });
+
+ it("should search traces by output only", async () => {
+ const trace = createTrace({
+ project_id: projectId,
+ input: { query: "simple input" },
+ output: { result: "unique_trace_output_keyword for testing" },
+ name: "output-search-trace",
+ });
+
+ await createTracesCh([trace]);
+
+ const traces = await caller.traces.all({
+ projectId,
+ filter: [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: new Date(new Date().getTime() - 1000).toISOString(),
+ },
+ ],
+ searchQuery: "unique_trace_output_keyword",
+ searchType: ["output"], // Search only in output
+ page: 0,
+ limit: 50,
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ });
+
+ expect(traces.traces.length).toBeGreaterThan(0);
+ expect(traces.traces.some((t) => t.id === trace.id)).toBe(true);
+ });
});
describe("traces.countAll", () => {
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index eebc02e182..7ff61e6d90 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -44,6 +44,9 @@ import {
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
+ DropdownMenuSub,
+ DropdownMenuSubTrigger,
+ DropdownMenuSubContent,
} from "@/src/components/ui/dropdown-menu";
import { useDataTableControls } from "@/src/components/table/data-table-controls";
import { MultiSelect as MultiSelectFilter } from "@/src/features/filters/components/multi-select";
@@ -51,6 +54,11 @@ import {
DataTableRefreshButton,
type RefreshInterval,
} from "@/src/components/table/data-table-refresh-button";
+import {
+ getSearchButtonLabel,
+ getSearchMode,
+ searchModeToType,
+} from "@/src/components/table/utils/searchUtils";
export interface MultiSelect {
selectAll: boolean;
@@ -74,6 +82,11 @@ interface SearchConfig {
fullText: string;
};
hidePerformanceWarning?: boolean;
+ availableSearchTypes?: {
+ content: boolean;
+ input: boolean;
+ output: boolean;
+ };
}
interface TableViewControllers {
@@ -127,6 +140,44 @@ interface DataTableToolbarProps<TData, TValue> {
viewModeToggle?: React.ReactNode;
}
+// Helper function to get the description for DocPopup
+function getSearchDescription(
+ searchType: TracingSearchType[] | undefined,
+ metadataFields: string[] | undefined,
+ hidePerformanceWarning: boolean | undefined,
+ tableAllowsFullTextSearch: boolean | undefined,
+): React.ReactNode {
+ const fields = metadataFields?.join(", ") ?? "";
+ const performanceWarning = !hidePerformanceWarning
+ ? " For improved performance, please filter the table down."
+ : "";
+
+ if (tableAllowsFullTextSearch && searchType?.includes("content")) {
+ return (
+ <p className="text-primary text-xs font-normal">
+ Searches in Input/Output and {fields}.{performanceWarning}
+ </p>
+ );
+ }
+ if (tableAllowsFullTextSearch && searchType?.includes("input")) {
+ return (
+ <p className="text-primary text-xs font-normal">
+ Searches in Input and {fields}.{performanceWarning}
+ </p>
+ );
+ }
+ if (tableAllowsFullTextSearch && searchType?.includes("output")) {
+ return (
+ <p className="text-primary text-xs font-normal">
+ Searches in Output and {fields}.{performanceWarning}
+ </p>
+ );
+ }
+ return (
+ <p className="text-primary text-xs font-normal">Searches in {fields}.</p>
+ );
+}
+
export function DataTableToolbar<TData, TValue>({
columns,
filterColumnDefinition,
@@ -253,30 +304,17 @@ export function DataTableToolbar<TData, TValue>({
>
<span className="flex items-center gap-1 truncate">
{searchConfig.tableAllowsFullTextSearch &&
- (searchConfig.searchType ?? []).includes("content")
- ? (searchConfig.customDropdownLabels?.fullText ??
- "Full Text")
- : (searchConfig.customDropdownLabels?.metadata ??
- "IDs / Names")}
+ getSearchButtonLabel(
+ searchConfig.searchType,
+ searchConfig.customDropdownLabels?.metadata,
+ )}
<DocPopup
- description={
- searchConfig.tableAllowsFullTextSearch &&
- (searchConfig.searchType ?? []).includes(
- "content",
- ) ? (
- <p className="text-primary text-xs font-normal">
- Searches in Input/Output and{" "}
- {searchConfig.metadataSearchFields?.join(", ")}.
- {!searchConfig.hidePerformanceWarning &&
- " For improved performance, please filter the table down."}
- </p>
- ) : (
- <p className="text-primary text-xs font-normal">
- Searches in{" "}
- {searchConfig.metadataSearchFields?.join(", ")}.
- </p>
- )
- }
+ description={getSearchDescription(
+ searchConfig.searchType,
+ searchConfig.metadataSearchFields,
+ searchConfig.hidePerformanceWarning,
+ searchConfig.tableAllowsFullTextSearch,
+ )}
/>
</span>
<ChevronDown className="h-4 w-4 opacity-50" />
@@ -284,37 +322,72 @@ export function DataTableToolbar<TData, TValue>({
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuRadioGroup
- value={
- searchConfig.tableAllowsFullTextSearch &&
- (searchConfig.searchType ?? []).includes("content")
- ? "metadata_fulltext"
- : "metadata"
- }
+ value={getSearchMode(
+ searchConfig.searchType,
+ searchConfig.tableAllowsFullTextSearch,
+ )}
onValueChange={(value) => {
if (
!searchConfig.tableAllowsFullTextSearch &&
- value === "metadata_fulltext"
+ value.startsWith("metadata_fulltext")
)
return;
-
- const newSearchType =
- value === "metadata_fulltext"
- ? ["id" as const, "content" as const]
- : ["id" as const];
- searchConfig.setSearchType?.(newSearchType);
+ searchConfig.setSearchType?.(searchModeToType(value));
}}
>
<DropdownMenuRadioItem value="metadata">
{searchConfig.customDropdownLabels?.metadata ??
"IDs / Names"}
</DropdownMenuRadioItem>
- <DropdownMenuRadioItem
- value="metadata_fulltext"
- disabled={!searchConfig.tableAllowsFullTextSearch}
- >
- {searchConfig.customDropdownLabels?.fullText ??
- "Full Text"}
- </DropdownMenuRadioItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger
+ disabled={!searchConfig.tableAllowsFullTextSearch}
+ >
+ <span className="flex items-center gap-2">
+ {getSearchMode(
+ searchConfig.searchType,
+ searchConfig.tableAllowsFullTextSearch,
+ ).startsWith("metadata_fulltext") && (
+ <span className="h-2 w-2 shrink-0 rounded-full bg-current" />
+ )}
+ {searchConfig.customDropdownLabels?.fullText ??
+ "Full Text"}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup
+ value={getSearchMode(
+ searchConfig.searchType,
+ searchConfig.tableAllowsFullTextSearch,
+ )}
+ onValueChange={(value) => {
+ searchConfig.setSearchType?.(
+ searchModeToType(value),
+ );
+ }}
+ >
+ {/* Only show options that are explicitly available */}
+ {(searchConfig.availableSearchTypes === undefined ||
+ searchConfig.availableSearchTypes.content) && (
+ <DropdownMenuRadioItem value="metadata_fulltext">
+ Input/Output
+ </DropdownMenuRadioItem>
+ )}
+ {(searchConfig.availableSearchTypes === undefined ||
+ searchConfig.availableSearchTypes.input) && (
+ <DropdownMenuRadioItem value="metadata_fulltext_input">
+ Input
+ </DropdownMenuRadioItem>
+ )}
+ {(searchConfig.availableSearchTypes === undefined ||
+ searchConfig.availableSearchTypes.output) && (
+ <DropdownMenuRadioItem value="metadata_fulltext_output">
+ Output
+ </DropdownMenuRadioItem>
+ )}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/web/src/components/table/utils/searchUtils.ts b/web/src/components/table/utils/searchUtils.ts
new file mode 100644
index 0000000000..2d5f8ec2f5
--- /dev/null
+++ b/web/src/components/table/utils/searchUtils.ts
@@ -0,0 +1,39 @@
+import type { TracingSearchType } from "@langfuse/shared";
+
+// Helper function to get the current search mode value for the radio group
+export function getSearchMode(
+ searchType: TracingSearchType[] | undefined,
+ tableAllowsFullTextSearch = false,
+): string {
+ if (!searchType || !tableAllowsFullTextSearch) return "metadata";
+ if (searchType.includes("content")) return "metadata_fulltext";
+ if (searchType.includes("input")) return "metadata_fulltext_input";
+ if (searchType.includes("output")) return "metadata_fulltext_output";
+ return "metadata";
+}
+
+// Helper function to get the button label based on current search type
+export function getSearchButtonLabel(
+ searchType: TracingSearchType[] | undefined,
+ metadataLabel?: string,
+): string {
+ if (!searchType) return metadataLabel ?? "IDs / Names";
+ if (searchType.includes("content")) return "Full Text: Content";
+ if (searchType.includes("input")) return "Full Text: Input";
+ if (searchType.includes("output")) return "Full Text: Output";
+ return metadataLabel ?? "IDs / Names";
+}
+
+// Helper function to convert search mode value to search type array
+export function searchModeToType(mode: string): TracingSearchType[] {
+ switch (mode) {
+ case "metadata_fulltext":
+ return ["id", "content"];
+ case "metadata_fulltext_input":
+ return ["id", "input"];
+ case "metadata_fulltext_output":
+ return ["id", "output"];
+ default:
+ return ["id"];
+ }
+}
diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.ts
index 6716431262..2aa7c27e87 100644
--- a/web/src/features/events/hooks/useEventsTableData.ts
+++ b/web/src/features/events/hooks/useEventsTableData.ts
@@ -3,6 +3,7 @@ import { useMemo } from "react";
import {
type FilterState,
AnnotationQueueObjectType,
+ type TracingSearchType,
type ScoreAggregate,
} from "@langfuse/shared";
import { type FullEventsObservations } from "@langfuse/shared/src/server";
@@ -27,7 +28,7 @@ type UseEventsTableDataParams = {
order: "ASC" | "DESC";
} | null;
searchQuery?: string | null;
- searchType?: ("id" | "content")[];
+ searchType?: TracingSearchType[];
selectedRows: Record<string, boolean>;
selectAll: boolean;
setSelectedRows: (rows: Record<string, boolean>) => void;
@@ -184,11 +185,14 @@ export function useEventsTableData({
projectId: string;
targetId: string;
}) => {
+ const visibleObservationIds = new Set(
+ (observations.data?.observations ?? [])
+ .map((observation) => observation.id)
+ .filter((id): id is string => Boolean(id)),
+ );
+
const selectedObservationIds = Object.keys(selectedRows).filter(
- (observationId) =>
- (observations.data?.observations ?? [])
- .map((o) => o.id)
- .includes(observationId),
+ (observationId) => visibleObservationIds.has(observationId),
);
await addToQueueMutation.mutateAsync({
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 7add804bd7..62d91c797c 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -407,6 +407,11 @@ export function PromptTable() {
fullText: "Full Text",
},
hidePerformanceWarning: true,
+ availableSearchTypes: {
+ content: true,
+ input: false,
+ output: false,
+ },
}}
/>
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 47e6aa3a47..3290d1cad6 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -1,5 +1,4 @@
import { z } from "zod";
-
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
@@ -36,39 +35,12 @@ import {
getObservationsWithPromptName,
getObservationMetricsForPrompts,
getAggregatedScoresForPrompts,
+ postgresSearchCondition,
} from "@langfuse/shared/src/server";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
import { TRPCError } from "@trpc/server";
import { promptChangeEventSourcing } from "@/src/features/prompts/server/promptChangeEventSourcing";
-const buildPromptSearchFilter = (
- searchQuery: string | undefined | null,
- searchType?: TracingSearchType[],
-): Prisma.Sql => {
- if (searchQuery === undefined || searchQuery === null || searchQuery === "") {
- return Prisma.empty;
- }
-
- const q = searchQuery;
- const types = searchType ?? ["id"];
- const searchConditions: Prisma.Sql[] = [];
-
- if (types.includes("id")) {
- searchConditions.push(Prisma.sql`p.name ILIKE ${`%${q}%`}`);
- searchConditions.push(
- Prisma.sql`EXISTS (SELECT 1 FROM UNNEST(p.tags) AS tag WHERE tag ILIKE ${`%${q}%`})`,
- );
- }
-
- if (types.includes("content")) {
- searchConditions.push(Prisma.sql`p.prompt::text ILIKE ${`%${q}%`}`);
- }
-
- return searchConditions.length > 0
- ? Prisma.sql` AND (${Prisma.join(searchConditions, " OR ")})`
- : Prisma.empty;
-};
-
const buildPathPrefixFilter = (pathPrefix?: string): Prisma.Sql => {
if (!pathPrefix) {
return Prisma.empty;
@@ -77,7 +49,6 @@ const buildPathPrefixFilter = (pathPrefix?: string): Prisma.Sql => {
const escapedPathPrefix = escapeSqlLikePattern(pathPrefix);
return Prisma.sql` AND (p.name LIKE ${`${escapedPathPrefix}/%`} ESCAPE '\\' OR p.name = ${pathPrefix})`;
};
-
const PromptFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
filter: z.array(singleFilter),
@@ -135,10 +106,22 @@ export const promptRouter = createTRPCRouter({
// pathFilter: SQL WHERE clause to filter prompts by folder (e.g., "AND p.name LIKE 'folder/%'")
const pathFilter = buildPathPrefixFilter(input.pathPrefix);
- const searchFilter = buildPromptSearchFilter(
- input.searchQuery,
- input.searchType,
- );
+ const additionalConditions = input.searchType?.includes("id")
+ ? [
+ Prisma.sql`EXISTS (SELECT 1 FROM UNNEST(p.tags) AS tag WHERE tag ILIKE ${`%${input.searchQuery}%`})`,
+ ]
+ : [];
+
+ const searchCondition = postgresSearchCondition({
+ searchQuery: input.searchQuery,
+ searchType: input.searchType,
+ tablePrefix: "p",
+ metadataColumns: ["name"],
+ contentColumns: {
+ content: ["prompt"],
+ },
+ additionalConditions,
+ });
const [prompts, promptCount] = await Promise.all([
// prompts
@@ -162,7 +145,7 @@ export const promptRouter = createTRPCRouter({
input.limit,
input.page,
pathFilter, // SQL WHERE clause: filters DB to only prompts in current folder, derived from prefix.
- searchFilter,
+ searchCondition,
input.pathPrefix, // Raw folder path: used for segment splitting & folder detection logic
),
),
@@ -176,7 +159,7 @@ export const promptRouter = createTRPCRouter({
1, // limit
0, // input.page,
pathFilter,
- searchFilter,
+ searchCondition,
input.pathPrefix,
),
),
@@ -216,10 +199,22 @@ export const promptRouter = createTRPCRouter({
const pathFilter = buildPathPrefixFilter(input.pathPrefix);
- const searchFilter = buildPromptSearchFilter(
- input.searchQuery,
- input.searchType,
- );
+ const additionalConditions = input.searchType?.includes("id")
+ ? [
+ Prisma.sql`EXISTS (SELECT 1 FROM UNNEST(p.tags) AS tag WHERE tag ILIKE ${`%${input.searchQuery}%`})`,
+ ]
+ : [];
+
+ const searchCondition = postgresSearchCondition({
+ searchQuery: input.searchQuery,
+ searchType: input.searchType,
+ tablePrefix: "p",
+ metadataColumns: ["name"],
+ contentColumns: {
+ content: ["prompt"],
+ },
+ additionalConditions,
+ });
const count = await ctx.prisma.$queryRaw<Array<{ totalCount: bigint }>>(
generatePromptQuery(
@@ -230,7 +225,7 @@ export const promptRouter = createTRPCRouter({
1, // limit
0, // page
pathFilter,
- searchFilter,
+ searchCondition,
input.pathPrefix,
),
);