File size: 2,531 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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_<dimensionId>" 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<string, number>  // 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<string, unknown>;
  const validDimensionSet = new Set(DIMENSION_IDS);

  // Filter to known dimension IDs with numeric scores in [0, 10]
  const cleanScores: Record<string, number> = {};
  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 });
});