What Is RAG, Do Agents Replace It, and How to Build One in 45 Lines
•
7 min read

What Is RAG, Do Agents Replace It, and How to Build One in 45 Lines

Why RAG exists, when 1M-token agents skip a vector pipeline, and a 45-line Python RAG script with real output.

Retrieval-Augmented Generation (RAG) is an architecture that retrieves relevant passages from an external knowledge base and injects them into a language model prompt before generating an answer. It exists because pretrained models have frozen knowledge cutoffs and no access to private company data.

A corpus under 200,000 tokens (about 500 pages) fits in a model's context window, the amount of text it reads in one prompt. Putting the files straight in the prompt works at that size and is the simplest start, but check the answers on your own questions, because long inputs lost accuracy in the studies below. Past that size, or with per-user permissions, build retrieval.

Why Does RAG Exist?

Large language models store knowledge inside their weights during training. Once training finishes, those weights stay fixed, and retraining a frontier model every week to learn new facts is too expensive. Public training runs also exclude private internal documents.

Take a 400-person logistics company where HR and IT update remote equipment stipends, VPN hostnames, travel approval caps, and incident escalation rules every quarter. If an engineer asks a general-purpose model "How much is our remote equipment allowance and how do I claim it?", the model lacks that policy. Without external context, it either refuses or invents a plausible policy, a failure mode we examine in our AI hallucination guide.

In 2020, Lewis et al. formalized RAG in Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks by pairing a model's parametric memory (weights) with non-parametric memory (a searchable document index). At query time, the system looks up relevant paragraphs and adds them next to the user's question. On Natural Questions, a benchmark of real Google search questions answered from Wikipedia, their RAG-Sequence model (the variant that uses the same retrieved passage for every word of the answer) reached 44.5 Exact Match (EM, the share of answers that match the reference answer exactly). A T5-large model (770 million parameters) answering closed-book, from its weights alone, reached 28.9 EM.

Closed-book model with frozen weights scoring 28.9 EM versus RAG with an external document index scoring 44.5 EM

What Role Does RAG Play in Modern AI Systems?

Early AI apps treated RAG as the entire architecture: split a PDF into chunks (short passages), turn each chunk into an embedding (a list of numbers that captures its meaning), store the embeddings, fetch the top three matches for a question, and generate an answer. In modern agent systems, RAG is one retrieval layer sitting alongside tool calls, web search, and Model Context Protocol (MCP) connectors.

Two things changed since then:

  • Better chunking and hybrid search: Pure vector similarity often misses exact product codes or policy names, so hybrid search adds keyword matching next to the vectors. In Anthropic's Contextual Retrieval study, top-20-chunk retrieval failed 5.7% of the time on average with standard embeddings. Prepending a short explanatory context to each chunk and adding keyword matching cut failures to 2.9% (a 49% reduction). Adding a reranking step, where a second model reorders the retrieved chunks by relevance, cut them to 1.9% (a 67% reduction).
  • Agentic retrieval loops: Building Effective Agents describes models that generate their own search queries and choose their own tools. In practice an agent can run a query, read the snippets, reword the query when a term is ambiguous, or call an API for live records. Pairing retrieval with a strict domain glossary keeps agents from drifting on internal acronyms.

Average top-20 failed retrievals dropping from 5.7% in standard embedding search to 2.9% with contextual hybrid search and 1.9% with reranking
Source: Introducing Contextual Retrieval (Anthropic)

Do You Still Need RAG When Agents Have 1M Context Windows?

Modern coding and research agents can browse the web, search local folders with grep (a text-search command), and pass up to 1 million tokens into a single prompt. When your team keeps clean markdown docs in a repository, a dedicated RAG pipeline adds machinery.

Anthropic's Contextual Retrieval post (September 2024) says a knowledge base under 200,000 tokens (about 500 pages) can go straight into the prompt, with prompt caching (reusing a cached prompt prefix to cut cost and latency) keeping repeat questions cheap. Nothing gets chunked, so no chunking bug can appear. Local search with grep and file reads also works when an agent can scan the folder in two or three turns.

You still need a dedicated retrieval pipeline in three production cases:

  1. Scale beyond the window: Thousands of PDFs, support tickets, or wikis cannot fit into 1M tokens, and scanning them with shell tools on every question is too slow.
  2. Cost, and a quality risk: Sending 500,000 tokens on each user turn burns money and adds latency, a trade-off we examine in our context compression guide. Long prompts also carry a quality risk. Chroma's Context Rot report (July 2025; Chroma sells a vector database) tested 18 models, including GPT-4.1, Claude 4 and Gemini 2.5, and found that performance grows less reliable as input grows, even on simple tasks. On a chat-history question set called LongMemEval, GPT-4.1 scored 0.87 when the prompt held only the relevant parts and 0.62 when it held the full 113,000-token history (the focused prompt was picked by hand, so it is a best case for any retriever). A separate arXiv study of 5 models measured accuracy drops of 13.9% to 85% as inputs got longer, even when the models could retrieve all the relevant information. Lost in the Middle found the same pattern in 2023: GPT-3.5-Turbo scored lower when the answer sat in the middle of 20 documents than with no documents at all. These studies date from 2023 and 2025, so whether the newest 1M-window models behave the same is something to test on your own documents.
  3. Permission boundaries: An HR manager and a contractor cannot query the same raw prompt dump. A retrieval layer filters chunks by user access-control lists before passing text to the language model.

Bar chart of LongMemEval scores for seven GPT models: each scores lower on the full 113k-token input than on the focused input, for example GPT-4.1 at 0.62 versus 0.87
Source: Context Rot (Chroma), LongMemEval Overall Performance - GPT

