(req: Request)
| 9 | }) |
| 10 | |
| 11 | export async function POST(req: Request) { |
| 12 | const langfuse = getLangfuseClient() |
| 13 | if (!langfuse) { |
| 14 | return Response.json({ success: true, logged: false }) |
| 15 | } |
| 16 | |
| 17 | // Validate input |
| 18 | let data |
| 19 | try { |
| 20 | data = feedbackSchema.parse(await req.json()) |
| 21 | } catch { |
| 22 | return Response.json( |
| 23 | { success: false, error: "Invalid input" }, |
| 24 | { status: 400 }, |
| 25 | ) |
| 26 | } |
| 27 | |
| 28 | const { messageId, feedback, sessionId } = data |
| 29 | |
| 30 | // Get user IP for tracking |
| 31 | const forwardedFor = req.headers.get("x-forwarded-for") |
| 32 | const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous" |
| 33 | |
| 34 | try { |
| 35 | // Find the most recent chat trace for this session to attach the score to |
| 36 | const tracesResponse = await langfuse.api.trace.list({ |
| 37 | sessionId, |
| 38 | limit: 1, |
| 39 | }) |
| 40 | |
| 41 | const traces = tracesResponse.data || [] |
| 42 | const latestTrace = traces[0] |
| 43 | |
| 44 | if (!latestTrace) { |
| 45 | // No trace found for this session - create a standalone feedback trace |
| 46 | const traceId = randomUUID() |
| 47 | const timestamp = new Date().toISOString() |
| 48 | |
| 49 | await langfuse.api.ingestion.batch({ |
| 50 | batch: [ |
| 51 | { |
| 52 | type: "trace-create", |
| 53 | id: randomUUID(), |
| 54 | timestamp, |
| 55 | body: { |
| 56 | id: traceId, |
| 57 | name: "user-feedback", |
| 58 | sessionId, |
| 59 | userId, |
| 60 | input: { messageId, feedback }, |
| 61 | metadata: { |
| 62 | source: "feedback-button", |
| 63 | note: "standalone - no chat trace found", |
| 64 | }, |
| 65 | timestamp, |
| 66 | }, |
| 67 | }, |
| 68 | { |
nothing calls this directly
no test coverage detected