Claude Failure Modes: Hallucination, Refusal, Format Drift, Context Loss
👋 In plain words: When a Claude feature gives a bad result, the first question is not “how do I patch this answer?” but “what kind of failure is this, and where did it start?” This lesson gives you a checklist of six failure modes, shows how each looks in a trace, and teaches you to decide whether your code or the model output is at fault before you fix anything.
The CCDV-F skill “Failure-Mode Diagnosis” asks you to analyse a trace or reproduction, identify the failure mode (hallucination, refusal, under-acting, context loss, format drift or inconsistent output), isolate whether it originates in the integration layer or in model output, and pick a recovery that addresses the cause rather than the symptom. In this lesson you will learn each mode’s signature, handle refusals correctly in code, build a small diagnosis helper, and practise choosing cause-level fixes.
🔑 Key terms
- Hallucination: a confident statement not supported by the input, the tools or facts.
- Refusal: Claude declines a request; the response has
stop_reason: "refusal". - Under-acting: answering without doing the needed work (no tool call, no check).
- Context loss: forgetting an instruction or fact given earlier in the session.
- Format drift: output gradually departs from the required format.
- Integration layer: your code around the model: request building, parsing, tools, history, retries.
🪜 Step 1: Learn the six signatures
| Failure mode | What you see | Usual causes | Cause-level fix |
|---|---|---|---|
| Hallucination | Specific facts with no source in input or tool results | Missing grounding, no “not found” path, under-acting | Grounding with citations and NOT_FOUND (Lesson 20); require tool use for facts |
| Refusal | stop_reason == "refusal", little or no text |
Request falls into a declined category; or misread intent | Handle it in code; rephrase legitimate intent with clear context; fall back where supported |
| Under-acting | No tool calls when data was needed | Vague tool descriptions; no instruction to use tools; low effort | Tool guidance, better descriptions, adequate effort (Lessons 24, 36) |
| Context loss | Later turns ignore earlier rules | Bloated history, buried instructions, pruning that dropped them | Context management, re-state rules, enforce with hooks (Lessons 19, 40) |
| Format drift | Extra prose, wrong keys, capitalised labels | No schema, prefill-era tricks, long conversations | Structured outputs, strict tools, validation (Lesson 22) |
| Inconsistent output | Same input, different answers | Ambiguous criteria, borderline cases | Precise criteria, examples, evals with repeat runs (Lessons 7, 15) |
🪜 Step 2: Decide which layer is at fault
Before changing a prompt, check whether your code caused the failure. Ask four questions in order:
- Did the model receive what you think it received? Log the exact request. Missing documents, truncated history and wrong tool lists are integration bugs.
- Did your code read the response correctly? Wrong content block index, ignoring
stop_reason, stopping streams early (Lesson 9) are integration bugs. - Did tool results reach the model? Missing
tool_result, swallowed errors (Lesson 32) are integration bugs. - Only then: was the model’s output wrong given a correct request? That is a model-output problem: fix prompts, tools, examples, effort or model choice.
🪜 Step 3: Handle refusals in code
A refusal is a normal HTTP 200 response with stop_reason: "refusal". Check it before reading content, and give the user a useful message:
📄 refusal.py
import anthropic
client = anthropic.Anthropic()
def answer(question: str) -> str:
r = client.messages.create(model="claude-opus-5-5", max_tokens=500,
messages=[{"role": "user", "content": question}])
if r.stop_reason == "refusal":
category = r.stop_details.category if r.stop_details else None
return f"[declined: category={category}] Please rephrase or contact support."
if r.stop_reason == "max_tokens":
return "[partial answer] " + "".join(b.text for b in r.content if b.type == "text")
return "".join(b.text for b in r.content if b.type == "text")
print(answer("How do I write a pytest fixture for a database connection?"))
print(answer("Write working malware that steals browser passwords."))⌨️ Terminal
python refusal.py🖥️ Output (sample run)
Use a fixture that opens the connection, yields it to the test, and closes it afterwards, for example with scope='session' for speed.
[declined: category=cyber] Please rephrase or contact support.
stop_detailsis populated only for refusals; always guard forNone.- Do not retry a refusal in a loop. If a legitimate request is declined (for example a security tester’s question), add the legitimate context, or use the server-side fallback features where Anthropic offers them for your model.
🪜 Step 4: Diagnose from a trace automatically
This helper applies the signatures to a simplified trace record. It runs locally:
📄 diagnose.py
def diagnose(trace: dict) -> list[str]:
findings = []
if trace["stop_reason"] == "refusal":
findings.append("refusal -> handle in code; check whether the request was legitimate and add context")
if trace["needs_data"] and not trace["tool_calls"]:
findings.append("under-acting -> require tool use for factual answers; improve tool descriptions")
claims = trace.get("claims", [])
unsupported = [c for c in claims if not any(c.lower() in src.lower() for src in trace["sources"])]
if unsupported:
findings.append(f"possible hallucination -> unsupported claims {unsupported}; add grounding + NOT_FOUND")
if trace.get("schema_errors"):
findings.append("format drift -> use structured outputs / strict tools and validate")
if trace.get("request_missing"):
findings.append(f"integration bug -> request was missing {trace['request_missing']}; fix the code first")
return findings or ["no known failure signature"]
traces = {
"T1": {"stop_reason": "end_turn", "needs_data": True, "tool_calls": [], "sources": [],
"claims": ["build 812 failed due to a DNS outage"]},
"T2": {"stop_reason": "end_turn", "needs_data": True, "tool_calls": ["get_logs"],
"sources": ["TimeoutError waiting for #pay-button"], "claims": ["TimeoutError waiting for #pay-button"],
"schema_errors": ["missing key 'severity'"]},
"T3": {"stop_reason": "end_turn", "needs_data": True, "tool_calls": ["search_docs"], "sources": [],
"claims": ["refunds take 5 days"], "request_missing": "the retrieved documents (empty list sent)"},
}
for name, t in traces.items():
print(name)
for f in diagnose(t):
print(" ", f)⌨️ Terminal
python diagnose.py🖥️ Output
T1
under-acting -> require tool use for factual answers; improve tool descriptions
possible hallucination -> unsupported claims ['build 812 failed due to a DNS outage']; add grounding + NOT_FOUND
T2
format drift -> use structured outputs / strict tools and validate
T3
possible hallucination -> unsupported claims ['refunds take 5 days']; add grounding + NOT_FOUND
integration bug -> request was missing the retrieved documents (empty list sent); fix the code first
Notice T3: the answer looks like a hallucination, but the root cause is an integration bug: the retrieved documents were never sent. Fixing the prompt would not help.
🪜 Step 5: Choose the recovery that fixes the cause
| Symptom | Symptom-level “fix” (avoid) | Cause-level fix |
|---|---|---|
| Wrong facts | Retry until it looks right | Ground in sources; check retrieval and tool results reach the model |
| Truncated answers | Retry | Detect max_tokens; raise the limit or shorten the task |
| JSON breaks occasionally | Regex clean-up | Structured outputs + validation |
| Rules forgotten late in sessions | Repeat the rule in every message | Context management + deterministic enforcement |
| Agent never calls tools | Force tool choice (rejected on current models) | Clear tool guidance and descriptions; adequate effort |
| Different answers each run | Run 5 times and vote in production | Precise criteria, examples; measure consistency in evals |
🌍 Real-world example: Ravi’s “hallucinating” docs bot
Ravi’s docs bot started inventing refund rules. The team blamed the model and planned a model change. Ravi logged the full request first: after a search-index migration, the retrieval step returned an empty list, so Claude received no documents at all. The fix was in the integration layer (an alert when retrieval returns nothing, and a NOT_FOUND instruction). The model was never the problem.
🧪 Practice Questions
Question 1. A support bot invents policy details. Logs show the retrieval step returned an empty list for those questions, but the bot still answered. What is the cause-level fix?
- A. Switch to a larger model
- B. Fix retrieval and add a grounding rule with a NOT_FOUND path when no documents are supplied
- C. Retry until the answer matches the policy
- D. Increase max_tokens
Show answer
Answer: B. The model received no sources, so the integration layer is at fault, and the prompt lacked a not-found path.
Question 2. A response has HTTP status 200, stop_reason “refusal” and no text. Code crashes reading content[0].text. What should change?
- A. Check stop_reason before reading content and handle refusals with a clear message
- B. Retry the request in a loop until it succeeds
- C. Treat it as a 500 error
- D. Raise max_tokens
Show answer
Answer: A. Refusals are normal responses that must be handled explicitly; retrying the same request does not change the decision.
Question 3. Which two failures are most likely in the integration layer rather than the model output? (Choose 2.)
- A. The tool result is never appended, so the agent repeats the call
- B. The model picks a slightly different wording each run
- C. The parser reads content[0] while the first block is a thinking block
- D. The model declines a malicious request
Show answer
Answer: A and C. Missing results and wrong parsing are code defects; wording variation and appropriate refusals are model behaviour.
Question 4. After a long session, the assistant stops following “answer in one line”. Which fix addresses the cause?
- A. Repeat the rule in capitals in every user message
- B. Manage context (prune, compact or start fresh) and re-state the rule as a system-level instruction; enforce critical rules in code
- C. Switch to Haiku
- D. Disable streaming
Show answer
Answer: B. The rule was lost in a bloated context. Context management and deterministic enforcement address that cause.
📝 Assignment
- Task 1: Take three bad outputs from one of your Claude features and classify each with the table in Step 1.
✅ Done when: each has a failure mode and a suspected layer. - Task 2: Add
stop_reasonhandling forrefusalandmax_tokensto every Claude call in one project.
✅ Done when: a test with a mocked refusal passes (Lesson 47). - Stretch: Extend
diagnose()with a check for context loss: a rule from the first turn that a later answer violates.
✅ Done when: a sample trace with a violated rule is flagged.
❓ Frequently Asked Questions
🤔 What are the most common LLM failure modes?
Hallucination, refusal, under-acting, context loss, format drift and inconsistent output.
🤔 How do I reduce Claude hallucinations?
Ground answers in supplied sources with citations, give a NOT_FOUND path, require tool use for facts, and check that sources actually reach the model.
🤔 How do I handle a Claude refusal in code?
Check stop_reason == "refusal" before reading content, read stop_details if present, and show a helpful message instead of retrying blindly.
🤔 How do I know if a bug is in my code or in the model?
Log the exact request and response. If the request was wrong, the response was misread, or tool results were lost, it is your code. Only a correct request with a wrong output is a model-output problem.
🏁 Summary
- Six modes: hallucination, refusal, under-acting, context loss, format drift, inconsistency.
- Check the integration layer first: request contents, response parsing, tool results.
- Handle
refusalandmax_tokensstop reasons explicitly. - Prefer cause-level fixes (grounding, schemas, context management, tool guidance) over retries.
- Keep a diagnosis checklist and run it on real traces.
Next, continue with Claude Prompt Injection Defense: Layered Mitigations.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.