RotNot / src /lib /debate /few-shot-examples.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
7.97 kB
/**
* Debate Arena β€” Few-Shot Calibration Examples
*
* Few-shot examples are manually graded debate argument pairs that anchor
* the LLM judge's scoring scale. Research consistently shows +15–25%
* accuracy improvement when judges are calibrated with concrete examples.
*
* ## How to add examples
*
* Edit `src/lib/judge/few-shot-examples.json`. Each entry is a `FewShotExample`:
*
* ```json
* [
* {
* "id": "ex-01",
* "scoreLevel": 8,
* "dimensionId": "argument-structure",
* "argument": "The full argument text as the user wrote it...",
* "rationale": "Why this scores an 8: clear thesis, logical flow, well-organised paragraphs...",
* "topic": "Social media should be regulated by governments"
* }
* ]
* ```
*
* ## Coverage goals (from Issue #21)
* - 3–4 examples per score level (1–5 is most useful; 6–10 less critical)
* - At least one example per scoring dimension
* - Mix of topic categories (philosophy, politics, ethics, technology...)
*
* ## File location
* `src/lib/judge/few-shot-examples.json`
*
* If the file is absent or empty, the judge runs without calibration (degraded mode).
*/
import { readFileSync } from "fs";
import { join } from "path";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** A single manually graded example for judge calibration. */
export interface FewShotExample {
/** Unique identifier, e.g. "ex-01" */
id: string;
/**
* Human-assigned score for this argument on the given dimension (0–10).
* Used to anchor the judge's scale.
*/
scoreLevel: number;
/**
* The scoring dimension this example illustrates.
* Must match one of the SCORING_DIMENSIONS ids in judge.ts, or "overall".
* "overall" examples are shown in the general guidelines section.
*/
dimensionId: string;
/** The verbatim argument text. */
argument: string;
/**
* Human explanation of WHY this receives the given score.
* This is the most important field β€” the judge learns from this rationale.
*/
rationale: string;
/** The debate topic this argument was made in response to (for context). */
topic: string;
/** Optional: which side the debater was arguing (pro | con) */
side?: "pro" | "con";
}
// ---------------------------------------------------------------------------
// File loading
// ---------------------------------------------------------------------------
const EXAMPLES_PATH = join(
process.cwd(),
"src/lib/judge/few-shot-examples.json",
);
/**
* Load few-shot examples from disk.
*
* Returns an empty array if:
* - The file does not exist (fresh install before Nicholas has graded examples)
* - The file is malformed JSON
* - The file contains an empty array
*
* This function is intentionally synchronous (same pattern as loadDimensionOverrides)
* to avoid restructuring all callers.
*/
export function loadFewShotExamples(): FewShotExample[] {
try {
const raw = readFileSync(EXAMPLES_PATH, "utf-8");
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
// Filter out entries that are missing required fields
return parsed.filter(
(item): item is FewShotExample =>
item !== null &&
typeof item === "object" &&
typeof (item as Record<string, unknown>).id === "string" &&
typeof (item as Record<string, unknown>).scoreLevel === "number" &&
typeof (item as Record<string, unknown>).dimensionId === "string" &&
typeof (item as Record<string, unknown>).argument === "string" &&
typeof (item as Record<string, unknown>).rationale === "string" &&
typeof (item as Record<string, unknown>).topic === "string",
);
} catch {
return [];
}
}
// ---------------------------------------------------------------------------
// Example filtering helpers
// ---------------------------------------------------------------------------
/**
* Get all examples for a specific scoring dimension.
*/
export function getExamplesForDimension(
examples: FewShotExample[],
dimensionId: string,
): FewShotExample[] {
return examples.filter((ex) => ex.dimensionId === dimensionId);
}
/**
* Get all "overall" examples (dimensionId === "overall").
*/
export function getOverallExamples(
examples: FewShotExample[],
): FewShotExample[] {
return examples.filter((ex) => ex.dimensionId === "overall");
}
/**
* Group examples by their scoreLevel bucket.
* Buckets: low (0–3), medium (4–6), high (7–10).
*/
export function groupByScoreLevel(
examples: FewShotExample[],
): { low: FewShotExample[]; medium: FewShotExample[]; high: FewShotExample[] } {
return {
low: examples.filter((ex) => ex.scoreLevel <= 3),
medium: examples.filter((ex) => ex.scoreLevel >= 4 && ex.scoreLevel <= 6),
high: examples.filter((ex) => ex.scoreLevel >= 7),
};
}
// ---------------------------------------------------------------------------
// Prompt formatting
// ---------------------------------------------------------------------------
/**
* Format a single few-shot example for inclusion in a prompt.
* Returns a compact block:
*
* Example (Score: 8/10 β€” Argument Structure):
* Topic: "..."
* Argument: "..."
* Why this scores 8: ...
*/
export function formatExample(example: FewShotExample): string {
const dimLabel =
example.dimensionId === "overall"
? "Overall Quality"
: example.dimensionId
.split("-")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ");
const sideNote = example.side ? ` (arguing ${example.side})` : "";
return [
`Example (Score: ${example.scoreLevel}/10 β€” ${dimLabel}):`,
`Topic: "${example.topic}"${sideNote}`,
`Argument: "${example.argument}"`,
`Why this scores ${example.scoreLevel}: ${example.rationale}`,
].join("\n");
}
/**
* Build the few-shot calibration block to inject into the judge system prompt.
*
* Groups examples by score level for maximum calibration effect.
* Returns an empty string if no examples are available (graceful degradation).
*
* @param examples - Pre-loaded examples (pass result of loadFewShotExamples())
* @param maxExamples - Maximum total examples to include (default 12 to stay within token budget)
*/
export function buildFewShotBlock(
examples: FewShotExample[],
maxExamples = 12,
): string {
if (examples.length === 0) return "";
// Prefer examples spread across score levels for calibration breadth
const { low, medium, high } = groupByScoreLevel(examples);
// Distribute budget: roughly equal across tiers, fill from available
const tierBudget = Math.ceil(maxExamples / 3);
const selected = [
...low.slice(0, tierBudget),
...medium.slice(0, tierBudget),
...high.slice(0, tierBudget),
].slice(0, maxExamples);
if (selected.length === 0) return "";
const header = `\n\n## Calibration Examples\nThe following manually graded examples anchor your scoring scale:\n`;
const body = selected.map(formatExample).join("\n\n");
return header + body;
}
/**
* Build a dimension-specific few-shot block for inline use within a scoring
* rubric. Returns a compact "(e.g. ...)" hint string, or "" if no examples.
*
* @param examples - All loaded examples
* @param dimensionId - The dimension to get examples for
* @param maxExamples - Max examples to include inline (default 2)
*/
export function buildInlineDimensionExamples(
examples: FewShotExample[],
dimensionId: string,
maxExamples = 2,
): string {
const dimExamples = getExamplesForDimension(examples, dimensionId).slice(
0,
maxExamples,
);
if (dimExamples.length === 0) return "";
const hints = dimExamples.map(
(ex) => `score ${ex.scoreLevel}: "${ex.argument.slice(0, 80)}${ex.argument.length > 80 ? "..." : ""}"`,
);
return ` (e.g. ${hints.join("; ")})`;
}