Blog · Claude API

Building RAG Systems with the Claude API

How to architect production RAG on the Claude API: chunking and retrieval strategy, context assembly, prompt caching, citation grounding, and the evaluation loop that keeps quality honest.

Retrieval-augmented generation remains the workhorse pattern for grounding Claude in your organisation’s knowledge — policy documents, tickets, contracts, runbooks — without retraining anything. The model reasons; your retrieval layer supplies the facts. Done well, RAG gives you answers that cite sources, respect access controls, and stay current as documents change.

Done badly, it produces confident nonsense with extra infrastructure. This article lays out a reference architecture for RAG on the Messages API and works through the decisions that actually determine quality: how you chunk, how you retrieve, how you assemble context, how prompt caching changes the economics, and how you evaluate the whole pipeline before your users do.

Why RAG Still Matters in the Long-Context Era

Claude’s context windows are large enough that teams periodically ask whether they can skip retrieval and paste everything in. For small, stable corpora, sometimes yes — especially with prompt caching making repeated large contexts affordable. But RAG survives the long-context era for reasons that have little to do with window size:

  • Access control. Retrieval is where you enforce per-user document permissions; a shared mega-prompt cannot.
  • Freshness. An index updates in seconds; re-shipping a giant prompt across every request does not scale operationally.
  • Cost discipline. Sending only relevant passages keeps token spend proportional to the question, not the corpus.
  • Attribution. Retrieved chunks give you natural citation units for auditability.

The practical answer is a spectrum: cache stable reference material in the prompt, retrieve the volatile and permission-sensitive remainder.

Reference Architecture: Retrieval in Front of the Messages API

A production Claude RAG pipeline has five stages, each independently testable. Ingestion parses documents, normalises formats, and attaches metadata — source, owner, timestamps, ACLs. Indexing embeds chunks into a vector store, usually alongside a keyword index for hybrid search. Retrieval takes the user query (often rewritten by a fast model like Claude Haiku 4.5), pulls candidates, and reranks them. Assembly builds the Messages API request: system prompt, retrieved passages with identifiers, then the question. Generation calls Claude and post-processes citations.

Keep the boundary clean: everything before assembly is deterministic infrastructure you can unit-test; everything after is model behaviour you evaluate statistically. For document-heavy sources exposed through internal systems, an MCP server is a natural retrieval interface — the same connector then serves both your RAG pipeline and future agent use cases. Our Claude API & MCP training builds this architecture end to end.

Chunking and Retrieval Strategy

Chunking is where most RAG quality is won or lost, because Claude can only reason over what retrieval surfaces. Guidelines that survive contact with real corpora:

  • Chunk along semantic boundaries — sections, headings, clauses — not fixed character counts. A contract clause split mid-sentence retrieves badly and reads worse.
  • Keep chunks self-contained: prepend the document title and section path so a chunk makes sense out of context.
  • Use hybrid retrieval. Vector search catches paraphrases; keyword search catches exact identifiers, SKUs, and error codes that embeddings blur.
  • Rerank. Pull a wide candidate set (say, 30–50), then rerank down to the handful you actually send.
  • Store rich metadata and filter on it — date ranges, product lines, ACLs — before similarity ever runs.

Resist tuning chunk size by intuition. Change one variable, rerun your evaluation set, and let retrieval hit-rate metrics decide.

Assembling the Prompt: Context, Citations, and Grounding

How you present retrieved passages shapes how faithfully Claude uses them. Wrap each chunk in a delimited block with a stable identifier, and instruct the model to answer only from the provided material and to cite the identifiers it used.

system = """Answer using ONLY the documents provided.
Cite sources as [doc_id]. If the documents do not
contain the answer, say so explicitly."""

context = "\n".join(
    f"<doc id='{c.id}' title='{c.title}'>{c.text}</doc>"
    for c in reranked_chunks
)

Two grounding disciplines pay off immediately. First, give Claude explicit permission to say “not found” — models hallucinate most when silence feels forbidden. Second, verify citations mechanically after generation: check that every cited identifier exists in the supplied context, and flag or regenerate responses that cite phantom sources. Structured outputs work well here, returning the answer and its citation list as a typed JSON payload your application can validate.

Prompt Caching and Model Selection: The Economics of RAG

RAG requests have a characteristic shape — a long, stable prefix (system prompt, output instructions, sometimes shared reference documents) followed by a variable tail (retrieved chunks and the user question). Prompt caching exploits exactly this shape: mark the stable prefix as cacheable and repeated calls reuse it at substantially reduced cost and latency. Order matters, so put stable content first and volatile content last. For pipelines that reprocess a corpus offline — summarising, tagging, generating synthetic Q&A for evaluation — the batch API cuts costs further on non-interactive volume.

