Skip to content

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

feat(annotation-queues): add support for batch adding sessions to annotation queues (#8169)

marliessophie49343b9a0c27
diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.ts
index dceda6924c..f4ba0b9bb6 100644
--- a/packages/shared/src/features/batchAction/types.ts
+++ b/packages/shared/src/features/batchAction/types.ts
@@ -14,6 +14,7 @@ const ActionIdSchema = z.enum([
"score-delete",
"trace-delete",
"trace-add-to-annotation-queue",
+ "session-add-to-annotation-queue",
]);
export type ActionId = z.infer<typeof ActionIdSchema>;
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index ae2c341818..c63d184360 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -116,6 +116,15 @@ export const BatchActionProcessingEventSchema = z.discriminatedUnion(
targetId: z.string().optional(),
type: z.enum(BatchActionType),
}),
+ z.object({
+ actionId: z.literal("session-add-to-annotation-queue"),
+ projectId: z.string(),
+ query: BatchActionQuerySchema,
+ tableName: z.enum(BatchTableNames),
+ cutoffCreatedAt: z.date(),
+ targetId: z.string().optional(),
+ type: z.enum(BatchActionType),
+ }),
z.object({
actionId: z.literal("eval-create"),
targetObject: z.enum(["trace", "dataset"]),
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index ae78a8b1ea..23194a2e6f 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -11,6 +11,8 @@ import {
sessionsTableColsWithOptions,
BatchExportTableName,
TableViewPresetTableName,
+ AnnotationQueueObjectType,
+ BatchActionType,
} from "@langfuse/shared";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
@@ -19,9 +21,8 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
import { type RouterOutput } from "@/src/utils/types";
import type Decimal from "decimal.js";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
-import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { useDebounce } from "@/src/hooks/useDebounce";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
@@ -43,6 +44,12 @@ import {
getScoreGroupColumnProps,
verifyAndPrefixScoreDataAgainstKeys,
} from "@/src/features/scores/components/ScoreDetailColumnHelpers";
+import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";
+import { type TableAction } from "@/src/features/table/types";
+import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
+import { type RowSelectionState } from "@tanstack/react-table";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
export type SessionTableRow = {
id: string;
@@ -76,6 +83,7 @@ export default function SessionsTable({
const { setDetailPageList } = useDetailPageLists();
const { selectedOption, dateRange, setDateRangeAndOption } =
useTableDateRange(projectId);
+ const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const [userFilterState, setUserFilterState] = useQueryFilterState(
[],
@@ -134,6 +142,8 @@ export default function SessionsTable({
environmentFilter,
);
+ const { selectAll, setSelectAll } = useSelectAll(projectId, "sessions");
+
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
@@ -164,6 +174,19 @@ export default function SessionsTable({
const sessions = api.sessions.all.useQuery(payloadGetAll);
const sessionCountQuery = api.sessions.countAll.useQuery(payloadCount);
+ const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
+ onSuccess: (data) => {
+ showSuccessToast({
+ title: "Sessions added to queue",
+ description: `Selected sessions will be added to queue "${data.queueName}". This may take a minute.`,
+ link: {
+ href: `/project/${projectId}/annotation-queues/${data.queueId}`,
+ text: `View queue "${data.queueName}"`,
+ },
+ });
+ },
+ });
+
const { scoreColumns, scoreKeysAndProps, isColumnLoading } =
useIndividualScoreColumns<SessionTableRow>({
projectId,
@@ -222,7 +245,53 @@ export default function SessionsTable({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sessions.isSuccess, sessions.data]);
+ const { selectActionColumn } = TableSelectionManager<SessionTableRow>({
+ projectId,
+ tableName: "sessions",
+ setSelectedRows,
+ });
+
+ const handleAddToAnnotationQueue = async ({
+ projectId,
+ targetId,
+ }: {
+ projectId: string;
+ targetId: string;
+ }) => {
+ const selectedSessionIds = Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((t) => t.id).includes(sessionId),
+ );
+
+ await addToQueueMutation.mutateAsync({
+ projectId,
+ objectIds: selectedSessionIds,
+ objectType: AnnotationQueueObjectType.SESSION,
+ queueId: targetId,
+ isBatchAction: selectAll,
+ query: {
+ filter: filterState,
+ orderBy: orderByState,
+ },
+ });
+ setSelectedRows({});
+ };
+
+ const tableActions: TableAction[] = [
+ {
+ id: "session-add-to-annotation-queue",
+ type: BatchActionType.Create,
+ label: "Add to Annotation Queue",
+ description: "Add selected sessions to an annotation queue.",
+ targetLabel: "Annotation Queue",
+ execute: handleAddToAnnotationQueue,
+ accessCheck: {
+ scope: "annotationQueues:CUD",
+ },
+ },
+ ];
+
const columns: LangfuseColumnDef<SessionTableRow>[] = [
+ selectActionColumn,
{
accessorKey: "bookmarked",
id: "bookmarked",
@@ -561,6 +630,18 @@ export default function SessionsTable({
filterColumnDefinition={transformFilterOptions()}
filterState={userFilterState}
setFilterState={useDebounce(setUserFilterState)}
+ actionButtons={[
+ Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((s) => s.id).includes(sessionId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="sessions-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Sessions}
+ />
+ ) : null,
+ ]}
columns={columns}
columnVisibility={columnVisibility}
setColumnVisibility={setColumnVisibility}
@@ -571,18 +652,21 @@ export default function SessionsTable({
projectId,
controllers: viewControllers,
}}
- actionButtons={[
- <BatchExportTableButton
- {...{ projectId, filterState, orderByState }}
- tableName={BatchExportTableName.Sessions}
- key="batchExport"
- />,
- ]}
selectedOption={selectedOption}
setDateRangeAndOption={setDateRangeAndOption}
columnsWithCustomSelect={["userIds"]}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((sessionId) =>
+ sessions.data?.sessions.map((s) => s.id).includes(sessionId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
environmentFilter={{
values: selectedEnvironments,
onValueChange: setSelectedEnvironments,
@@ -641,6 +725,8 @@ export default function SessionsTable({
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
help={{
description:
"A session is a collection of related traces, such as a conversation or thread. To begin, add a sessionId to the trace.",
diff --git a/web/src/features/annotation-queues/server/annotationQueueItems.ts b/web/src/features/annotation-queues/server/annotationQueueItems.ts
index 70d077763b..5680660289 100644
--- a/web/src/features/annotation-queues/server/annotationQueueItems.ts
+++ b/web/src/features/annotation-queues/server/annotationQueueItems.ts
@@ -6,12 +6,14 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import {
+ type ActionId,
type AnnotationQueueItem,
AnnotationQueueObjectType,
AnnotationQueueStatus,
BatchActionQuerySchema,
BatchActionType,
BatchExportTableName,
+ type BatchTableNames,
paginationZod,
Prisma,
} from "@langfuse/shared";
@@ -31,6 +33,20 @@ const isItemLocked = (item: AnnotationQueueItem) => {
);
};
+const MAP_OBJECT_TYPE_TO_ACTION_PROPS: Record<
+ "TRACE" | "SESSION",
+ { actionId: ActionId; tableName: BatchTableNames }
+> = {
+ [AnnotationQueueObjectType.TRACE]: {
+ actionId: "trace-add-to-annotation-queue",
+ tableName: BatchExportTableName.Traces,
+ },
+ [AnnotationQueueObjectType.SESSION]: {
+ actionId: "session-add-to-annotation-queue",
+ tableName: BatchExportTableName.Sessions,
+ },
+};
+
export const queueItemRouter = createTRPCRouter({
typeById: protectedProjectProcedure
.input(
@@ -269,11 +285,22 @@ export const queueItemRouter = createTRPCRouter({
let createdCount = 0;
if (input.isBatchAction && input.query) {
+ const actionProps =
+ MAP_OBJECT_TYPE_TO_ACTION_PROPS[
+ input.objectType as "TRACE" | "SESSION"
+ ];
+ if (!actionProps) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Batch action not supported for object type: ${input.objectType}`,
+ });
+ }
+ const { actionId, tableName } = actionProps;
await createBatchActionJob({
projectId: input.projectId,
- actionId: "trace-add-to-annotation-queue",
+ actionId,
actionType: BatchActionType.Create,
- tableName: BatchExportTableName.Traces,
+ tableName,
session: ctx.session,
query: input.query,
targetId: input.queueId,
diff --git a/web/src/features/table/components/targetOptionsQueryMap.tsx b/web/src/features/table/components/targetOptionsQueryMap.tsx
index c31828f9f9..0216e8aafc 100644
--- a/web/src/features/table/components/targetOptionsQueryMap.tsx
+++ b/web/src/features/table/components/targetOptionsQueryMap.tsx
@@ -2,4 +2,6 @@ import { api } from "@/src/utils/api";
export const targetOptionsQueryMap = {
"trace-add-to-annotation-queue": api.annotationQueues.allNamesAndIds.useQuery,
+ "session-add-to-annotation-queue":
+ api.annotationQueues.allNamesAndIds.useQuery,
} as const;
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index 928b4fab39..96f0a0d7da 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -19,7 +19,10 @@ import {
import { processClickhouseTraceDelete } from "../traces/processClickhouseTraceDelete";
import { env } from "../../env";
import { Job } from "bullmq";
-import { processAddToQueue } from "./processAddToQueue";
+import {
+ processAddSessionsToQueue,
+ processAddTracesToQueue,
+} from "./processAddToQueue";
import { processPostgresTraceDelete } from "../traces/processPostgresTraceDelete";
import { prisma } from "@langfuse/shared/src/db";
import { randomUUID } from "node:crypto";
@@ -55,7 +58,15 @@ async function processActionChunk(
break;
case "trace-add-to-annotation-queue":
- await processAddToQueue(projectId, chunkIds, targetId as string);
+ await processAddTracesToQueue(projectId, chunkIds, targetId as string);
+ break;
+
+ case "session-add-to-annotation-queue":
+ await processAddSessionsToQueue(
+ projectId,
+ chunkIds,
+ targetId as string,
+ );
break;
case "score-delete":
@@ -133,6 +144,7 @@ export const handleBatchActionJob = async (
if (
actionId === "trace-delete" ||
actionId === "trace-add-to-annotation-queue" ||
+ actionId === "session-add-to-annotation-queue" ||
actionId === "score-delete"
) {
const { projectId, tableName, query, cutoffCreatedAt, targetId, type } =
@@ -157,7 +169,7 @@ export const handleBatchActionJob = async (
cutoffCreatedAt: new Date(cutoffCreatedAt),
filter: convertDatesInFiltersFromStrings(query.filter ?? []),
orderBy: query.orderBy,
- tableName: tableName,
+ tableName: tableName as BatchTableNames,
searchQuery: query.searchQuery ?? undefined,
searchType: query.searchType ?? ["id" as const],
});
diff --git a/worker/src/features/batchAction/processAddToQueue.ts b/worker/src/features/batchAction/processAddToQueue.ts
index 89f92ba9aa..bbd6098324 100644
--- a/worker/src/features/batchAction/processAddToQueue.ts
+++ b/worker/src/features/batchAction/processAddToQueue.ts
@@ -1,7 +1,48 @@
import { logger, traceException } from "@langfuse/shared/src/server";
-import { prisma } from "@langfuse/shared/src/db";
+import { AnnotationQueueObjectType, prisma } from "@langfuse/shared/src/db";
-export const processAddToQueue = async (
+const addToQueue = async ({
+ projectId,
+ objectIds,
+ objectType,
+ targetId,
+}: {
+ projectId: string;
+ objectIds: string[];
+ objectType: AnnotationQueueObjectType;
+ targetId: string;
+}) => {
+ // cannot use prisma `createMany` operation as we do not have unique constraint enforced on schema level
+ // conflict must be handled on query level by reading existing items and filtering out traces that already exist
+
+ // First get existing items
+ const existingItems = await prisma.annotationQueueItem.findMany({
+ where: {
+ projectId,
+ queueId: targetId,
+ objectId: { in: objectIds },
+ objectType,
+ },
+ select: { objectId: true },
+ });
+
+ // Filter out objects that already exist
+ const existingObjectIds = new Set(existingItems.map((item) => item.objectId));
+ const newObjectIds = objectIds.filter((id) => !existingObjectIds.has(id));
+
+ if (newObjectIds.length > 0) {
+ await prisma.annotationQueueItem.createMany({
+ data: newObjectIds.map((objectId) => ({
+ projectId,
+ queueId: targetId,
+ objectId,
+ objectType,
+ })),
+ });
+ }
+};
+
+export const processAddTracesToQueue = async (
projectId: string,
traceIds: string[],
targetId: string,
@@ -10,39 +51,41 @@ export const processAddToQueue = async (
`Adding traces ${JSON.stringify(traceIds)} to annotation queue ${targetId} in project ${projectId}`,
);
try {
- // cannot use prisma `createMany` operation as we do not have unique constraint enforced on schema level
- // conflict must be handled on query level by reading existing items and filtering out traces that already exist
-
- // First get existing items
- const existingItems = await prisma.annotationQueueItem.findMany({
- where: {
- projectId,
- queueId: targetId,
- objectId: { in: traceIds },
- objectType: "TRACE",
- },
- select: { objectId: true },
+ await addToQueue({
+ projectId,
+ objectIds: traceIds,
+ objectType: AnnotationQueueObjectType.TRACE,
+ targetId,
});
-
- // Filter out traces that already exist
- const existingTraceIds = new Set(
- existingItems.map((item) => item.objectId),
+ } catch (e) {
+ logger.error(
+ `Error adding traces ${JSON.stringify(traceIds)} to annotation queue ${targetId} in project ${projectId}`,
+ e,
);
- const newTraceIds = traceIds.filter((id) => !existingTraceIds.has(id));
+ traceException(e);
+ throw e;
+ }
+};
- if (newTraceIds.length > 0) {
- await prisma.annotationQueueItem.createMany({
- data: newTraceIds.map((traceId) => ({
- projectId,
- queueId: targetId,
- objectId: traceId,
- objectType: "TRACE",
- })),
- });
- }
+export const processAddSessionsToQueue = async (
+ projectId: string,
+ sessionIds: string[],
+ targetId: string,
+) => {
+ logger.info(
+ `Adding sessions ${JSON.stringify(sessionIds)} to annotation queue ${targetId} in project ${projectId}`,
+ );
+
+ try {
+ await addToQueue({
+ projectId,
+ objectIds: sessionIds,
+ objectType: AnnotationQueueObjectType.SESSION,
+ targetId,
+ });
} catch (e) {
logger.error(
- `Error adding traces ${JSON.stringify(traceIds)} to annotation queue ${targetId} in project ${projectId}`,
+ `Error adding sessions ${JSON.stringify(sessionIds)} to annotation queue ${targetId} in project ${projectId}`,
e,
);
traceException(e);