Download src/lib/debate/judge.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/debate/judge.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/debate/judge.ts
-
curl -L -o judge.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/debate/judge.ts
18 kB
| /** | |
| * Debate Arena β Judge Scoring System | |
| * | |
| * The AI judge evaluates both debaters on multiple dimensions each round. | |
| * Scoring dimensions combine critical thinking metrics (from existing exercises) | |
| * with debate-specific criteria. | |
| */ | |
| import { readFileSync } from "fs"; | |
| import { join } from "path"; | |
| import { | |
| type FewShotExample, | |
| buildFewShotBlock, | |
| buildInlineDimensionExamples, | |
| loadFewShotExamples, | |
| } from "./few-shot-examples"; | |
| // --------------------------------------------------------------------------- | |
| // Dimension override support | |
| // --------------------------------------------------------------------------- | |
| const OVERRIDES_PATH = join( | |
| process.cwd(), | |
| "src/lib/judge/dimension-overrides.json", | |
| ); | |
| /** | |
| * Load approved dimension description overrides from disk. | |
| * Returns a map of dimensionId β overridden description text. | |
| * Returns an empty object if the file does not exist or cannot be parsed. | |
| * This is intentionally synchronous β it is called during server-side prompt | |
| * construction where async would require restructuring all callers. | |
| */ | |
| export function loadDimensionOverrides(): Record<string, string> { | |
| try { | |
| const raw = readFileSync(OVERRIDES_PATH, "utf-8"); | |
| const parsed: unknown = JSON.parse(raw); | |
| if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { | |
| return parsed as Record<string, string>; | |
| } | |
| return {}; | |
| } catch { | |
| // File doesn't exist yet (before first approval) or is malformed β use defaults | |
| return {}; | |
| } | |
| } | |
| /** | |
| * Apply dimension overrides to the canonical SCORING_DIMENSIONS list. | |
| * Returns a new array β does not mutate SCORING_DIMENSIONS. | |
| * Only dimensions with a non-empty string override are changed. | |
| */ | |
| export function applyDimensionOverrides( | |
| dimensions: ScoreDimension[], | |
| overrides: Record<string, string>, | |
| ): ScoreDimension[] { | |
| if (Object.keys(overrides).length === 0) return dimensions; | |
| return dimensions.map((d) => { | |
| const override = overrides[d.id]; | |
| if (typeof override === "string" && override.trim().length > 0) { | |
| return { ...d, description: override.trim() }; | |
| } | |
| return d; | |
| }); | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Scoring dimensions | |
| // --------------------------------------------------------------------------- | |
| export interface ScoreDimension { | |
| id: string; | |
| name: string; | |
| description: string; | |
| /** Which category this dimension belongs to */ | |
| category: "critical-thinking" | "debate-specific"; | |
| } | |
| /** | |
| * All scoring dimensions the judge evaluates for each debater per round. | |
| */ | |
| export const SCORING_DIMENSIONS: ScoreDimension[] = [ | |
| // Critical thinking dimensions (from existing exercises) | |
| { | |
| id: "flaw-detection", | |
| name: "Flaw Detection", | |
| description: "Identifying logical fallacies, weak premises, and unsupported claims in the opponent's argument.", | |
| category: "critical-thinking", | |
| }, | |
| { | |
| id: "steelman-awareness", | |
| name: "Steelman Awareness", | |
| description: "Presenting the strongest version of the opposing view before countering it.", | |
| category: "critical-thinking", | |
| }, | |
| { | |
| id: "devils-advocate-depth", | |
| name: "Devil's Advocate Depth", | |
| description: "Anticipating and addressing counterarguments proactively.", | |
| category: "critical-thinking", | |
| }, | |
| // Debate-specific dimensions | |
| { | |
| id: "argument-structure", | |
| name: "Argument Structure", | |
| description: "Logical flow, clear thesis, and coherent organisation of arguments.", | |
| category: "debate-specific", | |
| }, | |
| { | |
| id: "persuasiveness", | |
| name: "Persuasiveness", | |
| description: "Rhetorical effectiveness, compelling framing, and ability to move the audience.", | |
| category: "debate-specific", | |
| }, | |
| { | |
| id: "evidence-accuracy", | |
| name: "Evidence & Accuracy", | |
| description: "Factual correctness, citation of real data or studies, and appropriate use of examples.", | |
| category: "debate-specific", | |
| }, | |
| { | |
| id: "rebuttal-quality", | |
| name: "Rebuttal Quality", | |
| description: "Directly engaging with the opponent's points rather than talking past them.", | |
| category: "debate-specific", | |
| }, | |
| { | |
| id: "intellectual-honesty", | |
| name: "Intellectual Honesty", | |
| description: "Acknowledging strong opposing points, avoiding strawmen, and maintaining good faith.", | |
| category: "debate-specific", | |
| }, | |
| ]; | |
| /** | |
| * All dimension IDs, for convenience. | |
| */ | |
| export const DIMENSION_IDS = SCORING_DIMENSIONS.map((d) => d.id); | |
| // --------------------------------------------------------------------------- | |
| // Score types | |
| // --------------------------------------------------------------------------- | |
| /** Score for a single dimension: 0β10 */ | |
| export type DimensionScore = Record<string, number>; | |
| /** Scores for one debater in one round */ | |
| export interface RoundDebaterScore { | |
| dimensionScores: DimensionScore; | |
| overallScore: number; // 0β10, weighted average | |
| analysis: string; // brief written analysis | |
| } | |
| /** Complete round result from the judge */ | |
| export interface RoundJudgement { | |
| round: number; | |
| user: RoundDebaterScore; | |
| opponent: RoundDebaterScore; | |
| roundWinner: "user" | "opponent" | "tie"; | |
| roundSummary: string; | |
| } | |
| /** Final debate result */ | |
| export interface FinalJudgement { | |
| rounds: RoundJudgement[]; | |
| userTotalScore: number; | |
| opponentTotalScore: number; | |
| winner: "user" | "opponent" | "tie"; | |
| overallAnalysis: string; | |
| userStrengths: string[]; | |
| userWeaknesses: string[]; | |
| suggestions: string[]; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Score computation helpers | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Calculate weighted overall score from dimension scores. | |
| * Critical thinking dimensions are weighted slightly higher (1.2x) | |
| * to incentivise deep reasoning over surface-level rhetoric. | |
| */ | |
| export function calculateOverallScore(dimensionScores: DimensionScore): number { | |
| const criticalDimensionIds = new Set( | |
| SCORING_DIMENSIONS | |
| .filter((d) => d.category === "critical-thinking") | |
| .map((d) => d.id), | |
| ); | |
| let weightedSum = 0; | |
| let totalWeight = 0; | |
| for (const dim of SCORING_DIMENSIONS) { | |
| const score = dimensionScores[dim.id]; | |
| if (typeof score !== "number" || isNaN(score)) continue; | |
| const clamped = Math.min(10, Math.max(0, score)); | |
| const weight = criticalDimensionIds.has(dim.id) ? 1.2 : 1.0; | |
| weightedSum += clamped * weight; | |
| totalWeight += weight; | |
| } | |
| if (totalWeight === 0) return 0; | |
| return Math.round((weightedSum / totalWeight) * 10) / 10; | |
| } | |
| /** | |
| * Determine the round winner from two overall scores. | |
| * Tie if difference is β€ 0.5. | |
| */ | |
| export function determineRoundWinner( | |
| userScore: number, | |
| opponentScore: number, | |
| ): "user" | "opponent" | "tie" { | |
| const diff = userScore - opponentScore; | |
| if (Math.abs(diff) <= 0.5) return "tie"; | |
| return diff > 0 ? "user" : "opponent"; | |
| } | |
| /** | |
| * Determine the final debate winner from cumulative scores across rounds. | |
| * Tie if average score difference per round is β€ 0.3. | |
| */ | |
| export function determineFinalWinner( | |
| rounds: RoundJudgement[], | |
| ): "user" | "opponent" | "tie" { | |
| if (rounds.length === 0) return "tie"; | |
| const userTotal = rounds.reduce((sum, r) => sum + r.user.overallScore, 0); | |
| const oppTotal = rounds.reduce((sum, r) => sum + r.opponent.overallScore, 0); | |
| const avgDiff = (userTotal - oppTotal) / rounds.length; | |
| if (Math.abs(avgDiff) <= 0.3) return "tie"; | |
| return avgDiff > 0 ? "user" : "opponent"; | |
| } | |
| /** | |
| * Aggregate round scores into cumulative totals. | |
| */ | |
| export function aggregateScores(rounds: RoundJudgement[]): { | |
| userTotal: number; | |
| opponentTotal: number; | |
| userAvg: number; | |
| opponentAvg: number; | |
| } { | |
| if (rounds.length === 0) { | |
| return { userTotal: 0, opponentTotal: 0, userAvg: 0, opponentAvg: 0 }; | |
| } | |
| const userTotal = rounds.reduce((sum, r) => sum + r.user.overallScore, 0); | |
| const opponentTotal = rounds.reduce((sum, r) => sum + r.opponent.overallScore, 0); | |
| return { | |
| userTotal: Math.round(userTotal * 10) / 10, | |
| opponentTotal: Math.round(opponentTotal * 10) / 10, | |
| userAvg: Math.round((userTotal / rounds.length) * 10) / 10, | |
| opponentAvg: Math.round((opponentTotal / rounds.length) * 10) / 10, | |
| }; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Judge prompt builder | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Build the judge system prompt for scoring a round. | |
| * Applies any approved dimension overrides from dimension-overrides.json. | |
| * Injects few-shot calibration examples when available. | |
| * | |
| * Accepts optional parameters for testing: | |
| * - overrides: dimension description overrides map (loads from disk if omitted) | |
| * - examples: pre-loaded few-shot examples (loads from disk if omitted; pass [] to disable) | |
| */ | |
| export function buildJudgeSystemPrompt( | |
| overrides?: Record<string, string>, | |
| examples?: FewShotExample[], | |
| ): string { | |
| const resolved = overrides ?? loadDimensionOverrides(); | |
| const resolvedExamples = examples ?? loadFewShotExamples(); | |
| const dimensions = applyDimensionOverrides(SCORING_DIMENSIONS, resolved); | |
| const dimensionList = dimensions | |
| .map((d) => `- **${d.name}** (${d.id}): ${d.description}`) | |
| .join("\n"); | |
| const fewShotBlock = buildFewShotBlock(resolvedExamples); | |
| return `You are an impartial, expert debate judge with deep training in rhetoric, logic, and critical thinking. Your role is to evaluate both debaters rigorously but fairly across multiple dimensions of argumentation skill. | |
| ## Core Principles | |
| - Judge arguments on their logical merit, evidence quality, and rhetorical effectiveness β never on your personal agreement with the position. | |
| - Both debaters deserve equal scrutiny. Do not give either side the benefit of the doubt by default. | |
| - A strong argument for a position you disagree with should score higher than a weak argument for a position you support. | |
| - Acknowledge implicit trade-offs: rhetorical flair without substance is weak; dry accuracy without engagement is also weak. | |
| ## Scoring Dimensions (0β10 each) | |
| ${dimensionList} | |
| ## Detailed Scoring Rubric | |
| Use the full 0β10 scale. Most debates will cluster around 4β7, with true excellence (8+) and genuine failure (0β3) being rare and distinctive. | |
| **0β2: Absent or Severely Flawed** | |
| - No engagement with the dimension, or active demonstration of incompetence | |
| - Logical incoherence, complete factual errors, or argumentative avoidance | |
| - Example: Citing debunked statistics as fact, strawmanning the opponent's entire position without engaging their actual claims | |
| **3β4: Below Average** | |
| - Attempts engagement but execution has major gaps or errors | |
| - Partial understanding of the dimension, with significant misapplication | |
| - Example: Flaw detection that identifies logical fallacies but mislabels them; steelmanning that restates opponent's view but misses their strongest version | |
| **5β6: Adequate** | |
| - Meets basic expectations for the dimension | |
| - Competent but unremarkable β does what's required without distinction | |
| - Example: Clear argument structure with thesis and supporting points; identifies obvious flaws but misses subtle ones; addresses counterarguments superficially | |
| **7β8: Strong** | |
| - Demonstrates genuine skill and depth in this dimension | |
| - Goes beyond basic competence with specific, well-executed technique | |
| - Example: Flaw detection that precisely identifies logical structure and explains why it fails; steelmanning that genuinely strengthens the opponent's case before dismantling it; anticipates and preempts sophisticated counterarguments | |
| **9β10: Exceptional** | |
| - Masterful execution that would impress expert debaters | |
| - Rare demonstration of the dimension at its highest level | |
| - Example: Flaw detection combined with repair suggestions; devil's advocacy so thorough it temporarily convinces the reader; rebuttals that transform the opponent's own reasoning against them elegantly | |
| ## Chain-of-Thought Protocol | |
| Before assigning scores, mentally walk through: | |
| 1. What is the strongest version of each debater's position? | |
| 2. What are the specific logical moves each debater makes? | |
| 3. Where do those moves succeed or fail? | |
| 4. How does each debater engage (or fail to engage) with the other's claims? | |
| 5. Given the above, what score best reflects the quality demonstrated? | |
| ## Tie-Breaking Guidance | |
| When scores are close (within 0.5 points): | |
| - Favor the debater who demonstrated more dimensions at higher levels | |
| - Favor intellectual honesty over rhetorical polish | |
| - Favor direct engagement with the opponent over isolated arguments | |
| - Favor specific evidence over vague assertions | |
| - If still tied, "tie" is an acceptable outcome | |
| ## Anti-Bias Checklist | |
| - [ ] Would I score this the same if the debaters swapped positions? | |
| - [ ] Am I rewarding clarity of expression or just agreement with my views? | |
| - [ ] Am I penalizing complexity, or rewarding oversimplification? | |
| - [ ] Have I given each debater credit for their strongest moments? | |
| - [ ] Are my scores consistent with the calibration examples?${fewShotBlock}`; | |
| } | |
| /** | |
| * Build the judge evaluation prompt for a single round. | |
| * | |
| * Accepts optional few-shot examples that are injected as inline calibration | |
| * hints next to each dimension ID in the JSON schema β grounding the judge's | |
| * scale at the point where it writes dimension scores. | |
| * | |
| * @param examples - Pre-loaded few-shot examples (loads from disk if omitted; pass [] to disable) | |
| */ | |
| export function buildRoundEvaluationPrompt( | |
| topic: string, | |
| round: number, | |
| totalRounds: number, | |
| userArgument: string, | |
| opponentArgument: string, | |
| opponentName: string, | |
| previousRounds?: RoundJudgement[], | |
| examples?: FewShotExample[], | |
| ): string { | |
| const resolvedExamples = examples ?? loadFewShotExamples(); | |
| // Build per-dimension inline calibration hints (e.g. "score 8: '...'") | |
| const dimScoreSchema = DIMENSION_IDS.map((id) => { | |
| const hint = buildInlineDimensionExamples(resolvedExamples, id, 1); | |
| return `"${id}": N${hint}`; | |
| }).join(", "); | |
| let context = ""; | |
| if (previousRounds && previousRounds.length > 0) { | |
| context = `\n\nPrevious round scores for context:\n${previousRounds | |
| .map( | |
| (r) => | |
| `Round ${r.round}: User ${r.user.overallScore}/10, ${opponentName} ${r.opponent.overallScore}/10 β ${r.roundSummary}`, | |
| ) | |
| .join("\n")}`; | |
| } | |
| return `DEBATE TOPIC: "${topic}" | |
| ROUND: ${round} of ${totalRounds}${context} | |
| --- | |
| ## Instructions | |
| Evaluate BOTH debaters on ALL 8 dimensions (0β10 each). Consider: | |
| - What each debater actually said, not what they could have said | |
| - The logical structure and evidence quality of each argument | |
| - How effectively each debater engaged with the other's claims | |
| - The specific calibration hints provided in the dimension score schema | |
| ## USER'S ARGUMENT | |
| ${userArgument} | |
| ## ${opponentName.toUpperCase()}'S ARGUMENT | |
| ${opponentArgument} | |
| --- | |
| ## Response Format | |
| Respond ONLY in valid JSON (no markdown, no code fences, no trailing comments): | |
| { | |
| "user": { | |
| "dimensionScores": { ${dimScoreSchema} }, | |
| "analysis": "2-3 sentences analyzing the user's performance this round. Be specific: what did they do well, where did they fall short, what was their key logical move?" | |
| }, | |
| "opponent": { | |
| "dimensionScores": { ${dimScoreSchema} }, | |
| "analysis": "2-3 sentences analyzing ${opponentName}'s performance this round. Be specific: what did they do well, where did they fall short, what was their key logical move?" | |
| }, | |
| "roundWinner": "user" | "opponent" | "tie", | |
| "roundSummary": "One sentence: why the winner prevailed (or why it was a tie). Reference specific argumentative moves, not vague generalities." | |
| }`; | |
| } | |
| /** | |
| * Build the judge prompt for the final summary after all rounds. | |
| */ | |
| export function buildFinalSummaryPrompt( | |
| topic: string, | |
| rounds: RoundJudgement[], | |
| opponentName: string, | |
| ): string { | |
| const roundSummaries = rounds | |
| .map( | |
| (r) => | |
| `Round ${r.round}: User ${r.user.overallScore}/10 vs ${opponentName} ${r.opponent.overallScore}/10 β Winner: ${r.roundWinner}. ${r.roundSummary}`, | |
| ) | |
| .join("\n"); | |
| return `DEBATE TOPIC: "${topic}" | |
| OPPONENT: ${opponentName} | |
| ## Round-by-Round Results | |
| ${roundSummaries} | |
| ## Instructions | |
| Provide a comprehensive final assessment. This is the debater's primary learning artifact β be specific, constructive, and honest. | |
| Focus on: | |
| - Pattern recognition: what tendencies showed up across multiple rounds? | |
| - Comparative analysis: where did the user consistently outperform or underperform relative to ${opponentName}? | |
| - Actionable guidance: specific techniques or habits to develop, not vague platitudes | |
| ## Response Format | |
| Respond ONLY in valid JSON (no markdown, no code fences): | |
| { | |
| "overallAnalysis": "2-3 paragraph analysis. First paragraph: summarize the debate arc and who argued more effectively overall. Second paragraph: analyze the user's specific argumentative style β their go-to moves, recurring gaps, and how they developed across rounds. Third paragraph (if warranted): situate this performance within the broader context of the topic.", | |
| "userStrengths": [ | |
| "Specific strength with evidence: e.g., 'Effective use of steelmanning in Round 2, where you accurately summarized the opponent's position before rebutting it'", | |
| "Another specific strength β cite the round and the move" | |
| ], | |
| "userWeaknesses": [ | |
| "Specific weakness with evidence: e.g., 'Tended to concede without extracting concessions β in Round 1, you acknowledged the opponent's point about economic growth without noting the environmental trade-off you had established'", | |
| "Another specific weakness β cite the round and the gap" | |
| ], | |
| "suggestions": [ | |
| "Concrete improvement technique: e.g., 'Practice the "yes, and" rebuttal structure: acknowledge validity, then show limitation'", | |
| "Another specific technique or exercise", | |
| "Resource or method for developing this skill" | |
| ] | |
| }`; | |
| } | |