File size: 7,974 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | /**
* 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("; ")})`;
}
|