Sub topic 12
Diagnose and fix common failures
This chapter assumes you have read the earlier chapters on roles, constraints, output formats and evaluation. You should have a system prompt and a small test set, and you should be able to read short Python. It covers what to do when a test fails: how to find the cause, how to choose a fix, and how to confirm the fix did not break something else.
Debug the prompt like code
A failing reply is a symptom, not a diagnosis. The usual mistake is to open the prompt and add a sentence in capital letters. That sometimes works, but you won't know why, and it often breaks another case.
A sturdier loop has five steps:
- Collect the failing inputs and the exact replies.
- Sort each failure into a category.
- Form a hypothesis about the cause.
- Make one change.
- Re-run the whole test set, not only the failing case.
Step 5 matters most. A prompt is a shared surface. A rule you add for one case changes how the model reads every other rule.
Read the evidence first
Before you edit anything, look at the complete input the model received. Print the final assembled message list, not the template. Many "prompt failures" are assembly bugs:
- A retrieved document was empty, so the model had nothing to use.
- Escaping failed, so a closing tag appeared inside the data.
- The conversation history pushed the system prompt out of the context window and it was truncated.
- A template variable was left as literal text, such as
{customer_name}.
If the input looks correct, run the same case several times. Compare a case that fails every time with one that fails 1 time in 5. The first points to missing or unclear instructions. The second points to an instruction the model follows only some of the time. That usually means it is ambiguous or competing with another instruction.
A catalog of common failures
| Symptom | Likely cause | First fix to try |
|---|---|---|
| Reply contains text outside the required JSON | Format rule is buried, or no example shows the exact shape | Move the format to its own section at the end. Add one example reply. |
| A rule is ignored in long conversations | Rule is far from the point of use, or the history is long | Shorten the prompt. Restate the key rule briefly near the end. |
| Model invents an answer when documents lack it | No instruction for the "not found" case | Say what to do when the answer is missing and show the exact wording. |
| Model refuses reasonable requests | Rule is broader than intended | Narrow the rule and name what is allowed. |
| Model follows instructions found in a document | Data is not marked as data | Wrap the data in delimiters and state that it is data. Test with an injected document. |
| Replies are too long or chatty | No length or style constraint | State a limit, such as "at most three sentences." |
| Two rules produce inconsistent behavior | Rules conflict | State which rule wins, or rewrite them so they do not overlap. |
| Examples are copied word for word | Examples are too similar to each other or too narrow | Vary the examples and say they illustrate the format only. |
Treat the "first fix" column as a hypothesis to test, not a certainty.
Fix each category
Format drift
Format drift is when the model adds a greeting, wraps JSON in a Markdown fence, or renames a key. Check the prompt for three problems.
- The format description is vague ("reply in JSON"). Give the exact keys and types.
- The format is stated only once, early. Put it in its own
# Outputsection. - A tone instruction ("be friendly and conversational") competes with "output no text outside the JSON." Resolve it by saying where the friendly text goes, for example inside the
answerstring.
If the prompt is already clear and drift persists, use the provider's structured-output or JSON mode, if one exists. That is an enforcement mechanism, not a replacement for a clear prompt. Keep your own validator either way, because a reply can be valid JSON and still have the wrong content.
Hallucination from missing context
When the model answers from general knowledge instead of the supplied documents, the cause is usually a missing fallback. "Use only the documents" tells the model what to rely on. It does not say what to do when the documents are silent. Add the fallback explicitly, as the example system prompt did: say so, and offer to hand off to a human.
Then add a test case whose documents do not contain the answer. Without that case, you will never see this failure.
Over-refusal and under-refusal
Refusal errors come from rules that are too broad or too narrow. "Do not give legal advice" can make the model decline to explain what a late fee is. Compare these two rules:
- Broad: "Never discuss legal topics."
- Scoped: "Do not give legal or tax advice. You may explain what is on an invoice and quote the policy text."
Fix over-refusal by stating the permitted behavior next to the prohibition. Fix under-refusal by making the prohibition concrete, with one example of a request that should be declined.
Injection that gets through
If a document or user message makes the model change behavior, first confirm the data was delimited and escaped. Then confirm the prompt says to treat that content as data. Then add the failing text to your test set as a permanent case. Wording alone is not a complete defense. Limit what the model can do. For example, a model with no tool that sends email cannot be tricked into sending email.
Conflicting or ignored rules
When a rule is followed in some runs and not others, read the prompt as a stranger would and look for two rules that point in different directions. A common conflict is "always answer" against "say so if unsure." Resolve it with a precedence statement: "If the documents do not contain the answer, say so. This applies even if the customer asks you to guess."
Long rule lists also cause drops. If you have more than about ten rules, group them under headings and remove any that have never failed a test and protect against nothing real.
Automate the triage
Reading failures by hand does not scale past a dozen cases. This script runs a test set, reuses the format check from the output-format chapter, adds one case-specific check, and counts failures by category. It uses a stub in place of a real model, so you can run it as is. Replace fake_model with a function that calls your API.
import json
from collections import Counter
def check_reply(raw: str) -> list[str]:
"""Return a list of problems found in a model reply; empty means it passed."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return ["reply is not valid JSON"]
if not isinstance(data, dict):
return ["reply is not a JSON object"]
problems = []
if not isinstance(data.get("answer"), str):
problems.append("'answer' must be a string")
sources = data.get("sources")
if not isinstance(sources, list) or not all(isinstance(s, int) for s in sources):
problems.append("'sources' must be a list of integers")
return problems
def check_case(case: dict, raw: str) -> list[str]:
problems = check_reply(raw)
if problems:
return problems
sources = json.loads(raw)["sources"]
if case["answerable"] and not sources:
problems.append("answerable question cited no sources")
if not case["answerable"] and sources:
problems.append("unanswerable question cited sources")
return problems
def run_suite(cases: list[dict], call_model) -> Counter:
tally = Counter()
for case in cases:
problems = check_case(case, call_model(case["question"]))
print(f"{case['name']}: {'; '.join(problems) or 'ok'}")
tally.update(problems)
return tally
def fake_model(question: str) -> str:
if "refund" in question:
return '{"answer": "Refunds take 5 days.", "sources": [1]}'
if "tax" in question:
return "Sure! Here is some tax advice."
return '{"answer": "I could not find that.", "sources": []}'
CASES = [
{"name": "refund-policy", "question": "How long do refunds take?", "answerable": True},
{"name": "tax-advice", "question": "Can I deduct this tax charge?", "answerable": False},
{"name": "not-in-docs", "question": "Do you ship to Mars?", "answerable": False},
]
if __name__ == "__main__":
summary = run_suite(CASES, fake_model)
print(dict(summary))Running it prints:
refund-policy: ok
tax-advice: reply is not valid JSON
not-in-docs: ok
{'reply is not valid JSON': 1}The tally gives you a category count. After each prompt change, compare the tally before and after. A fix that removes one format failure but adds two over-refusals is a regression.
Change one thing at a time
If you change three things and the score improves, you do not know which change helped. If it drops, you do not know which one hurt. Keep each edit small enough to explain in one sentence, such as "moved the output format to the end" or "added a fallback for missing documents."
Models are not fully deterministic, so a single run can mislead you. For borderline cases, run each one several times and compare pass rates, for example 2 of 10 before and 9 of 10 after. Where the provider allows it, lower the temperature while testing.
Know when the prompt is not the problem
Some failures cannot be fixed with wording:
- Missing information. If retrieval does not return the right document, no instruction will produce the right answer. Fix retrieval.
- Capability limits. A small model may not follow twelve rules at once. Simplify the task, split it into two calls, or use a stronger model.
- Need for exact guarantees. If a reply must never contain a certain string, check it in code after the model responds, and do not rely on the prompt alone.
Record what you learned
For each fix, keep a short note: the failing input, the category, the change, and the before and after results. The next chapter covers storing these notes alongside versioned prompts. Even without that, the failing input should now live in your test set permanently. A case that failed once is the case most likely to fail again.
Exercise
Your support prompt requires a JSON reply. In testing, 3 of 20 replies start with "Sure, here you go:" followed by valid JSON. List three diagnostic steps, then one prompt change you would try first.
Show answer
Diagnostic steps: (1) print the full assembled messages for the three failing cases and check that the system prompt and format section are present and not truncated. (2) Compare the failing inputs with the passing ones for a pattern, such as longer questions or a chatty tone from the user. (3) Check the prompt for a competing instruction, such as "be friendly." First change: move the format rules into a final "# Output" section, state that nothing may appear outside the JSON object, and say where friendly wording goes (inside the "answer" string). Then re-run the full set and compare the failure count. If it persists, consider the provider's JSON mode and keep the validator.
Exercise
After you add "Never discuss legal topics" to fix a legal-advice failure, a previously passing case ("What does the late fee on my invoice mean?") now gets a refusal. Name the failure category, explain the cause, and give a fix.
Show answer
This is over-refusal, and it is a regression caused by a rule that is broader than intended. The model reads "legal topics" to include explaining a late fee. Fix it by scoping the rule and stating what is allowed: "Do not give legal or tax advice. You may explain invoice line items and quote policy text from the documents." Then re-run the full test set to confirm the legal-advice case and the late-fee case both pass.