CLAUDE LABJP
FORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as OctoberFORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as October
Articles/API & SDK
API & SDK/2026-04-27Advanced

Production-Grade Hallucination Defense for Claude API: A Multi-Layer Architecture

Prompt engineering alone is not enough to suppress hallucinations in production. After a real customer incident, I rebuilt the system around four defensive layers — input grounding, tool-use escape hatches, citations, and post-hoc verification. This is the implementation playbook.

hallucination3production111claude-api81guardrailadvanced11

Premium Article

"A user complained that we gave them a fake phone number." That was a real incident in a customer-support agent I was running last year. The system prompt explicitly said "do not guess information you don't know." It was Claude Sonnet 4.5 at temperature 0.3, with several integrated tools. By the standards of the time, it was a carefully built agent.

Hallucinations still happen. They happen in production.

This article starts from the moment I gave up on the assumption that better prompts alone would solve the problem. With four defensive layers — prompt-side grounding, inference-time tooling, output-time schema enforcement, and post-hoc verification — how far can you actually push fact-error rates down? I have collected the seven implementation patterns that made the largest difference in the systems I currently operate, with TypeScript code that runs as-is.

Why a single prompt loses

If you describe hallucination as "Claude lies sometimes," you will pick the wrong countermeasures. In production, I see at least three distinct failure modes.

Fabrication errors: Claude invents proper nouns, numbers, or URLs that look plausible but were never in the training data. Phone numbers, person names, and price tables are the most painful, because the business impact is direct.

Reasoning errors: Claude misreads the supplied context. The document says "cancellation is free up to 30 days in advance," and the answer says "cancellation is always free."

Instruction-skipping errors: You ask for JSON and get prose. You ask for a polite tone and the response slips into casual phrasing. These are hallucinations too, in the broad sense.

The three modes have different root causes. Fabrication is "refusal to admit not knowing." Reasoning errors are "failure to read context carefully." Instruction-skipping is "loss of formatting attention over long generations."

If you try to fix all three by stuffing more rules into a single prompt, the prompt swells and accuracy actually drops. My conclusion was simple: separate the layers, and use a different mechanism for each.

Layer 1: Input grounding as a hard contract

The most effective single intervention is to make it impossible for Claude to answer from its own knowledge. This is the basic idea of RAG (retrieval-augmented generation), but the production-quality move is to design grounding as a strong contract, not a polite request.

import Anthropic from "@anthropic-ai/sdk";
 
const client = new Anthropic();
 
interface RetrievedDoc {
  id: string;
  title: string;
  content: string;
  source_url: string;
}
 
async function answerWithGrounding(
  question: string,
  docs: RetrievedDoc[]
): Promise<string> {
  // Bad pattern: "please refer to these documents"
  // Production pattern: a hard contract — anything outside the documents is a violation
  const groundedSystem = `You are an internal knowledge bot.
 
Absolute rules:
1. You may only ground answers on information inside the <documents> section below.
2. Do not include any fact that is not present in <documents>, even if it is common knowledge.
3. If the documents are insufficient, answer exactly: "I cannot determine this from the provided information."
4. No guessing or inference. Quote proper nouns, numbers, dates, and URLs verbatim from <documents>.
 
Output format: end every response with "Sources: [doc_id1, doc_id2]" listing the documents you used.`;
 
  const docsBlock = docs
    .map((d) => `<document id="${d.id}" title="${d.title}">\n${d.content}\n</document>`)
    .join("\n\n");
 
  const response = await client.messages.create({
    model: "claude-sonnet-4-5",
    max_tokens: 1024,
    system: groundedSystem,
    messages: [
      {
        role: "user",
        content: `<documents>\n${docsBlock}\n</documents>\n\nQuestion: ${question}`,
      },
    ],
  });
 
  const text = response.content
    .filter((b): b is Anthropic.TextBlock => b.type === "text")
    .map((b) => b.text)
    .join("\n");
 
  return text;
}
 
// Usage:
// const answer = await answerWithGrounding("What is the refund policy?", retrievedDocs);
// Expected output:
// "Refunds are available in full for cancellations within 30 days of purchase.
//  Sources: [doc_42]"

The non-obvious detail here is that "absolute rules" needs three to five entries, not one. A single rule gets bent in ambiguous situations; multiple rules reinforce one another, and in my A/B tests violation rates roughly halved when I went from one rule to four. This is a quirk of how Claude weights instructions that I have confirmed several times in production traffic.

Wrapping the supplied content in <documents> tags is also intentional. Anthropic's prompt guidance recommends XML over Markdown delimiters, and in my experience Claude's attention locks on tagged blocks far more reliably than on --- separators.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
You will get a complete implementation path that takes hallucination from a customer-complaint problem to an acceptable residual risk — even after every prompt rewrite has stopped helping
You will learn to wire up self-consistency checks, LLM-as-judge verification, the Citations API, and JSON Schema guards together — with copy-paste TypeScript that runs as-is
You will know in advance the production-only failure modes such as judges going soft, citations returning empty strings, and tool schemas inviting fabrication, so you design around them from day one
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

API & SDK2026-06-25
When Your Support AI Is Confidently Wrong in Production — Notes on Refusing Outside Its Grounding and Routing to Humans
A field-tested approach to the Claude API support agent that demos perfectly yet states non-existent facts in production. Covers deciding 'don't answer' at retrieval time, grounded generation, measuring confident-wrong rate, and tuning escalation precision.
API & SDK2026-07-13
Coalescing Concurrent Claude API Calls: Single-Flight Against Duplicate Inference and Cache Stampede
A design for collapsing identical prompts that fire at the same instant into a single upstream Claude call, using single-flight (request coalescing). In-process and distributed implementations, jittered retries, and negative caching, with measured results.
API & SDK2026-07-03
How Many Concurrent Claude API Requests Can You Actually Hold? Sizing Production Infrastructure with Little's Law and Measured Memory
Concurrency, queue depth, and memory are numbers you can derive, not guess. A working method for sizing Claude API production deployments with Little's Law, a memory probe, and a 30-minute load check — learned the hard way from an OOM crash.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →