Opens in a new tab
Home / Blog / Artificial Intelligence

What Is Retrieval Augmented Generation (RAG)? An Engineering Guide

Retrieval-augmented generation grounds a language model in your own data at query time. Here's how RAG actually works today — hybrid retrieval, rerankers, agentic loops — and how to tell whether you actually need it.

SoftmaxAI EngineeringPublished July 28, 2026Updated August 5, 202612 min read
Topic
Retrieval-Augmented Generation (RAG)
Best for
Grounding LLMs in private, changing knowledge
Core pattern
Retrieve → rerank → generate with citations
Recent shift
Static pipelines → agentic, multi-step retrieval

What is retrieval-augmented generation?

Retrieval-augmented generation (RAG) is a technique that connects a large language model to an external knowledge source, so that it can look up relevant information at query time and produce an answer grounded in that retrieved evidence. Rather than relying only on what the model learned during training, a RAG system searches your documents, databases, tickets or wikis for passages relevant to the user's question, feeds those passages into the model's context window, and asks it to answer using them — with citations back to the source.

The practical difference is straightforward. Ask a plain language model about your company's refund policy and it will produce a generic, plausible-sounding answer, because it has never seen your policy. Ask the same model with RAG and it retrieves the actual policy document, quotes the relevant clause and links to it. One answer sounds right. The other is right, and can be checked.

That auditability is why RAG became the default architecture for enterprise AI. It's also why it's still the workhorse pattern today, long after very large context windows were supposed to have made it obsolete.

RAG is an architecture, not a product. Two systems both called "RAG" can differ by an order of magnitude in answer quality, depending on how documents are parsed, chunked, indexed, retrieved, reranked and evaluated. The model is rarely the bottleneck.

Why RAG still matters

As context windows grew to hundreds of thousands and then millions of tokens, an obvious question followed: why retrieve anything at all when you could just paste in the entire corpus? Three years of production experience have provided very clear answers.

  • Corpora are bigger than any context window. An enterprise knowledge base is measured in gigabytes, not megabytes. A million-token window holds perhaps a few thousand pages — a rounding error against a decade's worth of contracts, tickets and documentation.
  • Cost and latency scale with what you send. Stuffing a hundred thousand tokens into every request to answer a question that needed two paragraphs is both expensive and slow. Retrieval keeps the prompt small and the response fast, which is critical for chat and voice interfaces.
  • Attention still degrades over long contexts. Models are still measurably better at using information placed in a short, focused context than the same information buried in the middle of a very large one. Precise retrieval beats brute force.
  • Knowledge changes faster than models. Prices, policies, inventory and case notes all change hourly. A retrieval index updates in seconds. Retraining doesn't.
  • Governance requires provenance. Regulated teams need to know which document produced which sentence, and to ensure that a user only sees what they're permitted to see. Retrieval is the natural place to apply access control; a context dump is not.

The honest summary is that long context changed RAG rather than replacing it. Chunks got bigger, retrieval became more forgiving, and the brittle 200-token fragments of early systems are gone. But the retrieve-then-generate loop is still how grounded systems are built.

How RAG works: the pipeline end to end

A production RAG system has two halves: an ingestion path that runs whenever documents change, and a query path that runs on every question. Most teams build the second and neglect the first, which is exactly the wrong way round — ingestion quality sets the ceiling on everything that comes after.

The ingestion path

  • Parse. Convert PDFs, decks, spreadsheets, HTML and scanned documents into clean, structured text. Layout-aware parsing matters here: a table flattened into a wall of numbers is useless, and a two-column PDF read straight across is complete nonsense.
  • Chunk. Split documents along their natural structure — sections, clauses, headings — rather than at an arbitrary character count. Carry the document title and section path into every chunk, so that a retrieved fragment still tells you what it belongs to.
  • Enrich. Attach metadata: source, author, effective date, product line, access level and jurisdiction. That's what later enables filtered retrieval and permission enforcement.
  • Embed and index. Compute vector embeddings for semantic search and, in parallel, build a keyword index. Store both alongside the metadata.

The query path

  1. Understand the question. Rewrite it for retrieval, resolve pronouns against the conversation history, and break it down into several targeted sub-queries when it's compound.
  2. Retrieve. Run semantic (vector) and keyword (BM25) search together, filtered by metadata and by the user's permissions, and merge the candidate sets.
  3. Rerank. Pass the merged candidates through a cross-encoder reranker that scores each passage against the question directly. This is consistently one of the highest-leverage components in the pipeline.
  4. Assemble the context. Select the best passages within the token budget, remove near-duplicates, and order them so the strongest evidence sits where the model attends best.
  5. Generate. Ask the model to answer strictly from the passages provided, cite each claim, and say plainly when the evidence is insufficient.
  6. Verify and cite. Check that every citation resolves and that every assertion can be traced back to retrieved text. Ungrounded answers are regenerated or escalated rather than sent to the user.

The order matters more than the components. Teams often swap in a more powerful generation model to fix bad answers, when the real defect is three steps earlier — a PDF parser that destroyed the table the answer was in.

Hybrid retrieval and reranking: where the accuracy is

Teams stuck at "the answers are mostly good but sometimes confidently wrong" almost always have a retrieval problem, not a generation problem. If the right passage never reaches the context window, no model can recover.

Pure vector search fails in a specific and predictable way: it's excellent at meaning and poor at exact tokens. Part numbers, error codes, contract clause references, drug names and internal acronyms are precisely the terms users search for, and precisely where embeddings blur distinctions. Keyword search handles those perfectly and fails at paraphrase. Running both and merging the results covers each method's blind spots.

Reranking then does the heavy lifting. Retrieval optimises for recall — cast a wide net, perhaps 50 candidates. A cross-encoder reranker then reads each candidate together with the query and scores its true relevance, promoting the handful that actually answer the question. Adding a reranker to a plain vector pipeline is routinely the single biggest quality gain available, and it costs only a few tens of milliseconds.

Agentic RAG: retrieval becomes multi-step

The most significant change since the first wave of RAG systems is that retrieval is no longer a single step. Classic RAG runs one query, takes the top results and generates a response — whether or not those results actually answer the question. Agentic RAG puts a reasoning loop around retrieval.

  • It plans before it searches. A question such as "how did our EMEA renewal terms change after last year's policy update?" is broken down into separate retrievals for the old terms, the new policy and the effective dates, rather than one hopeful query.
  • It routes across sources. Structured questions go to SQL over the warehouse, document questions go to the vector index, and live questions go to an API. A single semantic index is the wrong tool for "how many open tickets does this account have?"
  • It critiques its own evidence. Before generating, the system asks whether the retrieved passages genuinely support an answer. If they don't, it reformulates and searches again rather than making an answer up.
  • It knows when to stop. A bounded number of retrieval rounds, then an honest "I couldn't find this", along with the sources it did check. Escalation is a feature, not a failure.

This is where RAG and AI agent development converge. The retrieval layer becomes one tool among several that an agent calls deliberately, and the interesting engineering moves into orchestration, tool selection and stopping conditions. The cost is latency and complexity, so the right pattern is tiered: answer easy questions with a single fast retrieval pass, and escalate to the agentic loop only when confidence is low.

GraphRAG and structured retrieval

Some questions aren't lookup questions at all. "Which of our suppliers are exposed to this component shortage?" requires traversing relationships, not matching passages. Knowledge-graph-backed retrieval — extracting entities and relationships at ingestion, then walking the graph at query time — handles multi-hop and aggregation questions that flat chunk retrieval simply can't. It's significantly more expensive to build, so it earns its place on connected corpora, not on an FAQ base.

RAG vs fine-tuning vs long context

These are complementary tools, and the common mistake is reaching for fine-tuning to fix a knowledge problem. Fine-tuning teaches a model how to behave; retrieval teaches it what is true right now.

RAGFine-tuningLong context
Best atGrounding answers in private, changing factsTeaching format, tone, and domain-specific behaviourReasoning over one large document or session
Update costSeconds — reindex the changed documentA retraining cycle per meaningful changeNone — but you resend everything each call
CitationsNative; every claim traces to a sourceNone; knowledge is baked into weightsPossible within the supplied text
Access controlEnforced at retrieval, per userImpossible — weights cannot be permissionedAll-or-nothing per request
Typical failureRight model, wrong passages retrievedConfident, fluent, out-of-date answersCost, latency, and attention dilution
Use it whenKnowledge is yours, large, and movesBehaviour must be consistent and specialisedThe whole relevant corpus is small
Choosing between the three approaches

In practice, most serious systems combine them: retrieval for the facts, light fine-tuning or careful prompting for voice and structure, and generous context windows so that retrieved passages arrive with enough surrounding detail to be useful.

How to evaluate a RAG system

"It seems to work" is not a launch criterion. RAG systems fail quietly — a subtly wrong answer looks exactly like a correct one — so evaluation has to be built alongside the pipeline, not bolted on after a complaint.

  • Retrieval recall. For a curated set of questions with known source passages, how often does the correct passage actually appear in the retrieved set? If recall is poor, nothing downstream can help.
  • Groundedness / faithfulness. Is every claim in the answer supported by the retrieved context? This is the primary hallucination metric, and the one to alert on.
  • Answer relevance. Does the response actually answer the question asked, rather than adjacent material that just happened to retrieve well?
  • Citation correctness. Do the cited sources genuinely contain the claims attributed to them? Plausible citations that don't support the statement are worse than no citations at all.
  • Refusal calibration. When the corpus doesn't contain the answer, does the system say so? Measure this deliberately, using unanswerable questions.

Build a golden set of a few hundred real questions with verified answers, run it on every change to parsing, chunking, prompts or models, and treat a regression as a build failure. That's ordinary software engineering discipline applied to a probabilistic component, and it's the difference between a demo and a system.

Where RAG delivers business value

