🪢 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(api): POST /comments GET /comments GET /comments/${commentId} (#3383)
marliessophie7babcbd17007
diff --git a/fern/apis/server/definition/comments.yml b/fern/apis/server/definition/comments.ymlnew file mode 100644index 0000000000..59577e5ef7--- /dev/null+++ b/fern/apis/server/definition/comments.yml@@ -0,0 +1,73 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ pagination: ./utils/pagination.yml+ commons: ./commons.yml+service:+ auth: true+ base-path: /api/public+ endpoints:+ create:+ docs: Create a comment. Comments may be attached to different object types (trace, observation, session, prompt).+ method: POST+ path: /comments+ request: CreateCommentRequest+ response: CreateCommentResponse+ get:+ docs: Get all comments+ method: GET+ path: /comments+ request:+ name: GetCommentsRequest+ query-parameters:+ page:+ type: optional<integer>+ docs: Page number, starts at 1.+ limit:+ type: optional<integer>+ docs: Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit+ objectType:+ type: optional<string>+ docs: Filter comments by object type (trace, observation, session, prompt).+ objectId:+ type: optional<string>+ docs: Filter comments by object id. If objectType is not provided, an error will be thrown.+ authorUserId:+ type: optional<string>+ docs: Filter comments by author user id.+ response: GetCommentsResponse+ get-by-id:+ docs: Get a comment by id+ method: GET+ path: /comments/{commentId}+ path-parameters:+ commentId:+ type: string+ docs: The unique langfuse identifier of a comment+ response: commons.Comment+types:+ CreateCommentRequest:+ properties:+ projectId:+ type: string+ docs: The id of the project to attach the comment to.+ objectType:+ type: string+ docs: The type of the object to attach the comment to (trace, observation, session, prompt).+ objectId:+ type: string+ docs: The id of the object to attach the comment to. If this does not reference a valid existing object, an error will be thrown.+ content:+ type: string+ docs: The content of the comment. May include markdown. Currently limited to 500 characters.+ authorUserId:+ type: optional<string>+ docs: The id of the user who created the comment.+ CreateCommentResponse:+ properties:+ id:+ type: string+ docs: The id of the created object in Langfuse+ GetCommentsResponse:+ properties:+ data: list<commons.Comment>+ meta: pagination.MetaResponsediff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex 44f0c5d40c..aff797aa34 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -286,6 +286,18 @@ types:- double- stringdocs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores++ Comment:+ properties:+ id: string+ projectId: string+ createdAt: datetime+ updatedAt: datetime+ objectType: CommentObjectType+ objectId: string+ content: string+ authorUserId: optional<string>+Dataset:properties:id: string@@ -405,6 +417,12 @@ types:- optional<integer>- optional<boolean>- optional<list<string>>+ CommentObjectType:+ enum:+ - TRACE+ - OBSERVATION+ - SESSION+ - PROMPTDatasetStatus:enum:- ACTIVEdiff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 0c1a63cc87..bf0f7174de 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -24,6 +24,183 @@ info:- Postman collection:https://cloud.langfuse.com/generated/postman/collection.jsonpaths:+ /api/public/comments:+ post:+ description: >-+ Create a comment. Comments may be attached to different object types+ (trace, observation, session, prompt).+ operationId: comments_create+ tags:+ - Comments+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateCommentResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateCommentRequest'+ get:+ description: Get all comments+ operationId: comments_get+ tags:+ - Comments+ parameters:+ - name: page+ in: query+ description: Page number, starts at 1.+ required: false+ schema:+ type: integer+ nullable: true+ - name: limit+ in: query+ description: >-+ Limit of items per page. If you encounter api issues due to too+ large page sizes, try to reduce the limit+ required: false+ schema:+ type: integer+ nullable: true+ - name: objectType+ in: query+ description: >-+ Filter comments by object type (trace, observation, session,+ prompt).+ required: false+ schema:+ type: string+ nullable: true+ - name: objectId+ in: query+ description: >-+ Filter comments by object id. If objectType is not provided, an+ error will be thrown.+ required: false+ schema:+ type: string+ nullable: true+ - name: authorUserId+ in: query+ description: Filter comments by author user id.+ required: false+ schema:+ type: string+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/GetCommentsResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ /api/public/comments/{commentId}:+ get:+ description: Get a comment by id+ operationId: comments_get-by-id+ tags:+ - Comments+ parameters:+ - name: commentId+ in: path+ description: The unique langfuse identifier of a comment+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Comment'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []/api/public/dataset-items:post:description: Create a dataset item@@ -2038,6 +2215,59 @@ paths:- BasicAuth: []components:schemas:+ CreateCommentRequest:+ title: CreateCommentRequest+ type: object+ properties:+ projectId:+ type: string+ description: The id of the project to attach the comment to.+ objectType:+ type: string+ description: >-+ The type of the object to attach the comment to (trace, observation,+ session, prompt).+ objectId:+ type: string+ description: >-+ The id of the object to attach the comment to. If this does not+ reference a valid existing object, an error will be thrown.+ content:+ type: string+ description: >-+ The content of the comment. May include markdown. Currently limited+ to 500 characters.+ authorUserId:+ type: string+ nullable: true+ description: The id of the user who created the comment.+ required:+ - projectId+ - objectType+ - objectId+ - content+ CreateCommentResponse:+ title: CreateCommentResponse+ type: object+ properties:+ id:+ type: string+ description: The id of the created object in Langfuse+ required:+ - id+ GetCommentsResponse:+ title: GetCommentsResponse+ type: object+ properties:+ data:+ type: array+ items:+ $ref: '#/components/schemas/Comment'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'+ required:+ - data+ - metaTrace:title: Tracetype: object@@ -2571,6 +2801,37 @@ components:description: >-The value of the score. Must be passed as string for categorical scores,and numeric for boolean and numeric scores+ Comment:+ title: Comment+ type: object+ properties:+ id:+ type: string+ projectId:+ type: string+ createdAt:+ type: string+ format: date-time+ updatedAt:+ type: string+ format: date-time+ objectType:+ $ref: '#/components/schemas/CommentObjectType'+ objectId:+ type: string+ content:+ type: string+ authorUserId:+ type: string+ nullable: true+ required:+ - id+ - projectId+ - createdAt+ - updatedAt+ - objectType+ - objectId+ - contentDataset:title: Datasettype: object@@ -2814,6 +3075,14 @@ components:items:type: stringnullable: true+ CommentObjectType:+ title: CommentObjectType+ type: string+ enum:+ - TRACE+ - OBSERVATION+ - SESSION+ - PROMPTDatasetStatus:title: DatasetStatustype: stringdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 349a180713..b13ed0bbc3 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -37,6 +37,129 @@]},"item": [+ {+ "_type": "container",+ "description": null,+ "name": "Comments",+ "item": [+ {+ "_type": "endpoint",+ "name": "Create",+ "request": {+ "description": "Create a comment. Comments may be attached to different object types (trace, observation, session, prompt).",+ "url": {+ "raw": "{{baseUrl}}/api/public/comments",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "comments"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "POST",+ "auth": null,+ "body": {+ "mode": "raw",+ "raw": "{\n \"projectId\": \"example\",\n \"objectType\": \"example\",\n \"objectId\": \"example\",\n \"content\": \"example\",\n \"authorUserId\": \"example\"\n}",+ "options": {+ "raw": {+ "language": "json"+ }+ }+ }+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Get",+ "request": {+ "description": "Get all comments",+ "url": {+ "raw": "{{baseUrl}}/api/public/comments?page=&limit=&objectType=&objectId=&authorUserId=",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "comments"+ ],+ "query": [+ {+ "key": "page",+ "value": "",+ "description": "Page number, starts at 1."+ },+ {+ "key": "limit",+ "value": "",+ "description": "Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit"+ },+ {+ "key": "objectType",+ "value": "",+ "description": "Filter comments by object type (trace, observation, session, prompt)."+ },+ {+ "key": "objectId",+ "value": "",+ "description": "Filter comments by object id. If objectType is not provided, an error will be thrown."+ },+ {+ "key": "authorUserId",+ "value": "",+ "description": "Filter comments by author user id."+ }+ ],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Get By Id",+ "request": {+ "description": "Get a comment by id",+ "url": {+ "raw": "{{baseUrl}}/api/public/comments/:commentId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "comments",+ ":commentId"+ ],+ "query": [],+ "variable": [+ {+ "key": "commentId",+ "value": "",+ "description": "The unique langfuse identifier of a comment"+ }+ ]+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ }+ ]+ },{"_type": "container","description": null,diff --git a/web/src/__tests__/comments.servertest.ts b/web/src/__tests__/comments.servertest.tsnew file mode 100644index 0000000000..a70d546db3--- /dev/null+++ b/web/src/__tests__/comments.servertest.ts@@ -0,0 +1,267 @@+/** @jest-environment node */++import {+ makeZodVerifiedAPICall,+ pruneDatabase,+} 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";++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",+ {+ name: "trace-name",+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ },+ );++ const { id: traceId } = traceResponse.body;++ const commentResponse = await makeZodVerifiedAPICall(+ PostCommentsV1Response,+ "POST",+ "/api/public/comments",+ {+ content: "hello",+ objectId: traceId,+ objectType: "TRACE",+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ authorUserId: "user-1",+ },+ );++ const { id: commentId } = commentResponse.body;++ const response = await makeZodVerifiedAPICall(+ GetCommentV1Response,+ "GET",+ `/api/public/comments/${commentId}`,+ );++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({+ id: commentId,+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ objectId: traceId,+ objectType: "TRACE",+ content: "hello",+ authorUserId: "user-1",+ });+ });++ it("should fail to create comment if reference object does not exist", async () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "POST",+ "/api/public/comments",+ {+ content: "hello",+ objectId: "invalid-trace-id",+ objectType: "TRACE",+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ },+ );+ } 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\"}`,+ );+ }+ });+});++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",+ name: "trace-1",+ },+ });++ 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 prisma.comment.createMany({+ data: [+ {+ id: "comment-2021-01-01",+ createdAt: new Date("2021-01-01T00:00:00Z"),+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ content: "comment-1",+ objectId: trace.id,+ objectType: "TRACE",+ authorUserId: "user-1",+ },+ {+ id: "comment-2021-02-01",+ createdAt: new Date("2021-02-01T00:00:00Z"),+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ content: "comment-2",+ objectId: generation.id,+ objectType: "OBSERVATION",+ authorUserId: "user-1",+ },+ {+ id: "comment-2021-03-01",+ createdAt: new Date("2021-03-01T00:00:00Z"),+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ content: "comment-3",+ objectId: trace.id,+ objectType: "TRACE",+ authorUserId: "user-1",+ },+ {+ id: "comment-2021-04-01",+ createdAt: new Date("2021-04-01T00:00:00Z"),+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ content: "comment-4",+ objectId: trace.id,+ objectType: "TRACE",+ },+ {+ id: "comment-2021-05-01",+ createdAt: new Date("2021-05-01T00:00:00Z"),+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ content: "comment-5",+ objectId: trace.id,+ objectType: "TRACE",+ },+ ],+ });+ });+ afterEach(async () => await pruneDatabase());++ it("should return all comments", async () => {+ const comments = await makeZodVerifiedAPICall(+ GetCommentsV1Response,+ "GET",+ "/api/public/comments",+ );+ expect(comments.body.data).toHaveLength(5);+ });++ it("should return comments for a specific objectId and objectType", async () => {+ const objectId = "trace-2021-01-01";+ const objectType = "TRACE";++ const comments = await makeZodVerifiedAPICall(+ GetCommentsV1Response,+ "GET",+ `/api/public/comments?objectType=${objectType}&objectId=${objectId}`,+ );++ expect(comments.body.data).toHaveLength(4);+ expect(comments.body.data.map((comment) => comment.id)).toEqual([+ "comment-2021-01-01",+ "comment-2021-03-01",+ "comment-2021-04-01",+ "comment-2021-05-01",+ ]);+ });++ 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 objectType = "TRACE";++ const comments = await makeZodVerifiedAPICall(+ GetCommentsV1Response,+ "GET",+ `/api/public/comments?objectType=${objectType}&objectId=${objectId}&authorUserId=${authorUserId}`,+ );++ expect(comments.body.data).toHaveLength(2);+ expect(comments.body.data.map((comment) => comment.id)).toEqual([+ "comment-2021-01-01",+ "comment-2021-03-01",+ ]);+ });++ it("should return an empty array when no comments match the criteria", async () => {+ const comments = await makeZodVerifiedAPICall(+ GetCommentsV1Response,+ "GET",+ "/api/public/comments?authorUserId=non-existent-user",+ );++ expect(comments.body.data).toHaveLength(0);+ });++ it("should throw 400 error with descriptive error message if objectType is provided but invalid", async () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "GET",+ "/api/public/comments?objectType=INVALID_TYPE",+ );+ } catch (error) {+ expect((error as Error).message).toContain(+ "API call did not return 200, returned status 400",+ );+ }+ });++ it("should return all trace comments if objectType is provided and objectId is not", async () => {+ const comments = await makeZodVerifiedAPICall(+ GetCommentsV1Response,+ "GET",+ "/api/public/comments?objectType=TRACE",+ );+ expect(comments.body.data).toHaveLength(4);+ expect(comments.body.data.map((comment) => comment.id)).toEqual([+ "comment-2021-01-01",+ "comment-2021-03-01",+ "comment-2021-04-01",+ "comment-2021-05-01",+ ]);+ });++ it("should throw 400 error with descriptive error message if objectId is provided but objectType is not", async () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "GET",+ "/api/public/comments?objectId=trace-2021-01-01",+ );+ } catch (error) {+ expect((error as Error).message).toBe(+ `API call did not return 200, returned status 400, body {\"message\":\"Invalid request data\",\"error\":[{\"code\":\"custom\",\"message\":\"objectType is required when objectId is provided\",\"path\":[\"objectType\"]}]}`,+ );+ }+ });+});diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex eea64f088c..3c5372af68 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -19,6 +19,7 @@ export const pruneDatabase = async () => {await prisma.events.deleteMany();await prisma.model.deleteMany();await prisma.llmApiKeys.deleteMany();+ await prisma.comment.deleteMany();};function createBasicAuthHeader(username: string, password: string): string {diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.tsnew file mode 100644index 0000000000..62da5f5436--- /dev/null+++ b/web/src/features/comments/validateCommentReferenceObject.ts@@ -0,0 +1,65 @@+import {+ CommentObjectType,+ type PrismaClient,+ type CreateCommentData,+} from "@langfuse/shared";+import { type z } from "zod";++type PrismaModelName = keyof Omit<+ PrismaClient,+ | "$connect"+ | "$disconnect"+ | "$on"+ | "$transaction"+ | "$use"+ | "$extends"+ | "$executeRaw"+ | "$executeRawUnsafe"+ | "$queryRaw"+ | "$queryRawUnsafe"+ | "$metrics"+ | symbol+>;++const COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL: Record<+ CommentObjectType,+ PrismaModelName+> = {+ [CommentObjectType.TRACE]: "trace",+ [CommentObjectType.OBSERVATION]: "observation",+ [CommentObjectType.SESSION]: "traceSession",+ [CommentObjectType.PROMPT]: "prompt",+} as const;++export const validateCommentReferenceObject = async ({+ ctx,+ input,+}: {+ ctx: any;+ 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}`,+ };+ }++ const model = ctx.prisma[prismaModel];+ const object = await model.findFirst({+ where: {+ id: objectId,+ projectId,+ },+ });++ if (!object) {+ return {+ errorMessage: `No ${prismaModel} with id ${objectId} in project ${projectId}`,+ };+ }++ return {};+};diff --git a/web/src/features/public-api/types/comments.ts b/web/src/features/public-api/types/comments.tsnew file mode 100644index 0000000000..7ee8838168--- /dev/null+++ b/web/src/features/public-api/types/comments.ts@@ -0,0 +1,66 @@+import {+ CommentObjectType,+ CreateCommentData,+ paginationZod,+} from "@langfuse/shared";+import { z } from "zod";++/**+ * Objects+ */++const APIComment = z+ .strictObject({+ id: z.string(),+ projectId: z.string(),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ objectType: z.nativeEnum(CommentObjectType),+ objectId: z.string(),+ content: z.string().min(1).max(500),+ authorUserId: z.string().nullish(),+ })+ .strict();++/**+ * Endpoints+ */++// POST /comments+export const PostCommentsV1Body = CreateCommentData.extend({+ authorUserId: z.string().nullish(),+}).strict();+export const PostCommentsV1Response = z.object({ id: z.string() }).strict();++// GET /comments+export const GetCommentsV1Query = z+ .object({+ objectType: z.nativeEnum(CommentObjectType).nullish(),+ objectId: z.string().nullish(),+ authorUserId: z.string().nullish(),+ ...paginationZod,+ })+ .strict()+ .refine(+ ({ objectId, objectType }) => {+ return objectId ? !!objectType : true;+ },+ {+ message: "objectType is required when objectId is provided",+ path: ["objectType"],+ },+ );++export const GetCommentsV1Response = z+ .object({+ data: z.array(APIComment),+ })+ .strict();++// GET /comments/:id+export const GetCommentV1Query = z+ .object({+ commentId: z.string(),+ })+ .strict();+export const GetCommentV1Response = APIComment;diff --git a/web/src/pages/api/public/comments/[commentId].ts b/web/src/pages/api/public/comments/[commentId].tsnew file mode 100644index 0000000000..3f2c2cd5cd--- /dev/null+++ b/web/src/pages/api/public/comments/[commentId].ts@@ -0,0 +1,34 @@+import { prisma } from "@langfuse/shared/src/db";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { LangfuseNotFoundError } from "@langfuse/shared";+import {+ GetCommentV1Query,+ GetCommentV1Response,+} from "@/src/features/public-api/types/comments";++export default withMiddlewares({+ GET: createAuthedAPIRoute({+ name: "Get Comment",+ querySchema: GetCommentV1Query,+ responseSchema: GetCommentV1Response,+ fn: async ({ query, auth }) => {+ const { commentId } = query;++ const comment = await prisma.comment.findUnique({+ where: {+ id: commentId,+ projectId: auth.scope.projectId,+ },+ });++ if (!comment) {+ throw new LangfuseNotFoundError(+ "Comment not found within authorized project",+ );+ }++ return comment;+ },+ }),+});diff --git a/web/src/pages/api/public/comments/index.ts b/web/src/pages/api/public/comments/index.tsnew file mode 100644index 0000000000..74f0fda108--- /dev/null+++ b/web/src/pages/api/public/comments/index.ts@@ -0,0 +1,61 @@+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import {+ GetCommentsV1Query,+ GetCommentsV1Response,+ PostCommentsV1Body,+ PostCommentsV1Response,+} from "@/src/features/public-api/types/comments";+import { prisma } from "@langfuse/shared/src/db";+import { v4 } from "uuid";+import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";+import { LangfuseNotFoundError } from "@langfuse/shared";++export default withMiddlewares({+ POST: createAuthedAPIRoute({+ name: "Create Comment",+ bodySchema: PostCommentsV1Body,+ responseSchema: PostCommentsV1Response,+ fn: async ({ body, auth }) => {+ const result = await validateCommentReferenceObject({+ ctx: { prisma, auth },+ input: body,+ });++ if (result.errorMessage) {+ throw new LangfuseNotFoundError(result.errorMessage);+ }++ const comment = await prisma.comment.create({+ data: {+ ...body,+ id: v4(),+ projectId: auth.scope.projectId,+ },+ });++ return { id: comment.id };+ },+ }),+ GET: createAuthedAPIRoute({+ name: "Get Comments",+ querySchema: GetCommentsV1Query,+ responseSchema: GetCommentsV1Response,+ fn: async ({ query, auth }) => {+ const { objectType, objectId, authorUserId, limit, page } = query;++ const comments = await prisma.comment.findMany({+ where: {+ projectId: auth.scope.projectId,+ objectType: objectType ?? undefined,+ objectId: objectId ?? undefined,+ authorUserId: authorUserId ?? undefined,+ },+ take: limit,+ skip: (page - 1) * limit,+ });++ return { data: comments };+ },+ }),+});diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.tsindex b571a7aaa0..788b5e2d3c 100644--- a/web/src/server/api/routers/comments.ts+++ b/web/src/server/api/routers/comments.ts@@ -9,46 +9,7 @@ import { CommentObjectType } from "@langfuse/shared";import { Prisma, CreateCommentData, DeleteCommentData } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";import { TRPCError } from "@trpc/server";--const COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL = {- [CommentObjectType.TRACE]: "trace",- [CommentObjectType.OBSERVATION]: "observation",- [CommentObjectType.SESSION]: "traceSession",- [CommentObjectType.PROMPT]: "prompt",-} as const;--const validateCommentReferenceObject = async ({- ctx,- input,-}: {- ctx: any;- input: z.infer<typeof CreateCommentData>;-}): Promise<void> => {- const { objectId, objectType, projectId } = input;- const prismaModel = COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL[objectType];-- if (!prismaModel) {- throw new TRPCError({- code: "NOT_FOUND",- message: `No prisma model for object type ${objectType}`,- });- }-- const model = ctx.prisma[prismaModel];- const object = await model.findFirst({- where: {- id: objectId,- projectId,- },- });-- if (!object) {- throw new TRPCError({- code: "NOT_FOUND",- message: `No ${prismaModel} with id ${objectId} in project ${projectId}`,- });- }-};+import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";export const commentsRouter = createTRPCRouter({create: protectedProjectProcedure@@ -61,7 +22,17 @@ export const commentsRouter = createTRPCRouter({scope: "comments:CUD",});- validateCommentReferenceObject({ ctx, input });+ const result = await validateCommentReferenceObject({+ ctx,+ input,+ });++ if (result.errorMessage) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: result.errorMessage,+ });+ }const comment = await ctx.prisma.comment.create({data: {