import { NextRequest, NextResponse } from "next/server"; import { withApiError, ApiError } from "@/lib/api-error"; import { DIMENSION_IDS } from "@/lib/debate/judge"; import { submitAllHumanFeedback } from "@/lib/langsmith"; /** * POST /api/debate/feedback * * Submits human override scores for a debate round to LangSmith. * These "human_" feedback keys are picked up by the reflector * to detect divergence between the LLM judge and human evaluators. * * Body: * { * runId: string, // LangSmith run ID from the judge response * scores: Record // dimensionId → 0-10 score (partial OK) * } * * Returns: * { submitted: number } // count of scores accepted * * A 503 is returned if LANGSMITH_API_KEY is not configured (graceful skip). * A 400 is returned for invalid body shape or unknown dimension IDs. * Unknown dimension IDs in scores are silently filtered (only valid IDs submitted). */ export const POST = withApiError(async (request: NextRequest) => { if (!process.env.LANGSMITH_API_KEY) { // Not an error — LangSmith is optional. Return graceful no-op. return NextResponse.json( { submitted: 0, skipped: "LANGSMITH_API_KEY not configured" }, { status: 200 }, ); } let body: { runId?: unknown; scores?: unknown }; try { body = await request.json(); } catch { throw new ApiError(400, "Invalid JSON body"); } if (!body.runId || typeof body.runId !== "string") { throw new ApiError(400, "runId is required and must be a string"); } if ( !body.scores || typeof body.scores !== "object" || Array.isArray(body.scores) ) { throw new ApiError(400, "scores must be a non-null object"); } const rawScores = body.scores as Record; const validDimensionSet = new Set(DIMENSION_IDS); // Filter to known dimension IDs with numeric scores in [0, 10] const cleanScores: Record = {}; for (const [dimId, value] of Object.entries(rawScores)) { if (!validDimensionSet.has(dimId)) continue; if (typeof value !== "number") continue; if (value < 0 || value > 10) continue; cleanScores[dimId] = value; } if (Object.keys(cleanScores).length === 0) { throw new ApiError( 400, "No valid scores provided. Scores must use valid dimension IDs and values in [0, 10].", ); } await submitAllHumanFeedback(body.runId, cleanScores); return NextResponse.json({ submitted: Object.keys(cleanScores).length }); });