The pattern pays off wherever expertise is locked up in documents and people spend their days searching for it.

  • Customer support. Deflect repetitive questions with cited answers drawn from real documentation, and give human agents an assistant that surfaces the right article mid-conversation. That's the fastest route to measurable value in most chatbot deployments.
  • Internal knowledge assistants. New engineers, clinicians and analysts stop interrupting senior colleagues, because the answer — with its source — is just one question away.
  • Contract and policy analysis. Ask questions across thousands of agreements and get clause-level citations, rather than a summary you can't verify.
  • Sales and proposal support. Produce accurate, up-to-date answers on products, pricing tiers and previous work, without a specialist having to write every response by hand.
  • Voice agents. Grounded retrieval is what stops a voice agent from making up an answer live on a call, where the caller has no opportunity to check a citation.

You can see the pattern in production in our case studies — retrieval assistants, document intelligence and conversational systems, all built on the same spec-first approach.

Common failure modes — and the fixes

SymptomUsual root causeFix
Confident but wrong answersThe right passage was never retrievedAdd hybrid keyword search and a reranker; measure retrieval recall first
Answers miss exact identifiersPure vector search blurs codes and part numbersFuse BM25 keyword results into the candidate set
Retrieved fragments lack contextFixed-size chunking split mid-clauseChunk on document structure; prepend title and section path
Tables and figures ignoredNaive PDF text extraction destroyed layoutLayout-aware parsing; serialise tables to markdown at ingestion
Stale answers after an updateIndex refresh is manual or batched nightlyEvent-driven reindexing on document change
Users see documents they should notPermissions applied after retrieval, or not at allFilter by access metadata inside the query, per user
Quality drifts silentlyNo eval set, no regression gateGolden question set in CI; alert on groundedness

How SoftmaxAI builds RAG systems

We build our retrieval systems the same way we build everything else: a written, client-approved specification before any code, an agent-accelerated build led by senior engineers, and every decision that matters owned by a human.

  • Spec first. We map the corpus, the real questions users ask, the access boundaries, the refusal behaviour and the acceptance criteria before a single line of pipeline code is written. Most RAG projects fail here, quietly, by skipping this.
  • Evaluation from day one. The golden question set is written with your domain experts as part of the specification, not reverse-engineered from complaints after launch.
  • Retrieval before generation. We tune the parsing, chunking, hybrid search and reranking until retrieval recall is high, and only then choose a generation model. Doing it the other way round wastes budget.
  • Deployed to your cloud. Systems run in your own GCP or AWS account, with monitoring, production evals and a clear reindexing path. As a Google Cloud Partner we build natively on Vertex AI and Gemini where that makes sense.

If you're earlier than that — still deciding whether retrieval is the right answer at all — the AI Opportunity Sprint is a short, fixed-scope engagement that pressure-tests the idea and gives you an honest feasibility read and architecture before you commit to a build.

RAGVector searchHybrid retrievalRerankingAgentic RAGGraphRAGVertex AIGroundedness evalsLLM orchestration

FAQ

Questions we get asked.

What does RAG stand for?
RAG stands for retrieval-augmented generation. It's an architecture in which a language model retrieves relevant information from an external knowledge source at query time, and then generates its answer from that retrieved evidence rather than from its training data alone.
Is RAG obsolete now that models have million-token context windows?
No. Long context made RAG much more forgiving — chunks can be larger and retrieval needn't be perfect — but enterprise corpora are far larger than any context window, sending everything on every request is slow and expensive, and retrieval is still the natural place to enforce permissions and produce citations.
Does RAG eliminate hallucinations?
It reduces them substantially and, more importantly, makes them detectable, because every claim should be traceable to a retrieved passage. It doesn't eliminate them. A model can still misread a passage, and if the wrong passage is retrieved, the answer will be wrong. Groundedness evaluation and honest refusal behaviour are what close the remaining gap.
RAG or fine-tuning — which should I choose?
Use RAG when the problem is knowledge: private, large or rapidly changing facts that the model needs to cite. Use fine-tuning when the problem is behaviour: a consistent format, tone or specialised task that the model performs poorly out of the box. Many production systems use both, and choosing fine-tuning for a knowledge problem is the most common and most expensive mistake.
What is agentic RAG?
Agentic RAG wraps retrieval in a reasoning loop. Rather than running one query and generating, the system plans a retrieval strategy, issues several targeted queries across different sources, assesses whether the evidence actually answers the question, and retries or escalates when it doesn't. It adds latency, so it's best applied selectively to the harder questions.
How long does it take to build a production RAG system?
A focused, well-scoped retrieval assistant typically reaches production in weeks rather than quarters, when the specification is written first and the evaluation set exists up front. Timelines stretch when document parsing is messy, access control is complex, or the success criteria were never defined.
What does a RAG system cost to run?
Ongoing cost is driven by embedding and reindexing volume, vector storage, retrieval and reranking calls, and generation tokens. Precise retrieval is what keeps it low: a well-tuned pipeline sends a few thousand tokens per answer rather than a hundred thousand, which is usually the difference between viable unit economics and unaffordable ones.
Start here

Thinking about RAG? Let’s pressure-test it — free.

A 30-minute call with the engineers who build these systems, not a salesperson. Bring your corpus and your toughest question, and you'll get an honest feasibility assessment, a rough architecture and a clear next step.