Match models to stages rather than using one everywhere: Claude Haiku 4.5 for query rewriting and relevance filtering, Claude Sonnet 5 as the default answer generator, and Claude Opus 4.8 or Claude Fable 5 where answers require synthesis across many conflicting sources. Consult Anthropic’s documentation for current capabilities rather than hard-coding assumptions.

Evaluation and Production Hardening

A RAG system without an evaluation harness is a liability with a UI. Before launch, build a golden set of 50–200 real questions with reference answers and known source documents, then measure two things separately: retrieval quality (did the right chunks surface?) and answer quality (faithfulness to sources, completeness, citation accuracy). Model-graded evaluation — using a strong Claude model as judge with a tight rubric — scales this affordably, spot-checked by humans.

Operationally, treat the pipeline like any production service: version your prompts and index schema together, log query, retrieved chunk IDs, and response for every request (with PII controls), monitor retrieval hit rates and “not found” rates as leading indicators, and re-run the golden set on every prompt or model change. Teams rolling RAG out organisation-wide often pair this build work with our corporate Claude AI training so stakeholders can interrogate quality claims, not just accept them.

Key takeaways

FAQ

Questions

Sometimes not — small, stable, non-sensitive corpora can be sent directly, especially with prompt caching. But retrieval remains necessary when documents change frequently, when per-user access control matters, or when the corpus is large enough that sending everything on every request is economically or operationally unreasonable. Most enterprise systems end up combining both.

Send the smallest set that reliably contains the answer — commonly five to fifteen reranked chunks rather than dozens of raw candidates. More context is not free: irrelevant passages add cost, latency, and distraction. Retrieve wide, rerank aggressively, and let your golden-set evaluation determine the number empirically for your corpus.

You reduce it with layered controls: instruct Claude to answer only from supplied documents and to state when the answer is absent, require citations to chunk identifiers, verify those citations programmatically, and monitor faithfulness with model-graded evaluation. Hallucination in RAG is usually a retrieval failure first, so measure retrieval quality separately.

Cait Hitesh Scaled

Your trainer

Meet Hitesh Motwani

Hitesh Motwani is a globally recognised corporate AI trainer and generative-AI expert. He has trained 2,00,000+ professionals across 16+ countries on Claude, ChatGPT and generative AI, and advised leadership teams at Tata, Flipkart, Hitachi, Siemens, Adani and Marks & Spencer. Connect on LinkedIn →

Trusted by

Teams we’ve trained

TataJSW PaintsMitsui & Co.BirlasoftXebiaPiramal FinanceHPEAction Construction EquipmentIndoramaPharmedM Square MediaFlipkartHitachiAdaniSonyMahindra

…and 200+ organisations, across 16+ countries.

What participants say

Real feedback from real sessions

Verified feedback collected from participants across corporate sessions — average rating 4.8/5.

★★★★★

“A very productive session for working professionals. A must-do.”

Sabyasachi DasGeneral Manager, Tata Teleservices
★★★★★

“The session was highly insightful and conducted in a very professional and interactive manner. Learnt about AI and excited to learn more!”

Rohan MankameDGM – Financial Planning, JSW Paints
★★★★★

“Highly recommended! Hands-on and directly useful — from making PPTs and strategic plans to building KRAs.”

Suneetha QureshiPresident, M Square Media
★★★★★

“Great work done by Mr Hitesh in the AI landscape — a true subject-matter expert. More power to him for spreading this knowledge.”

Vikram Sagar SaxenaAsst. Vice President, Pharmed Ltd
★★★★★

“I would recommend everyone to go through this session — it clarifies both what to expect from AI and where AI isn’t needed.”

Rahul AroraDeputy General Manager, Tata Tele Business Services
★★★★★

“Amazing session by Hitesh. The AI tools he shared are very helpful for day-to-day work.”

Varsha TaklikarDy. Manager, Mitsui & Co. India
★★★★★

“Mr Hitesh Motwani is a very informative trainer. The way he delivers training is awesome.”

Prem ChandDy. Manager – HR, Action Construction Equipment
★★★★★

“Mr Hitesh Motwani delivered a valuable, informative session and showed us exactly how to use AI tools to enhance our work. Thank you so much.”

Alisha KhanProgram Coordinator, Q Academy
★★★★★

“A nice interactive session with a lot of new insights and the power of AI. This will help me save time in routine activities.”

Ramnath BandiSenior Manager – Engineering, JSW Paints
★★★★★

“A very good training session. AI can do wonders — we’ll implement it to create efficiency and save time.”

Ruchit PanchalDeputy Manager, Mitsui & Co.
★★★★★

“Hitesh was very informative and knowledgeable about AI tools. It will let me use my time far more effectively.”

Dagmar NoronhaOperations Manager, Q Academy (Toronto)
★★★★★

“Your session helped me walk into the world of magic.”

Partha ChowdhuryDHM, JSW Paints

Work with us

Bring Claude AI training to your team

Tell us your team, tools and goals and we will send a fixed proposal — usually within one business day.