Claude Citations: Ground Answers in Documents and Return Not Found
👋 In plain words: When Claude answers from your documents, you want two guarantees: every claim comes from a document you supplied, and Claude says “not found” when the documents do not contain the answer. This lesson builds both, step by step, with Anthropic’s citations feature and a test that catches made-up answers.
An assistant that answers questions about your test plans, runbooks or requirements is only useful if it never invents an answer. In this lesson you will send documents with citations enabled, read the quoted source text and location for every claim, instruct Claude to return a fixed “NOT_FOUND” answer when the documents do not cover the question, and test both behaviours with pytest-style checks.
🔑 Key terms
- Grounding: answering only from supplied sources, not from the model’s general knowledge.
- Citation: a link from a sentence in the answer to the exact source text that supports it.
- cited_text: the quoted source passage in a citation.
- Hallucination: a confident answer that is not supported by the sources or by facts.
🪜 Step 1: Prepare the documents
Use plain-text documents for this lesson. Each becomes a document content block with a title. Turn on citations with "citations": {"enabled": True} on every document block (all or none):
📄 docs.py
RUNBOOK = """Staging deploys run every weekday at 14:00 UTC.
If the payments sandbox is down, mark payment tests as blocked, not failed.
Flaky tests are quarantined after 3 failures in 7 days."""
TEST_POLICY = """Every bug fix needs a regression test.
Release candidates need a full regression run with zero critical failures.
Performance tests run weekly on Sunday."""
def doc(text: str, title: str) -> dict:
return {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": text},
"title": title, "citations": {"enabled": True}}
🪜 Step 2: Ask a question with citations enabled
📄 ask_cited.py
import anthropic
from docs import RUNBOOK, TEST_POLICY, doc
client = anthropic.Anthropic()
SYSTEM = """Answer only from the provided documents. If the documents do not contain the answer,
reply exactly: NOT_FOUND"""
def ask(question: str):
return client.messages.create(
model="claude-opus-5-5",
max_tokens=1000,
system=SYSTEM,
messages=[{"role": "user", "content": [doc(RUNBOOK, "QA Runbook"), doc(TEST_POLICY, "Test Policy"),
{"type": "text", "text": question}]}],
)
if __name__ == "__main__":
r = ask("What should I do with payment tests when the payments sandbox is down?")
for block in r.content:
if block.type != "text":
continue
print("TEXT:", block.text)
for c in block.citations or []:
print(f" cited from '{c.document_title}' (doc {c.document_index}, "
f"chars {c.start_char_index}-{c.end_char_index}): {c.cited_text!r}")⌨️ Terminal
python ask_cited.py🖥️ Output (sample run)
TEXT: Mark them as blocked, not failed.
cited from 'QA Runbook' (doc 0, chars 48-123): 'If the payments sandbox is down, mark payment tests as blocked, not failed.'
- With citations on, the answer is split into several text blocks. Cited blocks carry a
citationslist. - Each citation gives the quoted source text and its location:
char_locationwith character indexes for plain text,page_locationwith page numbers for PDFs, andcontent_block_locationfor custom content.
🪜 Step 3: Make “not found” a first-class answer
Grounding fails most often on questions the documents do not answer. Without an explicit path, Claude may fill the gap from general knowledge. Give it a fixed, machine-checkable answer:
📄 not_found.py
from ask_cited import ask
r = ask("Which browser versions must we support?")
answer = "".join(b.text for b in r.content if b.type == "text").strip()
print("answer:", answer)
print("grounded refusal" if answer == "NOT_FOUND" else "WARNING: answered without a source")⌨️ Terminal
python not_found.py🖥️ Output (sample run)
answer: NOT_FOUND
grounded refusal
- A fixed token such as
NOT_FOUNDis easy to test and easy for the UI to turn into “I could not find this in the runbook”. - Ask Claude to cite every claim. An answer sentence with no citation is a signal to check.
🪜 Step 4: Verify grounding automatically
Two cheap checks catch most grounding failures. This runs locally on answer blocks shaped like the ones above:
📄 verify.py
from types import SimpleNamespace as NS
SOURCES = {
0: "Staging deploys run every weekday at 14:00 UTC.\nIf the payments sandbox is down, mark payment tests as blocked, not failed.",
}
def check_grounding(blocks) -> list[str]:
problems = []
for b in blocks:
text = b.text.strip()
if not text or text == "NOT_FOUND":
continue
if not b.citations:
problems.append(f"uncited claim: {text!r}")
for c in b.citations or []:
if c.cited_text not in SOURCES.get(c.document_index, ""):
problems.append(f"citation text not found in document {c.document_index}")
return problems
good = [NS(text="Mark them as blocked, not failed.", citations=[NS(document_index=0, cited_text="mark payment tests as blocked, not failed.")])]
bad = [NS(text="Payment tests should be retried 3 times.", citations=None)]
print("good answer:", check_grounding(good) or "OK")
print("bad answer :", check_grounding(bad))⌨️ Terminal
python verify.py🖥️ Output
good answer: OK
bad answer : ["uncited claim: 'Payment tests should be retried 3 times.'"]
- Uncited claim: a sentence with no source. Flag it, or fail the test in your evaluation suite.
- Citation mismatch: the quoted text is not in the document you sent. Rare with the citations feature, but it catches bugs in your own document handling.
🪜 Step 5: Know the rules and limits
- Citations and structured outputs do not mix. Using
citationstogether withoutput_config.formatreturns a 400 error. If you need JSON, extract structured data in a second step, or ask for citations inside your own schema fields. - All or none. Enable citations on every document block in a request, or on none.
- Do not echo citations back in user turns. Under API version
2026-10-21, atextblock with a non-emptycitationslist inside a user message is rejected with a 400. Sending Claude’s cited reply back as an assistant turn is fine. - Documents go before the question. Put documents first and the question last (Lesson 14).
🌍 Real-world example: Ravi’s runbook bot
Ravi’s runbook bot once told a new tester to “retry payment tests three times”, a rule that existed in no document. He enabled citations, added the NOT_FOUND instruction, and added 15 unanswerable questions to his golden set. The bot now says “not in the runbook” for those, and every other answer shows the quoted runbook line underneath.
🧪 Practice Questions
Question 1. A documentation assistant sometimes answers questions that the supplied documents do not cover, using general knowledge. Which two changes address this? (Choose 2.)
- A. Enable citations and instruct a fixed response such as NOT_FOUND when the documents lack the answer
- B. Move the documents into the system prompt
- C. Add unanswerable questions to the evaluation set and check for the NOT_FOUND response
- D. Use a larger max_tokens
Show answer
Answer: A and C. A defined not-found path plus citations makes grounding explicit, and evaluation with unanswerable questions keeps it verified.
Question 2. A request sets citations on the document blocks and output_config.format with a JSON schema. What happens?
- A. Claude returns JSON with citations inside
- B. The API returns a 400 error because citations and structured output formats are incompatible
- C. Citations are silently ignored
- D. The schema is ignored
Show answer
Answer: B. The two features cannot be combined in one request. Extract JSON in a separate step, or design your own citation fields.
Question 3. Which citation location type do you get for a plain-text document?
- A. char_location with start and end character indexes
- B. page_location with page numbers
- C. line_location with line numbers
- D. No location
Show answer
Answer: A. Plain text uses character offsets. PDFs use page_location, and custom content uses content_block_location.
Question 4. An app copies Claude’s cited answer blocks, citations included, into the next user message under API version 2026-10-21. What happens?
- A. It works and improves accuracy
- B. The request is rejected with a 400 error
- C. Citations are converted to plain text automatically
- D. The cache is reused
Show answer
Answer: B. Under 2026-10-21, text blocks with non-empty citations are not allowed in user messages. Send the reply back as an assistant turn, or strip the citations.
📝 Assignment
- Task 1: Load two of your team’s real runbooks or test policies and ask five questions with citations enabled.
✅ Done when: every answer shows its cited text. - Task 2: Add five questions the documents cannot answer and check that each returns
NOT_FOUND.
✅ Done when: all five do, or you have improved the system prompt until they do. - Stretch: Turn
check_groundinginto a pytest suite that runs against live answers for 10 questions and fails on any uncited claim.
✅ Done when: the suite runs in under a minute and reports uncited sentences by question.
❓ Frequently Asked Questions
🤔 How do I get Claude to cite sources?
Send your sources as document blocks with "citations": {"enabled": True}. Claude’s answer then includes citation objects with the quoted text and location.
🤔 How do I stop Claude from hallucinating answers from documents?
Instruct it to answer only from the documents and to return a fixed not-found response otherwise, enable citations, and test with unanswerable questions.
🤔 Can I use citations with JSON output?
Not in the same request. Citations and output_config.format are incompatible.
🤔 Do citations work with PDFs?
Yes. For PDFs, citations use page_location with page numbers.
🏁 Summary
- Enable citations on every document block; read
cited_textand the location on each citation. - Give Claude a fixed, testable not-found answer for missing information.
- Verify automatically: flag uncited claims and citation mismatches.
- Citations cannot be combined with structured output formats, and must not appear in user turns under
2026-10-21. - Keep unanswerable questions in your evaluation set.
Next, continue with RAG vs Long Context with Claude: When to Retrieve.
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.