CCDV-P Study Guide
Free study guide for the Claude Certified Developer - Professional (CCDV-P) exam: 25 lessons, one per official skill, on running Claude systems in production. One chapter per exam domain, one page per lesson, in the order the official exam guide lists them.
2. Domain 2: Production Integration, Reliability, and Knowledge Grounding
2.4. 2.4 Retrieval and knowledge grounding at scale
CCDV-P · Domain 2 · Lesson 2.4 · 21 min read
Agentic search vs RAG, chunking, contextual retrieval, hybrid search, reranking, citations and confidence signals, and finding the stage that lost the passage.
Why a cited answer can still be wrong
Halden Regional Health runs a policy assistant for its clinicians. About 4,000 doctors, nurses and pharmacists ask it roughly 11,000 questions a day, and it answers from 60,000 clinical guidelines and formulary documents, each answer with a link to its source. Around 400 of those documents are revised every month. The assistant has been popular for a year, and its dashboards are green.
Then a pharmacy audit of 500 dosing answers found 23 that cited the wrong version of a policy. The worst case: a nurse asked how to adjust an anticoagulant for a patient with reduced kidney function, and the answer quoted version 3 of the renal dosing policy, accurately and with a working link. Version 4, effective since March, had changed that adjustment. Every one of the 23 answers was faithful to its source. The source was out of date.
A model on its own cannot fix this. Claude knows nothing about Halden's policies, and nothing in its training says which version is in force today. Whatever reaches the context window is the evidence it reasons from, so the quality of the answer is capped by the quality of what retrieval hands it. Retrieval and knowledge grounding is the engineering of that hand-off: finding the right passages among millions, giving them to Claude in a form it can cite, and making the answer show how well it is supported.
Agentic search or a pre-built pipeline: what decides
The first question is whether you need a retrieval pipeline at all, and if so which kind. Teams often reach for a vector database by reflex. There are really three options, and the corpus and the query decide between them.
Full context means putting the whole knowledge base in the prompt. Anthropic's contextual retrieval write-up gives the threshold: under about 200,000 tokens (roughly 500 pages), include everything and skip retrieval, with prompt caching keeping repeat requests fast and cheap. A pre-built RAG pipeline (retrieval-augmented generation) does the work before the model runs. It splits documents into chunks, turns each chunk into an embedding (a vector that places text with similar meaning close together), and fetches the nearest chunks at query time. Agentic search lets Claude do the searching: it calls tools such as grep, a metadata query or a search endpoint, reads what comes back, and decides what to look for next. Claude Code works this way: Anthropic's context engineering guidance describes it using glob and grep to retrieve files just in time.
| Option | When it wins | What it costs |
|---|---|---|
| Full context | Corpus under about 200,000 tokens; questions span the whole text | Tokens on every request, cut by caching; does not scale past the window |
| Pre-built pipeline | Large corpus, tight latency budget, many similar questions | Index to build and keep fresh; chunks lose their surroundings; stale versions linger |
| Agentic search | Multi-step questions, exact identifiers, fast-changing sources, a need to show the search path | Several model turns per question: slower and dearer per answer |
Anthropic's Agent SDK guidance sums up the trade: semantic search is usually faster but less accurate, harder to maintain and less transparent, so start with agentic search and add semantic search when you need speed. That advice assumes a corpus an agent can explore in a few calls. Halden's corpus is tens of millions of tokens, and a clinician at a bedside will not wait for ten search turns, so the main path is a pipeline. The two combine: Halden exposes the pipeline as a search_policies tool, so Claude can issue a second, narrower query when the first results do not answer the question. Anthropic's context engineering guidance calls this a hybrid strategy: retrieve some data up front for speed, then explore further at the agent's discretion.
Chunking, embeddings and contextual retrieval
Here is the failure that trips up most pipelines. Halden's renal dosing policy runs to twelve pages, and its dosing table sits three pages below the heading that explains it. The fixed-size chunker cut out a chunk that reads, in full, "Reduce to once daily when clearance is below the threshold in section 2." That chunk names no drug, no policy and no version. It cannot match a question about the anticoagulant, and if it does match, nothing says it belongs to version 3.
Chunking decides the unit of retrieval. Chunks are usually no more than a few hundred tokens, and three choices matter. Size: small chunks match precisely but lose context, large ones dilute the embedding. Boundaries: split on headings, list items and table rows, never through a table. Overlap: repeat a little text across a boundary so no sentence is orphaned. In structured clinical documents, boundaries usually matter more than size.
The embedding model decides what "similar" means. Anthropic does not offer its own. Its docs use Voyage AI as the worked example, advise assessing several vendors, and list the criteria: how well the model's training data matches your domain, inference speed at production scale, and whether it can be customised for unusual vocabulary. The docs also say to set the query or document mode on every retrieval call (Voyage's input_type). One rule comes from general practice rather than the docs: embed queries and documents with the same model, and treat a model change as a full re-index, because vectors from two models cannot be compared.
Contextual retrieval is Anthropic's fix for the orphaned chunk. Before indexing, a model reads the whole document and writes a short context that situates each chunk in it, usually 50 to 100 tokens in Anthropic's write-up. Your code prepends that text to the chunk before embedding it and before building the keyword index. In the function below, look at the cache_control line, which caches the full document once so contextualising its 40 chunks does not pay for it 40 times, and at the return line, which prepends the context.
import anthropic
client = anthropic.Anthropic()
def contextualize(doc_text: str, chunk: str) -> str:
response = client.messages.create(
model=CONTEXT_MODEL, # a small, fast model is enough for this job
max_tokens=150,
messages=[{"role": "user", "content": [
{"type": "text", "text": f"<document>\n{doc_text}\n</document>",
"cache_control": {"type": "ephemeral"}}, # CACHE the document across its chunks
{"type": "text", "text": f"<chunk>\n{chunk}\n</chunk>\n"
"Write one short paragraph that situates this chunk in the document: "
"policy name, version, effective date and section. Answer with that paragraph only."},
]}],
)
return response.content[0].text + "\n\n" + chunk # PREPEND, then embed and index this text
In Anthropic's tests, contextual embeddings cut the failure rate (the share of relevant documents not retrieved in the top 20 chunks) from 5.7% to 3.7%, a 35% reduction. At Halden the orphaned chunk now begins "Anticoagulant renal dosing policy, version 3, superseded March 2026, section 4 dosing table", and that sentence is what lets the rest of the pipeline tell the versions apart.
Hybrid search and reranking
Now the opposite question: if embeddings capture meaning, why do they miss things? Because meaning is not identity. To an embedding model, "version 3" and "version 4" of the same policy are nearly the same text, and a formulary code such as "AC-412" is a handful of characters with little meaning to place. Embeddings are excellent at matching "kidney function" to "renal impairment" and poor at matching an exact identifier.
BM25 is the classic lexical ranking function: it scores a chunk by how many of the query's exact terms it contains, giving more weight to rare terms and normalising for chunk length. It finds "AC-412" instantly and has no idea that "kidney" and "renal" are related. Hybrid search runs both, embeddings and BM25, and merges the two ranked lists into one candidate set (rank fusion is the usual method). In Anthropic's tests, adding contextual BM25 to contextual embeddings took the failure rate from 5.7% to 2.9%, a 49% reduction.
The candidate set is wide on purpose, because recall is cheap at this stage and lost passages cannot be recovered later. A reranker then narrows it. A reranker is a model that reads the query and each candidate together and scores how well that candidate answers that query, which is far more accurate than comparing two independently computed vectors. Anthropic's tests retrieved 150 candidates, reranked them and passed the top 20 to Claude; with reranking added, the failure rate fell to 1.9%, a 67% reduction. Think of a hospital switchboard: the operator quickly forwards every call that might be for cardiology, and the cardiology coordinator, who actually reads each case, decides who sees the consultant.
Halden's retrieval path after the redesign
status: currentReranking has a price: it adds a small amount of latency (the reranker scores candidates in parallel) and a per-query cost, and reranking more candidates raises both. Notice the box marked FILTER. Neither embeddings, BM25 nor the reranker knows which policy version is in force; that is a fact about your data, not about language. Halden adds a status and an effective_date field to every chunk at ingestion and filters superseded versions out before reranking. Clinicians who ask for history get a separate path that includes them, labelled as superseded.
Grounding the answer: citations, not found, and confidence
The right passages have reached Claude. Can the clinician see what the answer rests on, and does the system say so when the evidence is thin? Halden's old prompt asked Claude to "mention the source", which produced paraphrased and sometimes invented titles. The citations feature replaces that instruction with an API mechanism. You send each retrieved passage as a search_result block (or a whole file as a document block) with citations enabled, and the response's text blocks come back with a citations list.
For search results each citation has the type search_result_location and carries the source and title you supplied, the exact cited_text, the search_result_index and the cited block range. The API extracts them itself, so citations always point at content you provided, and cited_text does not count toward output tokens. Two constraints: all search results in a request share one citations setting, and citations cannot be combined with structured outputs. In the block below, look at source and title: they are the only identity a citation carries, so Halden puts the version and status there.
{
"type": "search_result",
"source": "kb://policy/anticoag-renal-dosing/v4",
"title": "Anticoagulant renal dosing policy v4 (current, effective 2026-03-02)",
"content": [
{"type": "text", "text": "Context: version 4, section 4 dosing table for reduced kidney function."},
{"type": "text", "text": "Reduce to once daily when clearance is below the threshold in section 2."}
],
"citations": {"enabled": true}
}
Citations show WHERE a claim came from. Two more practices cover missing or mixed evidence. A "not found" answer is a designed outcome: the system prompt explicitly permits Claude to say the retrieved policies do not answer the question, in a fixed phrase your code detects and routes to a pharmacist. Anthropic lists permission to admit uncertainty as a basic technique against hallucination. Uncertainty declaration covers the middle ground: when retrieved passages conflict, or apply only to some patients, the answer says so instead of picking one.
A confidence signal is the hardest of the three to get right. It is tempting to ask Claude to rate its own confidence from 1 to 10. Resist it: a self-rating is more generated text, fluent and unmeasured. A useful signal is computed by your code from evidence it can check.
Where a confidence signal should come from
Halden shows a green, amber or grey badge: green when the top reranker score clears a threshold set on audited answers, every sentence with a dosing figure carries a citation, and every cited source is current. Grey means "not found" and a pharmacist link. The badge is enforced by code; Claude only supplies the citations it is measured on.
Diagnosing a retrieval failure stage by stage
When a grounded answer is wrong, the instinct is to blame the last thing that touched it, the model. At Halden, 23 bad answers all cited what they were given, so the generation step was doing its job. The useful question is: at which stage did the right passage first go missing?
A retrieval system has six stages, and each can lose the right passage in its own way. Diagnosis by stage takes a set of failing questions with known correct sources and checks, stage by stage, whether the right passage is still present. The first stage where it disappears is where the fix belongs.
Six stages, one question at each
| Stage | Per-stage check | What Halden found in the 23 failures |
|---|---|---|
| Ingestion | Is the right document indexed, current, once, with status metadata? | Version 4 not yet re-ingested for 2; versions 3 and 4 both live, with no status field, for the rest |
| Chunking | Does the chunk holding the answer name its document, section and version? | Dosing tables split from their headings; no version in the chunk text |
| Embedding | Same model and correct query and document modes for both? Similarity of right chunk vs wrong? | Version 3 and 4 chunks almost identical as vectors |
| Retrieval | Recall at 150: is the right chunk in the candidate set? | Both versions present in 21 of 23 |
| Reranking | Recall at 20: is it still there after reranking? | Version 3 outranked version 4 in 15; both passed in 6 |
| Generation | Given the right passage, did the answer use and cite it? | Faithful in all 23: Claude cited what it was handed |
Read top down, the root cause is ingestion. A pipeline that indexes superseded documents without a status field forces every later stage to choose between two near-identical passages with no way to know which is current. The 6 cases where both versions reached Claude show the limit of prompting: an instruction to "prefer the newest version" has nothing to go on when neither passage says which is newer. Halden's fix sits where the loss began: a status field and filter, a re-ingestion job triggered by every policy revision, and contextual retrieval so each chunk names its version. Measuring recall at each cut-off keeps the fix honest.
The exam traps
Each trap fixes the wrong stage or trusts a signal that measures nothing.
- ✗ Switching to a larger model because answers cite the wrong source. ✓ Check what the model was given first. If the wrong passage reached the context, the model faithfully used it, and the fix is upstream in retrieval.
- ✗ Adding "always use the most recent version" to the system prompt. ✓ Put status and effective date in metadata at ingestion and filter on them. The model cannot know which version is current unless the data says so.
- ✗ Raising the number of chunks sent to Claude to 100 "so the right one is in there". ✓ Retrieve wide, then rerank to a small set. Flooding the context adds cost and latency and gives near-duplicates more chances to win.
- ✗ Relying on embeddings alone for queries full of codes and identifiers. ✓ Add BM25 for hybrid search. Embeddings match meaning; exact terms need lexical matching.
- ✗ Asking Claude to cite sources in prose, or to rate its own confidence. ✓ Use the citations feature for verifiable pointers and compute confidence from retrieval scores, citation coverage and source status.
- ✗ Building a vector pipeline for a 300-page handbook, or ten-turn agentic search for a bedside lookup. ✓ Match the architecture to corpus size and latency budget: full context under about 200,000 tokens, a pipeline for large corpora with tight latency.
Put it together: trace one wrong answer back to its stage
You now have every piece: the architecture choice, the indexing decisions, hybrid search and reranking, grounded answers, and a method for finding the stage that failed. The fastest way to make them stick is to build a tiny version of Halden's problem, break it the same way, and find the break with per-stage checks.
Retrieval does not stop at this lesson. Telemetry (3.1) records which chunks each answer retrieved and cited, so a bad answer can be traced without re-running it. Failure diagnosis (4.1) separates "the right passage never arrived" from "it arrived and was ignored" across agents and turns. Evaluation design (5.1) turns the per-stage recall and groundedness checks into a suite that gates every index and prompt change.
Key takeaways
- ✓ Choose the architecture by corpus size, latency budget and query shape: full context under about 200,000 tokens, a pre-built pipeline for large corpora, agentic search when accuracy and freshness justify extra turns.
- ✓ Chunk on document structure, embed queries and documents with the same model, and treat any change of either as a full re-index.
- ✓ Contextual retrieval prepends a short model-written description to each chunk before embedding and BM25 indexing, so chunks carry their document, section and version.
- ✓ Hybrid search pairs embeddings for meaning with BM25 for exact terms, a reranker narrows a wide candidate set, and metadata filters enforce facts like which version is current.
- ✓ Ground answers with the citations feature, design "not found" and conflicting-evidence answers, and compute confidence signals from evidence instead of the model's self-rating.
- ✓ Diagnose a wrong grounded answer by following the right passage through all six stages and fixing the first stage where it goes missing.
Practise this
Practice questions for CCDV-P are being written and are not in this course yet. Read this lesson on the web to answer its check questions, with every option explained: https://claude.termidy.com/learn/ccdv-p/production-integration-reliability/retrieval-grounding-at-scale/.