Skip to content

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

fix: use drop down for prompt full text search (#8043)

Max Deichmannae91a98ad9bc
diff --git a/web/src/__tests__/async/prompts-trpc.servertest.ts b/web/src/__tests__/async/prompts-trpc.servertest.ts
index aeab8f6ec1..45fd1b5bac 100644
--- a/web/src/__tests__/async/prompts-trpc.servertest.ts
+++ b/web/src/__tests__/async/prompts-trpc.servertest.ts
@@ -679,6 +679,7 @@ describe("prompts trpc", () => {
filter: [],
orderBy: { column: "createdAt", order: "DESC" },
searchQuery: "customer support agent",
+ searchType: ["content"],
});
expect(contentSearchResults.prompts).toHaveLength(1);
@@ -694,6 +695,7 @@ describe("prompts trpc", () => {
filter: [],
orderBy: { column: "createdAt", order: "DESC" },
searchQuery: "marketing",
+ searchType: ["id"],
});
expect(nameSearchResults.prompts).toHaveLength(1);
@@ -707,6 +709,7 @@ describe("prompts trpc", () => {
filter: [],
orderBy: { column: "createdAt", order: "DESC" },
searchQuery: "documentation",
+ searchType: ["id"],
});
expect(tagSearchResults.prompts).toHaveLength(1);
@@ -720,6 +723,7 @@ describe("prompts trpc", () => {
filter: [],
orderBy: { column: "createdAt", order: "DESC" },
searchQuery: "nonexistent content",
+ searchType: ["id", "content"],
});
expect(noMatchResults.prompts).toHaveLength(0);
@@ -732,6 +736,7 @@ describe("prompts trpc", () => {
filter: [],
orderBy: { column: "createdAt", order: "DESC" },
searchQuery: "TECHNICAL",
+ searchType: ["id"],
});
expect(caseInsensitiveResults.prompts).toHaveLength(1);
@@ -780,6 +785,7 @@ describe("prompts trpc", () => {
filter: [],
orderBy: { column: "createdAt", order: "DESC" },
searchQuery: "machine learning",
+ searchType: ["content"],
});
// Should find the prompt because one of its versions contains the search term
@@ -789,4 +795,222 @@ describe("prompts trpc", () => {
expect(searchResults.prompts[0].version).toBe(2);
});
});
+
+ describe("prompts.count with search and searchType", () => {
+ it("should count prompts correctly with different search types", async () => {
+ const { project, caller } = await prepare();
+
+ // Create test prompts with different searchable content
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "customer-service-prompt",
+ version: 1,
+ type: "text",
+ prompt: {
+ text: "You are a helpful customer support agent. Answer questions about billing and account issues.",
+ },
+ createdBy: "test-user",
+ tags: ["support", "customer"],
+ labels: ["production"],
+ },
+ });
+
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "marketing-prompt",
+ version: 1,
+ type: "text",
+ prompt: {
+ text: "Create engaging marketing content that drives sales and conversions.",
+ },
+ createdBy: "test-user",
+ tags: ["marketing", "content"],
+ labels: ["staging"],
+ },
+ });
+
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "technical-docs",
+ version: 1,
+ type: "text",
+ prompt: {
+ text: "Generate comprehensive technical documentation for APIs and software systems.",
+ },
+ createdBy: "test-user",
+ tags: ["technical", "documentation"],
+ labels: ["latest"],
+ },
+ });
+
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "sales-support-prompt",
+ version: 1,
+ type: "text",
+ prompt: {
+ text: "Assist sales teams with lead qualification and customer outreach.",
+ },
+ createdBy: "test-user",
+ tags: ["sales", "support"],
+ labels: ["production"],
+ },
+ });
+
+ // Test 1: Count all prompts (no search)
+ const totalCountResult = await caller.prompts.count({
+ projectId: project.id,
+ });
+ expect(totalCountResult.totalCount).toBe(BigInt(4));
+
+ // Test 2: Count with ID search type (default) - search in names and tags
+ const idSearchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "support",
+ searchType: ["id"],
+ });
+ // Should find "customer-service-prompt" and "sales-support-prompt" (by name and tags)
+ expect(idSearchCountResult.totalCount).toBe(BigInt(2));
+
+ // Test 3: Count with content search type - search in prompt content
+ const contentSearchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "customer",
+ searchType: ["content"],
+ });
+ // Should find "customer-service-prompt" and "sales-support-prompt" (by content: "customer" appears in both)
+ expect(contentSearchCountResult.totalCount).toBe(BigInt(2));
+
+ // Test 4: Count with both ID and content search types
+ const combinedSearchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "marketing",
+ searchType: ["id", "content"],
+ });
+ // Should find "marketing-prompt" (by both name and content)
+ expect(combinedSearchCountResult.totalCount).toBe(BigInt(1));
+
+ // Test 5: Count with tag-specific search (ID search type)
+ const tagSearchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "documentation",
+ searchType: ["id"],
+ });
+ // Should find "technical-docs" (by tag)
+ expect(tagSearchCountResult.totalCount).toBe(BigInt(1));
+
+ // Test 6: Count with content that doesn't exist in names/tags but exists in prompt text
+ const contentOnlySearchResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "billing",
+ searchType: ["content"],
+ });
+ // Should find "customer-service-prompt" (by content only)
+ expect(contentOnlySearchResult.totalCount).toBe(BigInt(1));
+
+ // Test 7: Count with no matches
+ const noMatchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "nonexistent",
+ searchType: ["id", "content"],
+ });
+ expect(noMatchCountResult.totalCount).toBe(BigInt(0));
+
+ // Test 8: Count with case insensitive search
+ const caseInsensitiveCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "TECHNICAL",
+ searchType: ["id"],
+ });
+ // Should find "technical-docs" (case insensitive)
+ expect(caseInsensitiveCountResult.totalCount).toBe(BigInt(1));
+
+ // Test 9: Count with filters and search combined
+ const filteredSearchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ searchQuery: "support",
+ searchType: ["id"],
+ filter: [
+ {
+ column: "labels",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ],
+ });
+ // Should find prompts with "support" AND "production" label
+ expect(filteredSearchCountResult.totalCount).toBe(BigInt(2));
+ });
+
+ it("should count prompts with folder path prefix and search", async () => {
+ const { project, caller } = await prepare();
+
+ // Create prompts in different folder structures
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "folder1/customer-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Customer service prompt" },
+ createdBy: "test-user",
+ tags: ["customer"],
+ },
+ });
+
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "folder1/support-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Technical support prompt" },
+ createdBy: "test-user",
+ tags: ["support"],
+ },
+ });
+
+ await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: "folder2/customer-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Another customer prompt" },
+ createdBy: "test-user",
+ tags: ["customer"],
+ },
+ });
+
+ // Test: Count with path prefix and search
+ const folderSearchCountResult = await caller.prompts.count({
+ projectId: project.id,
+ pathPrefix: "folder1",
+ searchQuery: "customer",
+ searchType: ["id"],
+ });
+ // Should only find prompts in folder1 that match "customer"
+ expect(folderSearchCountResult.totalCount).toBe(BigInt(1));
+
+ // Test: Count with path prefix but no search
+ const folderCountResult = await caller.prompts.count({
+ projectId: project.id,
+ pathPrefix: "folder1",
+ });
+ // Should find all prompts in folder1
+ expect(folderCountResult.totalCount).toBe(BigInt(2));
+ });
+ });
});
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index 9f01433ea1..61c41b57cc 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -58,6 +58,11 @@ interface SearchConfig {
tableAllowsFullTextSearch?: boolean;
setSearchType: ((newSearchType: TracingSearchType[]) => void) | undefined;
searchType: TracingSearchType[] | undefined;
+ customDropdownLabels?: {
+ metadata: string;
+ fullText: string;
+ };
+ hidePerformanceWarning?: boolean;
}
interface TableViewControllers {
@@ -185,8 +190,10 @@ export function DataTableToolbar<TData, TValue>({
<span className="flex items-center gap-1 truncate">
{searchConfig.tableAllowsFullTextSearch &&
(searchConfig.searchType ?? []).includes("content")
- ? "Full Text"
- : "IDs / Names"}
+ ? (searchConfig.customDropdownLabels?.fullText ??
+ "Full Text")
+ : (searchConfig.customDropdownLabels?.metadata ??
+ "IDs / Names")}
<DocPopup
description={
searchConfig.tableAllowsFullTextSearch &&
@@ -196,8 +203,8 @@ export function DataTableToolbar<TData, TValue>({
<p className="text-xs font-normal text-primary">
Searches in Input/Output and{" "}
{searchConfig.metadataSearchFields.join(", ")}.
- For improved performance, please filter the table
- down.
+ {!searchConfig.hidePerformanceWarning &&
+ " For improved performance, please filter the table down."}
</p>
) : (
<p className="text-xs font-normal text-primary">
@@ -234,13 +241,15 @@ export function DataTableToolbar<TData, TValue>({
}}
>
<DropdownMenuRadioItem value="metadata">
- IDs / Names
+ {searchConfig.customDropdownLabels?.metadata ??
+ "IDs / Names"}
</DropdownMenuRadioItem>
<DropdownMenuRadioItem
value="metadata_fulltext"
disabled={!searchConfig.tableAllowsFullTextSearch}
>
- Full Text
+ {searchConfig.customDropdownLabels?.fullText ??
+ "Full Text"}
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 5b67cc6a74..8627c58057 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -16,7 +16,6 @@ import {
StringParam,
useQueryParams,
withDefault,
- useQueryParam,
} from "use-query-params";
import { createColumnHelper } from "@tanstack/react-table";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
@@ -33,6 +32,7 @@ import {
} from "@/src/components/ui/breadcrumb";
import { Slash, Folder, Home } from "lucide-react";
import { promptsTableColsWithOptions } from "@langfuse/shared";
+import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
type PromptTableRow = {
id: string;
@@ -101,10 +101,8 @@ export function PromptTable() {
folder: StringParam,
});
- const [searchQuery, setSearchQuery] = useQueryParam(
- "search",
- withDefault(StringParam, null),
- );
+ const { searchQuery, searchType, setSearchQuery, setSearchType } =
+ useFullTextSearch();
// Reset pagination when search query changes
useEffect(() => {
@@ -132,6 +130,7 @@ export function PromptTable() {
orderBy: orderByState,
pathPrefix: currentFolderPath,
searchQuery: searchQuery || undefined,
+ searchType: searchType,
},
{
enabled: Boolean(projectId),
@@ -464,8 +463,13 @@ export function PromptTable() {
updateQuery: useDebounce(setSearchQuery, 300),
currentQuery: searchQuery ?? undefined,
tableAllowsFullTextSearch: true,
- setSearchType: undefined,
- searchType: undefined,
+ setSearchType,
+ searchType,
+ customDropdownLabels: {
+ metadata: "Names, Tags",
+ fullText: "Full Text",
+ },
+ hidePerformanceWarning: true,
}}
/>
<DataTable
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 1efa8d2da2..3b533eccd8 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -20,6 +20,7 @@ import {
promptsTableCols,
PromptType,
StringNoHTMLNonEmpty,
+ TracingSearchType,
} from "@langfuse/shared";
import { orderBy, singleFilter } from "@langfuse/shared";
import {
@@ -36,6 +37,34 @@ 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 PromptFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
filter: z.array(singleFilter),
@@ -43,6 +72,7 @@ const PromptFilterOptions = z.object({
...paginationZod,
pathPrefix: z.string().optional(),
searchQuery: z.string().optional(),
+ searchType: z.array(TracingSearchType).optional(),
});
export const promptRouter = createTRPCRouter({
@@ -97,19 +127,10 @@ export const promptRouter = createTRPCRouter({
})()
: Prisma.empty;
- const searchFilter =
- input.searchQuery !== undefined &&
- input.searchQuery !== null &&
- input.searchQuery !== ""
- ? (() => {
- const q = input.searchQuery;
- return Prisma.sql` AND (
- p.name ILIKE ${`%${q}%`}
- OR EXISTS (SELECT 1 FROM UNNEST(p.tags) AS tag WHERE tag ILIKE ${`%${q}%`})
- OR p.prompt::text ILIKE ${`%${q}%`}
- )`;
- })()
- : Prisma.empty;
+ const searchFilter = buildPromptSearchFilter(
+ input.searchQuery,
+ input.searchType,
+ );
const [prompts, promptCount] = await Promise.all([
// prompts
@@ -159,7 +180,15 @@ export const promptRouter = createTRPCRouter({
};
}),
count: protectedProjectProcedure
- .input(z.object({ projectId: z.string() }))
+ .input(
+ z.object({
+ projectId: z.string(),
+ searchQuery: z.string().optional(),
+ searchType: z.array(TracingSearchType).optional(),
+ pathPrefix: z.string().optional(),
+ filter: z.array(singleFilter).optional(),
+ }),
+ )
.query(async ({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
@@ -167,14 +196,37 @@ export const promptRouter = createTRPCRouter({
scope: "prompts:read",
});
+ const filterCondition = input.filter
+ ? tableColumnsToSqlFilterAndPrefix(
+ input.filter,
+ promptsTableCols,
+ "prompts",
+ )
+ : Prisma.empty;
+
+ const pathFilter = input.pathPrefix
+ ? (() => {
+ const prefix = input.pathPrefix;
+ return Prisma.sql` AND (p.name LIKE ${`${prefix}/%`} OR p.name = ${prefix})`;
+ })()
+ : Prisma.empty;
+
+ const searchFilter = buildPromptSearchFilter(
+ input.searchQuery,
+ input.searchType,
+ );
+
const count = await ctx.prisma.$queryRaw<Array<{ totalCount: bigint }>>(
generatePromptQuery(
Prisma.sql` count(*) AS "totalCount"`,
input.projectId,
- Prisma.empty,
+ filterCondition,
Prisma.empty,
1, // limit
0, // page
+ pathFilter,
+ searchFilter,
+ input.pathPrefix,
),
);