My default is the least flexible option that works: put the files in the prompt, check the answers on your own questions, and build retrieval when size, cost or permissions force it. That is a personal preference; no measurement backs it.

How to Build a Simple RAG Script in 45 Lines

You can build a working RAG script using only Python's standard library, with no external frameworks. The script below talks to LM Studio (a desktop app that runs local models and serves them at http://localhost:1234/v1, an endpoint that accepts the same requests as OpenAI's API), converts each document into an embedding, finds the closest matches using cosine similarity (the angle between two vectors), and passes only the top matches (top_k=2) to the model.

It uses two models: text-embedding-nomic-embed-text-v1.5 turns text into embeddings, and meta-llama-3.1-8b-instruct writes the answer. Installing LM Studio and starting its API server are covered in our LM Studio guide.

Save the following 45 lines as simple_rag.py:

import json, math, urllib.request
 
BASE = "http://localhost:1234/v1"
DOCS = [
    "Remote equipment allowance: Full-time engineers receive $600 every 24 months for monitors, chairs, or keyboards. Submit receipts in Expensify within 30 days.",
    "VPN and staging access: Staging databases are only reachable through the WireGuard VPN (wg-staging.internal). Direct SSH from public Wi-Fi is blocked.",
    "Incident escalation SLA: Severity-1 outages require paging the on-call lead within 10 minutes via PagerDuty and posting an update in #inc-war-room.",
    "Annual travel policy: Conference travel up to $1,800 per year is approved by engineering managers without VP sign-off.",
]
 
def post(path, payload):
    req = urllib.request.Request(
        f"{BASE}{path}",
        data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=30) as res:
        return json.loads(res.read())
 
def embed(text):
    return post("/embeddings", {"model": "text-embedding-nomic-embed-text-v1.5", "input": text})["data"][0]["embedding"]
 
def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
 
index = [(doc, embed(doc)) for doc in DOCS]
 
def ask_rag(query, top_k=2):
    q_vec = embed(query)
    ranked = sorted(index, key=lambda item: cosine(q_vec, item[1]), reverse=True)[:top_k]
    context = "\n".join(f"- {doc}" for doc, _ in ranked)
    prompt = f"Answer using ONLY this context. If missing, say you do not know.\n\nContext:\n{context}\n\nQuestion: {query}"
    reply = post("/chat/completions", {
        "model": "meta-llama-3.1-8b-instruct",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.0,  # 0.0: least random output
    })["choices"][0]["message"]["content"]
    return ranked, prompt, reply
 
for q in ["How much is the remote equipment allowance and how do I claim it?", "What is our parental leave policy?"]:
    ranked, prompt, reply = ask_rag(q)
    print(f"=== QUERY: {q}")
    print("TOP CHUNKS:", [d[:60] + "..." for d, _ in ranked])
    print("OUTPUT:", reply, "\n")

What the Script Printed

I ran simple_rag.py on Windows 11 with LM Studio, using the two models above. I did not test multi-page PDF chunking, an external vector database, or a run without the refusal instruction in the prompt.

=== QUERY: How much is the remote equipment allowance and how do I claim it?
TOP CHUNKS: ['Remote equipment allowance: Full-time engineers receive $600...', 'Annual travel policy: Conference travel up to $1,800 per yea...']
OUTPUT: The remote equipment allowance is $600 every 24 months. To claim it, you need to submit receipts in Expensify within 30 days. 
 
=== QUERY: What is our parental leave policy?
TOP CHUNKS: ['Annual travel policy: Conference travel up to $1,800 per yea...', 'Remote equipment allowance: Full-time engineers receive $600...']
OUTPUT: I do not know. 

The first query ranks the equipment policy first, and the model returns the $600 allowance, the 24-month interval and the Expensify rule. It also shows what top_k=2 costs: the second chunk, the travel policy, has nothing to do with the question, and the retriever returns it anyway. The model ignored it.

The second query asks about something the knowledge base never mentions. The retriever still returns two chunks, because it always returns top_k=2, but with the strict instruction in the prompt, meta-llama-3.1-8b-instruct answered "I do not know" instead of inventing a parental leave policy.

Common Errors When Building Simple RAG

  • Embedding model mismatch: Indexing documents with one embedding model and querying with another produces meaningless cosine scores. Use the exact same embedding model ID for both steps.
  • Chunks that are too large or too small: Splitting mid-sentence drops subjects and numbers, while 2,000-token chunks dilute similarity scores. As a rule of thumb, start with 200 to 400 words per chunk and preserve headings.
  • Skipping data preprocessing: How you chunk matters, but the input also needs cleaning before you chunk it. Source documents often carry stray characters and tags such as Figure, Table, <xml> or <div>. They end up inside chunks, skew the embedding vectors and take up room in the prompt. Strip them out before splitting.
  • Missing refusal instruction: Without an explicit instruction to answer only from the supplied context, a small model can fall back to its training weights when the retrieved chunks are irrelevant.

Takeaways

Build retrieval when the corpus is too big to send on every turn, when answers get worse as the prompt grows, or when users need different access rights. Whatever the pipeline looks like, the 45 lines show the part that stays the same: retrieve a few chunks, tell the model to answer only from them, and let it say "I do not know".

Sources

|Share:

Subscribe to our newsletter

Get the latest articles and updates delivered to your inbox.

pxuanbach
Written by

pxuanbach

Software Engineer at UtilKits. Writing about AI, development, and technology trends.

Related Articles