A production system prompt has five parts in this order: role (who the model is), capabilities (what it can do), constraints (what it must not do), output format (the shape of the response), and refusal policy (what to say when a request falls outside the role). Skip any one and the model guesses.
Each part has a job, and the guess is rarely what you want. I'll walk all five with before/after examples, cover the structure that maximises prompt-cache hits, then the six prompt and pipeline techniques that stop an LLM from hallucinating (grounding, citations, tools, structured output, "I don't know" permission, LLM-as-judge), and finally how to write LLM evals that catch regressions so a prompt edit cannot quietly break what already worked.
The cliché advice "be specific" isn't actionable. Specific about what? The five-part structure is what to be specific about. It works across Claude, GPT, Gemini, and local models because it covers the same gaps every model has: it doesn't know who it is, what it's allowed to do, what it must avoid, what shape the answer takes, or what to say when asked to go off-script.
Jump to:
- Part 1: Role
- Part 2: Capabilities
- Part 3: Constraints
- Part 4: Output format
- Part 5: Refusal policy
- Full example: before and after
- Structuring for prompt-cache hits
- Stop an LLM from hallucinating
- Write LLM evals that catch regressions
- FAQ
Part 1: Role
The role is one or two sentences telling the model who it is. Not "you are a helpful assistant", that's the default and produces generic output. Something specific.
Bad: You are a helpful assistant.
Good: You are a senior backend engineer specialising in MySQL optimisation. You have 15 years of production experience and tend toward pragmatic over theoretical solutions.
The specifics shape every subsequent generation. A "senior backend engineer" writes different code than a "junior developer learning Rails". A "compliance officer" answers questions about user data differently than a "marketing copywriter". Pick the role that matches the actual job.
Part 2: Capabilities
List the things the model is supposed to be able to do. This sounds redundant, the model knows what it can do, but it's where you tell the model what to apply that capability to.
Capabilities:
- Review SQL queries for performance issues
- Suggest index changes
- Explain EXPLAIN output line by line
- Compare MySQL versions (5.7, 8.0, 8.4) when version-specific behaviour matters
Capabilities act as soft routing. When a user asks "should this be an INDEX or a UNIQUE INDEX?", the model knows it's allowed to give a strong opinion because "suggest index changes" is in the capability list. When they ask "rewrite my Python code", the model is more likely to redirect because Python isn't in the capability list.
Part 3: Constraints
The opposite of capabilities, what the model must not do. Constraints are where you encode the rules that matter for your product:
Constraints:
- Never generate SQL that drops a production table
- Never execute commands. Only suggest them, then let the user run them.
- Never assume the user is on a specific MySQL version unless they say so. Ask.
- Never write SQL longer than 50 lines without proposing a refactor first.
Constraints prevent the model from being helpful in ways that are dangerous. They also prevent specific kinds of unhelpful (the 50-line SQL one, without that constraint, you sometimes get walls of SQL that the user can't review).
Write constraints as imperatives ("Never X") not preferences ("Avoid X"). The imperative form is more reliably followed.
Part 4: Output format
The shape of the response. This is the part most prompts skip, and it's the part that has the biggest impact on whether the model output is usable in your app.
For structured-output use cases, this overlaps with schema-constrained JSON (covered in How to Get Reliable JSON from an LLM). For free-text use cases:
Output format:
- Start with a one-line summary in italics.
- Show the recommended query in a SQL code block.
- Add 2-4 bullet points explaining why this is better than the original.
- If you suggest an index, show the CREATE INDEX statement separately.
- Use Markdown, not HTML.
The result: every response has the same shape, which makes the UI rendering predictable and the user's mental model consistent.
Part 5: Refusal policy
What happens when the user asks for something outside the role's scope. Without this, the model either:
- Tries to help anyway and produces low-quality output outside its area
- Refuses awkwardly with generic "I can't help with that"
- Goes off-topic for the rest of the conversation
A good refusal policy gives the model a specific way to redirect:
Refusal policy:
- If the user asks about a topic outside MySQL optimisation, briefly acknowledge it, then ask whether they want to refocus on the SQL question or end the session.
- If the user asks you to run a destructive command, decline and explain the risk in one sentence.
- If the user asks for legal or financial advice, redirect them to a qualified professional.
Concrete redirects beat generic refusals. The model now has a template for how to handle the case rather than improvising.
Full example: before and after
Before (typical first-draft system prompt):
You are a helpful AI assistant that helps users with their SQL queries.
Be polite and explain your reasoning.
After (five-part structured):
ROLE
You are a senior MySQL DBA with 15 years of production experience. You tend toward
pragmatic, indexable solutions over clever ones.
CAPABILITIES
- Review SQL queries for performance issues
- Suggest schema and index changes
- Explain EXPLAIN output line by line
- Identify when a query needs to become two queries
- Call out version-specific behaviour for MySQL 5.7, 8.0, and 8.4
CONSTRAINTS
- Never run commands; suggest them and let the user execute
- Never generate destructive SQL (DROP, TRUNCATE without WHERE) without an explicit
confirmation step
- Never assume the MySQL version; ask if it's not in the conversation
- Keep individual SQL outputs under 50 lines; refactor or break into stages if longer
OUTPUT FORMAT
Start with a one-sentence summary. Then the recommended query in a SQL code block.
Then 2-4 bullets explaining why. If an index would help, show the CREATE INDEX in
a separate code block.
REFUSAL POLICY
- If the user asks about non-MySQL topics, acknowledge briefly and offer to refocus
- If the user asks to run a destructive operation, decline and explain the risk
- If the user is panicking about a production issue, give the safest fix first and
the optimal fix second
The "after" version is longer, but every part has a job. The model output is dramatically more predictable. It's also cacheable, the entire prompt is stable across calls, so prompt caching makes it essentially free after the first invocation (covered in How to Cut LLM API Costs with Prompt Caching).
Structuring for prompt-cache hits
Put the system prompt first, in full. Put dynamic content (user message, retrieved RAG context, current timestamp) outside the system prompt, in the user message. This way the system prompt is a stable prefix that prompt caching can recognise.
{
system: SYSTEM_PROMPT, // The whole 200-line stable block, cached
messages: [
{ role: "user", content: `User question: ${userMessage}\n\nRelevant context: ${ragContext}` }
]
}Not:
{
system: `${SYSTEM_PROMPT}\n\nCurrent time: ${new Date()}`, // Dynamic: kills the cache
messages: [{ role: "user", content: userMessage }]
}The current time, request ID, user ID, anything that varies per call has to live in the user message, not the system prompt. Otherwise no two calls share a prefix and you pay full price every time.
Stop an LLM from hallucinating
A well-structured system prompt sets the role, but it does not stop the model from inventing facts. Six techniques actually reduce hallucination: ground the model with retrieved context, require inline citations, use tools for verifiable facts, constrain to a structured output, explicitly permit "I don't know", and run an LLM-as-judge to flag suspect responses. None eliminate hallucination, but stacked together they cut the rate dramatically. In my experience the biggest single gain comes from grounding the answer in retrieved context, and each added layer catches a different class of mistake.
"Tell it not to hallucinate" doesn't work because the model has no internal mechanism that distinguishes "I know this for certain" from "this is a plausible-sounding string of tokens". What works is changing the environment so the model has access to ground truth, is forced to expose its sources, and has explicit permission to say it doesn't know. Most of these live in the constraints and refusal-policy parts of the system prompt; two of them live in the pipeline around it.
Ground the model with retrieved context
The single biggest reduction comes from giving the model the actual source documents it should answer from, rather than letting it generate from training-data memory. This is Retrieval-Augmented Generation, the default architecture for any answer that depends on facts that change (your company's docs, current events, user data). Retrieve the relevant documents (covered in How to Build RAG with Embeddings and Vector Search), include them with clear markers, and instruct the model to answer only from that context:
You are answering questions about TechEarl's product. Use ONLY the documentation
below to answer. If the answer is not in the documentation, say so.
<documentation>
{{retrieved_chunks}}
</documentation>
User question: {{question}}
The "ONLY the documentation below" instruction is doing most of the work. Without it, the model freely mixes retrieved context with its training-data memory and you can't tell which is which. Note that the retrieved chunks go in the user turn, per the prompt-cache structure above, not in the system prompt.
Require inline citations
After every claim in the answer, require an inline citation pointing to the chunk that supports it:
For every factual statement in your answer, add a citation in square brackets
referencing the source: [source: doc-123, line 45-60]. Do not add citations for
opinions or general knowledge.
If a claim cannot be cited, do not make the claim.
That has two effects. You can verify post-hoc: a claim with a citation can be checked against its source, and an uncited claim in a system that requires citations is suspect. And the model self-corrects: when it knows it will have to cite, fewer "this sounds right" claims slip through. The format doesn't matter as long as it's parseable ([source: ...], <cite>...</cite>, or footnote-style [1]). Pick one and stick with it.
Use tools for verifiable facts
For facts the model is repeatedly wrong about (current date, current weather, your specific database row counts, today's stock price), give it a tool to look up the answer instead of generating it:
You have access to a tool: get_current_time(timezone)
Call this whenever you need to reason about the current time. Never guess.
The model is bad at "what's today's date" because its training data has no idea what "today" is. A tool call returns the actual answer. The same pattern works for currency conversions, user record lookups, document retrieval, anything with a deterministic answer. This is the foundation of agentic workflows, covered in How to Build an LLM Agent with Tool Use.
Constrain to a structured output
A free-text response is the maximum surface area for hallucination. "Summarise this customer's account status" lets the model invent details. "Return this JSON: { "status": "active|inactive|past_due", "last_login_date": "YYYY-MM-DD or null", "open_tickets": integer }" forces it to pick from the enum, produce a real date or null, and produce an integer. The enum constraint alone cuts the "creative liberty" hallucination rate hugely. This is the output format part taken to its strict form; the full pattern is in How to Get Reliable JSON from an LLM.
Explicitly permit "I don't know"
Models hallucinate more when they perceive they're "supposed to" answer, because training pushes them toward helpfulness. Put the permission in the refusal policy:
If the user asks something the documentation doesn't cover, say so directly. Use
phrasing like: "I don't see that covered in the available documentation."
It is better to admit a knowledge gap than to guess. Guessing is the failure mode
to avoid.
Added to a RAG system prompt, this single instruction takes a meaningful chunk out of the residual rate. Models that "want to help" stop trying when help would mean inventing, and start saying "I don't know" where they should have all along.
Run an LLM-as-judge
For the residual hallucinations that get past the first five, layer in a separate LLM call that checks whether the answer is grounded in the source material:
You are a fact-checker. Given a question, a model answer, and the source
documentation the answer should be based on, identify any claims in the answer
that are NOT supported by the documentation. List them in JSON:
{ "unsupported_claims": [...], "supported_claims": [...] }
Run it on every customer-facing answer before you ship it. If there are unsupported claims, regenerate or fall back to an "I'm not sure, can a human help?" template. The judge can hallucinate too, but it does so independently of the answer-generation model, so the chance both make the same wrong claim is far lower than either alone. For production-scale judging, Sonnet is a good default tier (How to Choose Between Claude Haiku, Sonnet, and Opus). Don't use the same model as your answer generation; you want some architectural diversity.
The order to stack them in production
- Grounding (RAG) first: the biggest single drop. Get the model reading real documents.
- Explicit "I don't know" permission: a one-line addition with a large effect.
- Citation requirements: a two-line addition that lets you verify and forces self-correction.
- Structured outputs where applicable: best for extraction and classification, less so for free-form QA.
- Tool use for verifiable facts: when there is a specific kind of fact the model gets wrong.
- LLM-as-judge: only for high-stakes outputs where the cost of the second call is justified.
Stop adding techniques when the residual rate is acceptable for your use case. For a casual chatbot, 1-2% might be fine. For a medical or legal summary, you want closer to 0.1% with humans in the loop above that. Measure it with an eval set (see the eval section below). The Anthropic guide on reducing hallucinations covers the citation and grounding patterns from Anthropic's side.
Write LLM evals that catch regressions
LLM evals are unit tests for prompts. They catch the moment a system prompt edit, a model switch, or a retrieval change quietly breaks a slice of your traffic, which is exactly the regression a human skimming a few outputs misses. The standard stack is a golden dataset of input-output pairs, a scoring method matched to each output type, and CI that fails the build when quality drops.
LLM behaviour is fragile in ways ordinary code is not. Change one word in a system prompt and a share of outputs suddenly look different; switch models and a prompt that produced clean JSON yesterday produces malformed JSON today. Without evals you find out from users. With evals you find out on the pull request.
Build a golden dataset
The dataset is the heart of the eval; without good cases the scoring does not matter. Pull cases from real traffic and mix four kinds:
- Happy path: the common queries that make up most of your traffic.
- Edge cases: long inputs, short inputs, odd characters, multilingual text.
- Adversarial: prompt-injection attempts, off-topic requests, requests the refusal policy should block.
- Regression cases: every bug you have fixed. When a user reports a wrong answer, add that input to the dataset before you fix the prompt.
Each case is { input, expected, metadata }, where the shape of expected depends on the scoring method (a string for exact match, a rubric for a judge, a sample acceptable answer for similarity). Store the dataset as a JSON file checked into the repo and version it with the prompt. It doubles as documentation of what good looks like.
Pick a scoring method per output type
| Method | Best for | Speed | Weak spot |
|---|---|---|---|
| Exact match | Structured outputs: JSON, classification labels, enums | Instant | Only works when there is one right answer |
| LLM-as-judge | Free-form text, multi-criteria quality, "is this answer correct" | Slow (an LLM call per case) | Only as good as the judge prompt |
| Embedding similarity | "Is this semantically close to the expected answer?" | Fast | Fooled by negation |
Exact match comes first whenever the output is structured, which is another reason to constrain to a structured output: parse the JSON and compare objects, compare the chosen label, or normalise an extracted value and compare.
Embedding similarity suits outputs where two valid answers phrase the same thing differently, such as a summary or a factual answer. Embed both, take the cosine similarity, and pass above a threshold you calibrate on your own data:
from openai import OpenAI
import numpy as np
client = OpenAI()
def te_embed(text):
return client.embeddings.create(model="text-embedding-3-small", input=text).data[0].embedding
def te_cosine(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def te_score(model_output, expected):
return te_cosine(te_embed(model_output), te_embed(expected))The catch is negation. "The patient is allergic to penicillin" and "The patient is not allergic to penicillin" embed very close together but mean opposite things. Where negation matters, use a judge.
LLM-as-judge is the catch-all for anything without an objective answer. It is the same pattern as the hallucination judge above, scored against a rubric:
You are an evaluator. You will be given a user question, the assistant's answer,
and (optionally) a reference answer. Score the assistant's answer on:
1. Correctness: are the facts accurate? (0-5)
2. Completeness: does it address all parts of the question? (0-5)
3. Tone: appropriate for a customer-support context? (0-5)
Return JSON: { correctness: int, completeness: int, tone: int, comments: string }
The judge prompt needs the same care as the prompt under test. Use a strong model for the judge, give it rubrics rather than vague criteria ("5: fully correct with no errors. 3: partially correct. 1: misleading."), run several independent judges and take the median when the stakes are high, and validate it by having a human grade a sample of cases and comparing. Ideally the judge is a different model from the one under test, so the two do not fail in the same way.
A runnable eval harness
import Anthropic from "@anthropic-ai/sdk";
import fs from "fs/promises";
const client = new Anthropic();
const dataset = JSON.parse(await fs.readFile("eval-dataset.json", "utf8"));
const SYSTEM_PROMPT = await fs.readFile("system-prompt.md", "utf8");
async function teRunModel(input) {
const response = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 2048,
system: SYSTEM_PROMPT,
messages: [{ role: "user", content: input }],
});
return response.content.find((b) => b.type === "text").text;
}
async function teJudge(question, answer, expected) {
const response = await client.messages.create({
model: "claude-opus-5-5", // a different, stronger model as the judge
max_tokens: 2048,
messages: [{
role: "user",
content: `Question: ${question}\n\nReference answer: ${expected}\n\nAssistant answer: ${answer}\n\nScore the assistant answer on correctness (0-5) and completeness (0-5). Return JSON: { correctness, completeness, comments }`,
}],
});
return JSON.parse(response.content.find((b) => b.type === "text").text);
}
const results = await Promise.all(dataset.map(async (case_) => {
const output = await teRunModel(case_.input);
const score = await teJudge(case_.input, output, case_.expected);
return { ...case_, output, score };
}));
const avgCorrectness = results.reduce((s, r) => s + r.score.correctness, 0) / results.length;
const passing = results.filter((r) => r.score.correctness >= 4).length;
console.log(`Average correctness: ${avgCorrectness.toFixed(2)}/5`);
console.log(`Passing (≥4): ${passing}/${results.length}`);
process.exit(avgCorrectness < 4.0 ? 1 : 0);Run it with node eval.mjs. It exits 1 when the average drops below 4.0 out of 5, which is what turns it into a CI gate.
Run evals in CI and track the trend
name: LLM Eval
on:
pull_request:
paths:
- "prompts/**"
- "src/llm/**"
jobs:
eval:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci
- run: node eval.mjs
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}This runs on any pull request that touches the prompts or the LLM code and fails it when the score drops under the gate. Set the gate from your baseline: if the current average is 4.3, gating at 4.0 allows normal variance and blocks real regressions. Tune it as the dataset grows.
Per-PR gating misses slow drift, where no single change trips the gate but twenty of them take you from 4.3 to 3.8. Log every run and chart the average per model version, per-case score history (regression-prone cases stand out), cost per run (which exposes prompt bloat), and which case categories are slipping. External tooling worth a look: Anthropic's guide to building tests, OpenAI's evals library, and Promptfoo, an open-source eval framework.
What to do next
For the techniques that compound with a well-structured system prompt:
- How to Get Reliable JSON from an LLM: the output-format part of the system prompt overlaps with structured outputs. Use both for production reliability.
- How to Build RAG with Embeddings and Vector Search: the retrieval layer behind grounding, the biggest single anti-hallucination technique.
For the LLM-tier and cost decisions a good system prompt enables:
- How to Choose Between Claude Haiku, Sonnet, and Opus: a strong system prompt is what lets you drop a workload from Sonnet to Haiku without quality loss.
External reference: the Anthropic prompt engineering guide covers the patterns Anthropic recommends. OpenAI's prompt engineering documentation covers GPT-specific patterns.
FAQ
Long enough to cover the five parts above; short enough to read in one sitting. In practice, production system prompts are 200-1,500 tokens. Below 200 tokens you're probably missing structure; above 1,500 you're probably duplicating yourself.
The length doesn't matter much for cost (prompt caching makes the system prompt essentially free after the first call), but it matters for cognitive overhead when you're maintaining and editing the prompt.
Second person: "You are X. You can Y. You must never Z." Models follow second-person instruction more reliably than first-person ("I am X. I will Y.") which the model can interpret as descriptive rather than directive.
Avoid third person ("The assistant is X"): it adds an unnecessary layer of indirection and the model sometimes ignores it.
Yes. Role first establishes who the model is, every subsequent part is interpreted through that role. Capabilities and Constraints next define what the role can and can't do. Output format and Refusal policy come last because they're applied at response-generation time.
If you put Constraints before Role, the model treats the constraints as general rules rather than rules-for-this-role and they bind less reliably.
Mostly yes. The five-part structure is engine-agnostic. The slight differences: Claude responds well to a clear hierarchy with markdown headers; current GPT models respond well to numbered lists; Gemini handles long XML-tagged sections well. The same content, lightly reformatted, works across all three.
Anthropic's recommended format wraps each section in XML-like tags (<role>...</role>); OpenAI's and Gemini's docs prefer markdown. Both work on the other engines.
Run an eval. Build a list of 20-50 representative user messages, plus a list of 10-20 adversarial messages (asking for things the constraints should block). Run them all through the model. Score whether each output matches what the system prompt should have produced.
The eval suite for this is covered in Write LLM evals that catch regressions above. The same eval catches regressions when you edit the system prompt.
Ideally no. A different model for the prompt under test and the judge reduces correlated failures: if both get something wrong the same way, you miss the regression. The judge should be at least as capable as the model being tested.
For factual-recall cases where two correct answers can be phrased differently, yes: embedding similarity is faster and cheaper. Where nuance, tone, negation or partial correctness matters, no. Most eval suites mix the two.
Start a little under your baseline: if the current average is 4.3 on a 5-point scale, gate at 4.0. That is tight enough to catch real regressions and loose enough to allow normal eval variance. If the gate blocks changes that were actually fine, loosen it; if regressions slip through, tighten it.
You can prompt it to be more careful, and there's a small effect, but "don't hallucinate" by itself does very little. The model has no internal mechanism for distinguishing what it knows from what it's confidently making up.
The six techniques above change the environment so the model has access to ground truth, exposes its sources, and has explicit permission to refuse. Those produce measurable reductions.
Modestly, not dramatically. Claude Opus hallucinates less than Sonnet, which hallucinates less than Haiku, but the gap is small compared to the gap between "no grounding" and "RAG with citations".
Spending money on a better model is the lazy answer. Spending the same money on retrieval and prompt engineering usually buys a larger reduction, because it attacks the cause (missing or unverified context) rather than the symptom.
RAG (Retrieval-Augmented Generation) is the architecture: retrieve relevant documents from a vector database, include them in the prompt, generate the answer. Grounding is the general concept of including authoritative source material in the prompt.
RAG is the most common form of grounding, but you can ground with any source: a pasted-in document, a tool-call result, a database query output. The benefit is the same: the model answers from real text rather than from training-data memory.
Build an eval set of 100-500 questions with verified correct answers. Run them through your system. Count how many responses contain claims that contradict the verified answer or that aren't in the cited source.
For ongoing measurement, an LLM-as-judge on a sampled fraction of production traffic gives you a cheap continuous signal.
No. Fine-tuning teaches the model new patterns; it doesn't fix the fundamental issue that the model has no internal "I don't know" signal. A fine-tuned model can still hallucinate on questions outside its training set.
Fine-tuning helps when the task is narrow and well-defined; combine it with the grounding techniques above for the lowest residual hallucination rate.
Sources
Authoritative references this article was fact-checked against.
- Models overview: Claude API documentationplatform.claude.com
- Model deprecations: Claude API documentationplatform.claude.com





