#Prompts are code
AddedIn an application, a prompt isn't a message you type once. It's a template your code fills in thousands of times a day, and it decides your feature's behaviour as much as any function you write. Change one sentence and the output format, tone, refusal rate or cost can change for every user. So treat prompts like code: keep them in the repository, review changes in pull requests, give them versions, and test them before release, with an eval set (inputs with known good answers) instead of unit tests that check exact strings (Evals is the whole chapter on this).
The mental model is a prompt is a function whose implementation runs on someone else's computer. You control the inputs (the template and what you put in it), you can't step through the body, and the body changes when the provider ships a new model. That's why the discipline that matters is the one around it: pin the model version, version the prompt, record which prompt version produced each output, and re-run the evals whenever either changes.
import { createHash } from "node:crypto";
// prompts/ticket-summary.mjs: one prompt, one module, an explicit version.
const ticketSummary = {
id: "ticket-summary",
version: 3,
model: "claude-sonnet-5-5", // pinned alongside the prompt it was tested with
system: [
"You summarise customer support tickets for the on-call engineer.",
"Write exactly three bullet points: the problem, what the customer tried, and what they need.",
"Engineers read these on their phones during incidents, so keep each bullet under 20 words.",
].join("\n"),
render: ({ ticket }) => `<ticket>\n${ticket}\n</ticket>\n\nSummarise this ticket.`,
};
const fingerprint = (prompt) =>
createHash("sha256").update(JSON.stringify([prompt.model, prompt.system, prompt.render({ ticket: "{{ticket}}" })])).digest("hex").slice(0, 12);
// A snapshot test: CI stores the fingerprint that the eval suite last passed with.
const approved = { "ticket-summary@3": "f2c6d3b0a8e1" };
const key = `${ticketSummary.id}@${ticketSummary.version}`;
const now = fingerprint(ticketSummary);
console.log(key, "fingerprint", now);
// Someone "tidies" the system prompt: a trailing space and a softer word.
const edited = { ...ticketSummary, system: ticketSummary.system.replace("exactly three", "three ") };
console.log("after a small edit:", fingerprint(edited));
console.log(fingerprint(edited) === now ? "unchanged" : `changed without a version bump: re-run the evals, then bump to @${ticketSummary.version + 1}`);
// Every log line records which prompt produced the output.
console.log(JSON.stringify({ event: "llm_call", prompt: key, fingerprint: now, model: ticketSummary.model, approved: approved[key] === now }));ticket-summary@3 fingerprint c22e8bfaac05
after a small edit: 47fb1215960d
changed without a version bump: re-run the evals, then bump to @4
{"event":"llm_call","prompt":"ticket-summary@3","fingerprint":"c22e8bfaac05","model":"claude-sonnet-5-5","approved":false}- The prompt lives in its own module with an
id, aversion, themodelit was tested with, a fixedsystemprompt and arenderfunction for the per-request part. Engineers edit it in a pull request like any other code, and reviewers can see exactly what changed. fingerprinthashes everything that shapes the model's input: model, system prompt and the rendered template with a placeholder. Two prompts with the same fingerprint send byte-identical instructions.- The edit swaps "exactly three" for "three " (with a stray space). It looks harmless, but "exactly" was doing work, and the fingerprint changes. The check prints that the prompt changed without a version bump: the CI rule is "a changed fingerprint needs a passing eval run and a new version".
- The
approvedmap stands for what CI stored the last time the evals passed. In this run it doesn't match the current fingerprint (the stored value is a stand-in), so the log line saysapproved: false, which is exactly the signal a release gate would block on. - The log line records prompt id, version, fingerprint and model with every call. When quality drops in production, this is how you find out whether a prompt change, a model change or the inputs changed.
- A side effect worth knowing: byte-for-byte stability also matters for prompt caching, which matches exact prefixes. The same discipline that makes prompts reviewable keeps the cache hitting (Prompt caching).
Where prompts live. Small teams keep them as modules next to the code that uses them (src/ai/prompts/ticket-summary.ts), with the eval cases beside them (src/ai/evals/ticket-summary.cases.jsonl). Larger teams sometimes move them into a prompt management tool (Langfuse, Braintrust, PromptLayer and others offer one) so non-engineers can edit and roll out versions without a deploy; the trade-off is that prompt changes then bypass code review, so the tool must enforce evals and versioning itself. Either way, never build prompts by string concatenation scattered across a codebase: you can't review what you can't find.
The fingerprint above tells you that a prompt changed. The eval gate tells you whether the change is allowed to ship. In CI, every pull request that touches a prompt (or the pinned model) runs the prompt's eval cases and compares the pass rate with the last approved run. This model shows the harness with a stand-in model function, because the point here is the mechanics: cases, checks, a baseline, and a gate that fails the build.
// A minimal prompt eval gate. `callModel` stands in for the real SDK call so the harness itself is visible.
const cases = [
{ id: "refund-late", input: "Order arrived 3 weeks late, I want a refund.", expect: { category: "billing" } },
{ id: "login-loop", input: "I keep getting sent back to the login page.", expect: { category: "bug" } },
{ id: "export-csv", input: "How do I export my tasks to CSV?", expect: { category: "how-to" } },
{ id: "angry-mixed", input: "Your app is broken AND you charged me twice.", expect: { category: "billing" } },
{ id: "empty", input: " ", expect: { category: "other" } },
];
// Two prompt versions, simulated by two deterministic stand-ins with different blind spots.
const v3 = (input) => (/refund|charged/i.test(input) ? "billing" : /login|crash|broken/i.test(input) ? "bug" : /how do i/i.test(input) ? "how-to" : "other");
const v4 = (input) => (/broken|login|crash/i.test(input) ? "bug" : /refund|charged/i.test(input) ? "billing" : /how do i/i.test(input) ? "how-to" : "other");
function runEval(callModel) {
const results = cases.map((c) => ({ id: c.id, got: callModel(c.input), want: c.expect.category }));
const passed = results.filter((r) => r.got === r.want);
return { rate: passed.length / cases.length, failures: results.filter((r) => r.got !== r.want) };
}
const baseline = runEval(v3); // stored from the last approved run
const candidate = runEval(v4);
console.log(`baseline ticket-classifier@3: ${(baseline.rate * 100).toFixed(0)}%`);
console.log(`candidate ticket-classifier@4: ${(candidate.rate * 100).toFixed(0)}%`);
for (const f of candidate.failures) console.log(` regression: ${f.id} expected ${f.want}, got ${f.got}`);
const newlyBroken = candidate.failures.filter((f) => !baseline.failures.some((b) => b.id === f.id));
const gatePasses = candidate.rate >= baseline.rate && newlyBroken.length === 0;
console.log(gatePasses ? "gate: PASS" : `gate: FAIL (${newlyBroken.length} case(s) that passed before now fail)`);
process.exitCode = 0; // in CI you'd set 1 on failure; 0 here so the page's checker can run itbaseline ticket-classifier@3: 100%
candidate ticket-classifier@4: 80%
regression: angry-mixed expected billing, got bug
gate: FAIL (1 case(s) that passed before now fail)- Each case has an id, an input and an expected outcome. Real eval sets mix typical inputs, edge cases (an empty message) and every bug ever reported, and they live in the repository next to the prompt.
v3andv4stand in for two prompt versions. In a real harnesscallModelcalls the SDK with the prompt module and parses the structured output; the gate logic is identical.runEvalscores every case and keeps the failures, because a single pass rate hides which cases broke.- The candidate checks "broken" before "charged", so the angry customer who was charged twice is now filed as a bug: the pass rate drops and the gate lists exactly which case regressed.
- The gate has two conditions: the overall rate mustn't drop, and no case that passed before may fail now. The second matters because a change can fix two cases and break one, keep the same rate, and still break something a customer relies on.
- With a real model the outputs vary slightly between runs, so gates usually use a margin ("no more than 2 points below baseline") and run each case a few times or at a fixed low effort; deterministic checks such as a category label keep the noise small.
The most common prompt incident isn't a clever attack; it's an unreviewed edit. Someone tweaks wording in a prompt-management dashboard or a config file "just to fix one customer", nobody runs the evals, and a day later the refusal rate, the cost or the escalation rate has moved. You find out from a dashboard if you log prompt versions, and from angry users if you don't. The other classic is prompt drift through code: a helper that builds the system prompt gains a conditional (if (user.isEnterprise) system += …), so production now runs prompt variants nobody evaluated. The fix for both is the same discipline: every rendered variant has an id, every id has passing evals, and every call logs the id.
A teammate's pull request only reformats prompts/ticket-summary.mjs with Prettier: no wording changes. CI reports a changed fingerprint for ticket-summary@3. Is CI wrong?
Show answer
Probably not: if the formatter changed the string contents (line breaks or spaces inside a template literal), the bytes the model receives changed.
- The fingerprint hashes the rendered system prompt and template, not the source file. Reformatting code around strings leaves the hash alone.
- But template literals keep their whitespace exactly. If Prettier re-indented a multi-line template literal, the prompt now contains different indentation, which is a different prompt.
- A different prompt can behave differently (rarely by much for whitespace, but you don't know until you measure), and it also changes the prompt-cache prefix, so the first requests after deploy pay cache writes.
- So CI is right to flag it. The fix is to run the evals (they'll almost certainly pass), bump the version, or build prompts from arrays of lines joined with
\n(as inprompt-registry.mjs) so formatters can't touch the content.