Overview
Prompt distillation shrinks a long, wordy system prompt into a compact version while keeping rare edge-case formatting rules intact. Instead of guessing which lines can be cut, you distill against real edge-case test inputs and verify the compressed prompt on every rule.
- Keep strict rules as compact invariants: Convert long prose explanations into short, direct rules with exact output markers or schemas.
- Verify edge cases with a regression suite: Test the shorter prompt on rare inputs—such as empty values, special characters, or nested structures—so compression never drops a rule.
Steps
- Collect edge-case test cases and formatting rules: List every output rule (JSON shape, escaping, null handling, length caps) along with tricky edge cases that often break formatting.
- Draft a compact distilled prompt: Remove filler and repeated examples, keeping exact constraints, allowed values, and edge-case rules in short lines.
- Run side-by-side evals on edge cases: Compare outputs from the original and distilled prompts on your edge-case suite using strict schema and format checks.
- Restore only the failing edge-case rules: If a specific edge case fails, add back a crisp rule or one minimal example for that exact case, then re-test.
Example
export interface EdgeCaseTest {
id: string;
input: string;
validateOutput: (rawOutput: string) => { ok: boolean; reason?: string };
}
export interface DistillationEvalReport {
totalCases: number;
passedCases: number;
failedCases: Array<{ id: string; reason: string; output: string }>;
passRate: number;
}
export function distillSystemPrompt(params: {
role: string;
coreRules: string[];
edgeCaseRules: string[];
outputSchemaHint: string;
}): string {
const sections: string[] = [
`Role: ${params.role}`,
"",
"Rules:",
...params.coreRules.map((r) => `- ${r}`),
"",
"Edge-case rules:",
...params.edgeCaseRules.map((r) => `- ${r}`),
"",
`Output format: ${params.outputSchemaHint}`,
];
return sections.join("\n").trim();
}
export async function evaluateDistilledPrompt(
cases: EdgeCaseTest[],
runModel: (input: string) => Promise<string>
): Promise<DistillationEvalReport> {
const failedCases: Array<{ id: string; reason: string; output: string }> = [];
let passedCases = 0;
for (const testCase of cases) {
const output = await runModel(testCase.input);
const check = testCase.validateOutput(output);
if (check.ok) {
passedCases += 1;
} else {
failedCases.push({
id: testCase.id,
reason: check.reason ?? "Validation failed.",
output,
});
}
}
return {
totalCases: cases.length,
passedCases,
failedCases,
passRate: cases.length === 0 ? 1 : Number((passedCases / cases.length).toFixed(4)),
};
}
// Demo setup for a structured extraction prompt with edge cases
const distilledPrompt = distillSystemPrompt({
role: "Extract order fields strictly as JSON.",
coreRules: [
"Return valid JSON only with no markdown fences.",
"Use null when a field is missing or unclear.",
],
edgeCaseRules: [
"Escape quotes and newlines inside string values.",
"Keep leading zeros in order/ZIP codes as strings.",
"Return an empty items array [] when no items are listed.",
],
outputSchemaHint: '{"orderId": string|null, "zip": string|null, "items": string[]}',
});
const edgeCases: EdgeCaseTest[] = [
{
id: "leading-zero-zip",
input: "Order #A1, ZIP 02134, no line items mentioned.",
validateOutput: (raw) => {
try {
const parsed = JSON.parse(raw) as { zip?: unknown; items?: unknown };
if (parsed.zip !== "02134") return { ok: false, reason: "ZIP lost leading zero or type." };
if (!Array.isArray(parsed.items) || parsed.items.length !== 0) {
return { ok: false, reason: "Items should be empty array []." };
}
return { ok: true };
} catch {
return { ok: false, reason: "Invalid JSON output." };
}
},
},
];
console.log(distilledPrompt);
console.log("Prepared edge cases:", edgeCases.length);
Tips
- Keep rare edge cases in your test set even after compression: Edge-case rules often fail only on 2%–5% of traffic, so automated assertions must run on every prompt change.
- Pair prompt compression with structured output schemas: Let schema validation or grammar constraints enforce structure whenever your provider supports them, reducing prose needed in the system prompt.
- Measure token savings against quality on every version: Track prompt token count alongside edge-case pass rate so you do not trade accuracy for minor token savings.
You must log in or register to comment.
