🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(comments): add support for comment button on each trace preview in session view (#3848)
marliessophie2d265eb3f999
diff --git a/web/src/__tests__/comments.servertest.ts b/web/src/__tests__/async/comments-api.servertest.tssimilarity index 78%rename from web/src/__tests__/comments.servertest.tsrename to web/src/__tests__/async/comments-api.servertest.tsindex e08e2e4894..297d996ffb 100644--- a/web/src/__tests__/comments.servertest.ts+++ b/web/src/__tests__/async/comments-api.servertest.ts@@ -1,42 +1,43 @@/** @jest-environment node */-import {- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";import {GetCommentsV1Response,GetCommentV1Response,PostCommentsV1Response,} from "@/src/features/public-api/types/comments";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";import { prisma } from "@langfuse/shared/src/db";import { z } from "zod";+import {+ createObservationsCh,+ createTracesCh,+} from "@/src/__tests__/async/repositories/clickhouse-helpers";+import {+ createObservation,+ createTrace,+} from "@/src/__tests__/fixtures/tracing-factory";describe("Create and get comments", () => {- beforeEach(async () => await pruneDatabase());- afterEach(async () => await pruneDatabase());-- it("should create and get comment", async () => {- const traceResponse = await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {+ beforeAll(async () => {+ const traces = [+ createTrace({name: "trace-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- );+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ id: "1234",+ }),+ ];- const { id: traceId } = traceResponse.body;+ await createTracesCh(traces);+ });+ it("should create and get comment", async () => {const commentResponse = await makeZodVerifiedAPICall(PostCommentsV1Response,"POST","/api/public/comments",{content: "hello",- objectId: traceId,+ objectId: "1234",objectType: "TRACE",projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",authorUserId: "user-1",@@ -55,7 +56,7 @@ describe("Create and get comments", () => {expect(response.body).toMatchObject({id: commentId,projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- objectId: traceId,+ objectId: "1234",objectType: "TRACE",content: "hello",authorUserId: "user-1",@@ -80,25 +81,13 @@ describe("Create and get comments", () => {);} catch (error) {expect((error as Error).message).toBe(- `API call did not return 200, returned status 404, body {\"message\":\"No trace with id invalid-trace-id in project 7a88fb47-b4e2-43b8-a06c-a5ce950dc53a\",\"error\":\"LangfuseNotFoundError\"}`,+ `API call did not return 200, returned status 404, body {\"message\":\"Reference object, TRACE: invalid-trace-id not found in Clickhouse. Skipping creating comment.\",\"error\":\"LangfuseNotFoundError\"}`,);}});it("should fail to create comment if content is empty", async () => {try {- const traceResponse = await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- name: "trace-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- );-- const { id: traceId } = traceResponse.body;-await makeZodVerifiedAPICall(z.object({message: z.string(),@@ -108,7 +97,7 @@ describe("Create and get comments", () => {"/api/public/comments",{content: "",- objectId: traceId,+ objectId: "1234",objectType: "TRACE",projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",},@@ -122,18 +111,6 @@ describe("Create and get comments", () => {it("should fail to create comment if content is larger than 3000 characters", async () => {try {- const traceResponse = await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- name: "trace-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- );-- const { id: traceId } = traceResponse.body;-await makeZodVerifiedAPICall(z.object({message: z.string(),@@ -143,7 +120,7 @@ describe("Create and get comments", () => {"/api/public/comments",{content: "a".repeat(3001),- objectId: traceId,+ objectId: "1234",objectType: "TRACE",projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",},@@ -157,29 +134,28 @@ describe("Create and get comments", () => {});describe("GET /api/public/comments API Endpoint", () => {- beforeEach(async () => {- await pruneDatabase();-- const trace = await prisma.trace.create({- data: {- id: "trace-2021-01-01",- createdAt: new Date("2021-01-01T00:00:00Z"),- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ beforeAll(async () => {+ const traces = [+ createTrace({name: "trace-1",- },- });+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ id: "1234",+ }),+ ];- const generation = await prisma.observation.create({- data: {- id: "generation-2021-01-01",- createdAt: new Date("2021-01-01T00:00:00Z"),- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- traceId: trace.id,- name: "generation-1",- type: "GENERATION",- },+ await createTracesCh(traces);++ const observation = createObservation({+ name: "generation-1",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ id: "5678",+ type: "GENERATION",+ trace_id: "1234",});+ await createObservationsCh([observation]);++ await prisma.comment.deleteMany();await prisma.comment.createMany({data: [{@@ -187,7 +163,7 @@ describe("GET /api/public/comments API Endpoint", () => {createdAt: new Date("2021-01-01T00:00:00Z"),projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",content: "comment-1",- objectId: trace.id,+ objectId: "1234",objectType: "TRACE",authorUserId: "user-1",},@@ -196,7 +172,7 @@ describe("GET /api/public/comments API Endpoint", () => {createdAt: new Date("2021-02-01T00:00:00Z"),projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",content: "comment-2",- objectId: generation.id,+ objectId: "5678",objectType: "OBSERVATION",authorUserId: "user-1",},@@ -205,7 +181,7 @@ describe("GET /api/public/comments API Endpoint", () => {createdAt: new Date("2021-03-01T00:00:00Z"),projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",content: "comment-3",- objectId: trace.id,+ objectId: "1234",objectType: "TRACE",authorUserId: "user-1",},@@ -214,7 +190,7 @@ describe("GET /api/public/comments API Endpoint", () => {createdAt: new Date("2021-04-01T00:00:00Z"),projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",content: "comment-4",- objectId: trace.id,+ objectId: "1234",objectType: "TRACE",},{@@ -222,13 +198,12 @@ describe("GET /api/public/comments API Endpoint", () => {createdAt: new Date("2021-05-01T00:00:00Z"),projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",content: "comment-5",- objectId: trace.id,+ objectId: "1234",objectType: "TRACE",},],});});- afterEach(async () => await pruneDatabase());it("should return all comments", async () => {const comments = await makeZodVerifiedAPICall(@@ -240,7 +215,7 @@ describe("GET /api/public/comments API Endpoint", () => {});it("should return comments for a specific objectId and objectType", async () => {- const objectId = "trace-2021-01-01";+ const objectId = "1234";const objectType = "TRACE";const comments = await makeZodVerifiedAPICall(@@ -260,7 +235,7 @@ describe("GET /api/public/comments API Endpoint", () => {it("should return comments linked to a specific object and by a specific author", async () => {const authorUserId = "user-1";- const objectId = "trace-2021-01-01";+ const objectId = "1234";const objectType = "TRACE";const comments = await makeZodVerifiedAPICall(diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex 1556ed3ce4..7e29b1e50c 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -17,6 +17,7 @@ import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer"import { Button } from "@/src/components/ui/button";import useLocalStorage from "@/src/components/useLocalStorage";import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";+import { useSession } from "next-auth/react";import { ScrollScreenPage } from "@/src/components/layouts/scroll-screen-page";import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";@@ -28,6 +29,7 @@ export const SessionPage: React.FC<{projectId: string;}> = ({ sessionId, projectId }) => {const { setDetailPageList } = useDetailPageLists();+ const userSession = useSession();const [visibleTraces, setVisibleTraces] = useState(PAGE_SIZE);const session = api.sessions.byId.useQuery({@@ -60,15 +62,25 @@ export const SessionPage: React.FC<{string[]>("emptySelectedConfigIds", []);- const commentCounts = api.comments.getCountByObjectId.useQuery(+ const sessionCommentCounts = api.comments.getCountByObjectId.useQuery({projectId,objectId: sessionId,objectType: "SESSION",},- { enabled: session.isSuccess },+ { enabled: session.isSuccess && userSession.status === "authenticated" },);+ const traceCommentCounts =+ api.comments.getTraceCommentCountsBySessionId.useQuery(+ {+ projectId,+ sessionId,+ queryClickhouse: useClickhouse(),+ },+ { enabled: session.isSuccess && userSession.status === "authenticated" },+ );+if (session.error?.data?.code === "UNAUTHORIZED")return <ErrorPage message="You do not have access to this session." />;@@ -122,7 +134,7 @@ export const SessionPage: React.FC<{projectId={projectId}objectId={sessionId}objectType="SESSION"- count={commentCounts.data?.get(sessionId)}+ count={sessionCommentCounts.data?.get(sessionId)}/>,]}/>@@ -169,17 +181,26 @@ export const SessionPage: React.FC<{<div className="mb-1 flex flex-wrap content-start items-start gap-1"><GroupedScoreBadges scores={trace.scores} /></div>- <AnnotateDrawer- projectId={projectId}- traceId={trace.id}- scores={trace.scores}- emptySelectedConfigIds={emptySelectedConfigIds}- setEmptySelectedConfigIds={setEmptySelectedConfigIds}- variant="badge"- type="session"- source="SessionDetail"- key={"annotation-drawer" + trace.id}- />+ <div className="flex items-center gap-1">+ <AnnotateDrawer+ projectId={projectId}+ traceId={trace.id}+ scores={trace.scores}+ emptySelectedConfigIds={emptySelectedConfigIds}+ setEmptySelectedConfigIds={setEmptySelectedConfigIds}+ variant="badge"+ type="session"+ source="SessionDetail"+ key={"annotation-drawer" + trace.id}+ />+ <CommentDrawerButton+ projectId={projectId}+ objectId={trace.id}+ objectType="TRACE"+ count={traceCommentCounts.data?.get(trace.id)}+ className="h-6 rounded-full text-xs"+ />+ </div></div></Card>))}diff --git a/web/src/features/comments/CommentDrawerButton.tsx b/web/src/features/comments/CommentDrawerButton.tsxindex 72defa952e..7d0667199e 100644--- a/web/src/features/comments/CommentDrawerButton.tsx+++ b/web/src/features/comments/CommentDrawerButton.tsx@@ -20,12 +20,14 @@ export function CommentDrawerButton({objectType,count,variant = "secondary",+ className,}: {projectId: string;objectId: string;objectType: CommentObjectType;count?: number;variant?: "secondary" | "outline";+ className?: string;}) {const hasReadAccess = useHasProjectAccess({projectId,@@ -38,7 +40,7 @@ export function CommentDrawerButton({if (!hasReadAccess || (!hasWriteAccess && !count))return (- <Button type="button" variant="secondary" disabled>+ <Button type="button" variant="secondary" className={className} disabled><MessageCircleOff className="h-4 w-4 text-muted-foreground" /></Button>);@@ -46,7 +48,12 @@ export function CommentDrawerButton({return (<Drawer><DrawerTrigger asChild>- <Button type="button" variant={variant} size="icon">+ <Button+ type="button"+ variant={variant}+ size="icon"+ className={className}+ >{!!count ? (<CommentCountIcon count={count} />) : (diff --git a/web/src/features/comments/CommentList.tsx b/web/src/features/comments/CommentList.tsxindex edffe1c15d..14100abc9a 100644--- a/web/src/features/comments/CommentList.tsx+++ b/web/src/features/comments/CommentList.tsx@@ -56,7 +56,7 @@ export function CommentList({objectId,objectType,},- { enabled: hasReadAccess },+ { enabled: hasReadAccess && session.status === "authenticated" },);const form = useForm<z.infer<typeof CreateCommentData>>({@@ -96,7 +96,11 @@ export function CommentList({}));}, [comments.data]);- if (!hasReadAccess || (!hasWriteAccess && comments.data?.length === 0))+ if (+ !hasReadAccess ||+ (!hasWriteAccess && comments.data?.length === 0) ||+ session.status !== "authenticated"+ )return null;function onSubmit(values: z.infer<typeof CreateCommentData>) {@@ -192,7 +196,7 @@ export function CommentList({.map((word) => word[0]).slice(0, 2).concat("")- : comment.authorUserId ?? "U"}+ : (comment.authorUserId ?? "U")}</AvatarFallback></Avatar><div className="relative rounded-md border">diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.tsindex 62da5f5436..d7d2e40a6b 100644--- a/web/src/features/comments/validateCommentReferenceObject.ts+++ b/web/src/features/comments/validateCommentReferenceObject.ts@@ -4,6 +4,7 @@ import {type CreateCommentData,} from "@langfuse/shared";import { type z } from "zod";+import { getObservationById, getTraceById } from "@langfuse/shared/src/server";type PrismaModelName = keyof Omit<PrismaClient,@@ -31,6 +32,13 @@ const COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL: Record<[CommentObjectType.PROMPT]: "prompt",} as const;+const isObservationOrTrace = (objectType: CommentObjectType) => {+ return (+ objectType === CommentObjectType.OBSERVATION ||+ objectType === CommentObjectType.TRACE+ );+};+export const validateCommentReferenceObject = async ({ctx,input,@@ -39,27 +47,42 @@ export const validateCommentReferenceObject = async ({input: z.infer<typeof CreateCommentData>;}): Promise<{ errorMessage?: string }> => {const { objectId, objectType, projectId } = input;- const prismaModel = COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL[objectType];- if (!prismaModel) {- return {- errorMessage: `No prisma model for object type ${objectType}`,- };- }+ if (isObservationOrTrace(objectType)) {+ let clickhouseObject;+ if (objectType === CommentObjectType.OBSERVATION) {+ clickhouseObject = await getObservationById(objectId, projectId);+ } else {+ clickhouseObject = await getTraceById(objectId, projectId);+ }- const model = ctx.prisma[prismaModel];- const object = await model.findFirst({- where: {- id: objectId,- projectId,- },- });+ return !!clickhouseObject+ ? {}+ : {+ errorMessage: `Reference object, ${objectType}: ${objectId} not found in Clickhouse. Skipping creating comment.`,+ };+ } else {+ const prismaModel = COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL[objectType];- if (!object) {- return {- errorMessage: `No ${prismaModel} with id ${objectId} in project ${projectId}`,- };- }+ if (!prismaModel) {+ return {+ errorMessage: `No prisma model for object type ${objectType}`,+ };+ }++ const model = ctx.prisma[prismaModel];+ const object = await model.findFirst({+ where: {+ id: objectId,+ projectId,+ },+ });- return {};+ if (!object) {+ return {+ errorMessage: `No ${prismaModel} with id ${objectId} in project ${projectId}`,+ };+ }+ return {};+ }};diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.tsindex 788b5e2d3c..1964c97ac3 100644--- a/web/src/server/api/routers/comments.ts+++ b/web/src/server/api/routers/comments.ts@@ -10,6 +10,8 @@ import { Prisma, CreateCommentData, DeleteCommentData } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";import { TRPCError } from "@trpc/server";import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";+import { getTracesIdentifierForSession } from "@langfuse/shared/src/server";export const commentsRouter = createTRPCRouter({create: protectedProjectProcedure@@ -180,35 +182,6 @@ export const commentsRouter = createTRPCRouter({});}}),- // deprecated procedure, returns empty map, kept to prevent caching issues- getCountsByObjectIds: protectedProjectProcedure- .input(- z.object({- projectId: z.string(),- objectIds: z.array(z.string()),- objectType: z.nativeEnum(CommentObjectType),- }),- )- .query(async ({ input, ctx }) => {- try {- throwIfNoProjectAccess({- session: ctx.session,- projectId: input.projectId,- scope: "comments:read",- });-- return new Map();- } catch (error) {- console.error(error);- if (error instanceof TRPCError) {- throw error;- }- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "Fetching comment count by object id failed.",- });- }- }),getCountByObjectId: protectedProjectProcedure.input(z.object({@@ -288,4 +261,90 @@ export const commentsRouter = createTRPCRouter({});}}),+ getTraceCommentCountsBySessionId: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ sessionId: z.string(),+ queryClickhouse: z.boolean().default(false),+ }),+ )+ .query(async ({ input, ctx }) => {+ try {+ return await measureAndReturnApi({+ input,+ operation: "comments.getTraceCommentCountsBySessionId",+ user: ctx.session.user ?? undefined,+ pgExecution: async () => {+ const session = await ctx.prisma.traceSession.findFirst({+ where: {+ id: input.sessionId,+ projectId: input.projectId,+ },+ include: {+ traces: {+ select: {+ id: true,+ },+ },+ },+ });+ if (!session) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Session not found in project",+ });+ }++ const allTraceCommentCounts = await ctx.prisma.$queryRaw<+ Array<{ objectId: string; count: bigint }>+ >`+ SELECT object_id as "objectId", COUNT(*) as count+ FROM comments+ WHERE project_id = ${input.projectId}+ AND object_type = 'TRACE'+ GROUP BY object_id+ `;++ const traceIds = new Set(+ session.traces.map((t: { id: string }) => t.id),+ );+ return new Map(+ allTraceCommentCounts+ .filter((c) => traceIds.has(c.objectId))+ .map(({ objectId, count }) => [objectId, Number(count)]),+ );+ },+ clickhouseExecution: async () => {+ const clickhouseTraces = await getTracesIdentifierForSession(+ input.projectId,+ input.sessionId,+ );++ const allTraceCommentCounts = await ctx.prisma.$queryRaw<+ Array<{ objectId: string; count: bigint }>+ >`+ SELECT object_id as "objectId", COUNT(*) as count+ FROM comments+ WHERE project_id = ${input.projectId}+ AND object_type = 'TRACE'+ GROUP BY object_id+ `;++ const traceIds = new Set(clickhouseTraces.map((t) => t.id));+ return new Map(+ allTraceCommentCounts+ .filter((c) => traceIds.has(c.objectId))+ .map(({ objectId, count }) => [objectId, Number(count)]),+ );+ },+ });+ } catch (e) {+ console.error(e);+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Unable to get trace comment counts by session id",+ });+ }+ }),});