Imagine asking a university chatbot, “What is the deadline for the current semester’s project proposal?” A language model may not have the latest department policy in its training data. Even when it knows general university procedures, it should not guess the deadline. Retrieval-Augmented Generation (RAG) lets an application search authorized documents and supply relevant passages to a model before it answers.
RAG is an AI application architecture that combines information retrieval with generation. Instead of requiring every changing fact to be stored in the model’s parameters, the application retrieves evidence at request time and includes it in the model’s context.
1. Understand the problem RAG solves
A pretrained model learns patterns from its training data, but its parameters are not a continuously updated database. Its answer may be outdated, unsupported, or incomplete. Prompting alone cannot give it access to a document it has never received.
RAG separates two jobs:
- Retriever: Find documents or passages relevant to the question.
- Generator: Use those passages and the user’s question to produce a response.
The generator still can misinterpret retrieved material. Retrieval is an opportunity for grounding, not a guarantee of correctness.
2. A full RAG workflow
Document preparation and indexing
- Collect sources: Use authorized documents, webpages, or database records.
- Extract and clean: Remove irrelevant navigation, duplicated boilerplate, and corrupted text.
- Chunk: Divide large documents into passages while retaining section and source information.
- Represent: Generate embeddings, keyword indexes, or both.
- Store: Index content together with metadata, permissions, titles, and document identifiers.
Answering a question
- Receive the user’s question and determine whether retrieval is appropriate.
- Search the authorized index for candidate passages.
- Filter by permissions and optionally rerank the matches.
- Choose relevant passages that fit within the model’s usable context budget.
- Send the question plus supporting context to the generator.
- Produce an answer that distinguishes supported facts from uncertainty.
- Attach source references and, when possible, verify them.
3. Walk through a university-policy example
Suppose a retrieved page states:
“Project proposals must be submitted by 15 November 2026 at 17:00 PKT.”
This is illustrative policy text, not a real university announcement. The assistant can answer the student’s question and link to that specific source, assuming it is current and authorized.
If the search returns no relevant policy, a responsible answer is “I could not find the deadline in the available documents”, not a guessed date.
If two retrieved pages disagree, the application should compare publication or update dates and source authority rather than combining contradictory facts.
4. A minimal application skeleton
The following Python shows the control flow, not a runnable integration with a particular model provider. Its three functions would need implementations for your chosen retrieval and generation services.
from typing import Sequence
def retrieve(question: str) -> Sequence[dict]:
"""Return authorized passages with source identifiers."""
raise NotImplementedError
def generate(question: str, context: str) -> str:
"""Call a language model through a validated API client."""
raise NotImplementedError
def answer_with_sources(question: str) -> dict:
passages = retrieve(question)
if not passages:
return {"answer": "No relevant source found.", "sources": []}
selected = passages[:5] # Real systems should rank and budget context.
context = "\n\n".join(
f"SOURCE {p['id']}:\n{p['text']}" for p in selected
)
response = generate(question, context)
return {
"answer": response,
"sources": [p["id"] for p in selected],
}
This example makes the boundaries visible. It does not verify that every statement in response is supported by the listed passages. That additional check belongs in a production design.
5. What makes retrieval good?
Chunking: A chunk must retain enough context to make sense. Splitting in the middle of a definition may make the passage misleading.
Retrieval: Keyword search can match exact terms while embeddings can find paraphrases. Hybrid retrieval often serves both needs.
Reranking: A reranker examines promising candidates more carefully and puts the best evidence first.
Metadata and permissions: Include source dates, course identifiers, access levels, and language where relevant. Authorization is not optional.
Context construction: Select enough evidence to answer, without flooding the model with unrelated passages or exceeding context limits.
6. Evaluate the complete system
RAG quality has two separate dimensions: did we retrieve appropriate evidence, and did the generator use that evidence correctly?
| Metric or check | Question it answers |
|---|---|
| Recall@k | Was the relevant passage in the top retrieved results? |
| Precision@k | How many top results were relevant? |
| Groundedness | Does the generated answer follow the retrieved evidence? |
| Citation correctness | Do references support the specific claims beside them? |
| Answer completeness | Are necessary facts present? |
| Abstention behavior | Does the system admit missing or conflicting evidence? |
| Permission safety | Did retrieval expose only authorized content? |
| Latency and cost | Is the end-to-end experience viable? |
Test the system on representative questions rather than judging it from one successful demo.
7. Limitations and security risks
- Poor retrieval: The correct document may never reach the model.
- Stale sources: Indexed information may be outdated after the original changes.
- Prompt injection: A retrieved page may contain malicious instructions. Treat passages as untrusted data.
- Misleading citations: A model may cite a source that does not support the claim.
- Context conflicts: Documents can contradict each other; source policy is needed.
- Privacy: Embeddings and indexes must obey document-level access controls.
- Long-document reasoning: Relevant facts can be scattered across multiple sources.
A RAG system should track which source version produced each answer so developers can investigate failures.
8. When to use RAG instead of fine-tuning
Choose RAG when the application needs access to specific, regularly updated, or private knowledge that can be retrieved at answer time. Choose fine-tuning when the goal is to change learned response patterns or a specialized capability, subject to evaluation and cost. Prompting can guide both. These approaches are complementary rather than mutually exclusive.
Related concepts
- Embeddings and Vector Search
- Information Retrieval and Search
- RAG: Chunking, Indexing, and Reranking
- Prompting vs. RAG vs. Fine-Tuning
- Evaluating RAG and AI Agents
References
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.