LevelUpWith

Explore / Retrieval Engineering for LLM Apps: RAG That Works / Lesson 1

Lesson 1: Anatomy of a RAG Pipeline and Where It Breaks

Learn the stages of a retrieval-augmented system (ingest, parse, chunk, embed, index, retrieve, rerank, generate) and which stage usually causes a wrong or missing answer.

Free to read, no account needed. Part of Retrieval Engineering for LLM Apps: RAG That Works.

By the end of this level you'll be able to

  • Draw your own demo's pipeline stage by stage and name the input and output of each stage
  • Instrument a Python RAG script so it logs the retrieved chunks, scores and final prompt for every query
  • Sort ten failed answers into retrieval failures and generation failures using those logs

Why your demo lies to you

Your first RAG demo probably looked like this: load some PDFs, split them, embed them, put them in a vector database, and pass the top 5 hits to an LLM. It worked on the three questions you tried, then it failed on the fourth with a confident wrong answer. The natural move is to change the prompt or swap the model. Usually that is the wrong move.

A RAG system is a pipeline, and a wrong answer can start at any stage. The model only sees what the earlier stages hand it. If the paragraph with the answer never reached the prompt, no prompt wording will fix it. The first skill in retrieval engineering isn't a clever technique. It's being able to point at a failure and say which stage caused it.

The idea goes back to Lewis et al.'s 2020 NeurIPS paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. It paired a generator with a dense index of Wikipedia searched by a neural retriever. Production systems have since grown more stages, and each stage is another place for things to go wrong.

The eight stages, with inputs and outputs

Think of a kitchen line. If the dish is wrong, you don't blame the plating station until you've checked that the right ingredients arrived.

Stage Input Output Typical way it breaks
Ingest Source systems (drive, wiki, S3) Raw files plus metadata Documents missing or stale
Parse PDF, HTML, scans Clean text, tables, structure Tables mangled, scanned pages come out empty
Chunk Parsed text Passages with IDs Answer split across two chunks
Embed Chunks (and later, queries) Vectors The model doesn't capture your domain's terms
Index Vectors plus metadata A searchable index Wrong filters, old versions still present
Retrieve Query Top-k chunks with scores The right chunk ranks 9th when k=5
Rerank Candidate chunks Reordered, trimmed list Good chunk gets pushed out
Generate Prompt (query plus chunks) Answer Ignores, misreads or adds to the context

The first five stages run offline when you build the index. The last three run on every query. Your demo may skip reranking; that's fine, so leave that box empty in your diagram.

Barnett et al.'s Seven Failure Points When Engineering a RAG System (CAIN 2024) catalogued failures from three real deployments. Read the list and notice how many of them happen before generation:

  1. Missing content (the answer isn't in the corpus)
  2. Missed the top-ranked documents (the answer exists but ranks below k)
  3. Not in context (it was retrieved but dropped when the prompt was assembled)
  4. Not extracted (it's in the prompt but the model misses it)
  5. Wrong format
  6. Incorrect specificity
  7. Incomplete

The first three are failures of retrieval or context assembly. Rewriting the prompt can't fix any of them.

Walkthrough: instrument your script

You can't sort failures you can't see. Wrap your query path so every call writes one JSON line holding the query, each retrieved chunk with its score, the exact prompt and the answer. retrieve, build_prompt and generate are your existing functions, whatever vector store and LLM client they use.

import json, time, uuid

LOG_PATH = "rag_trace.jsonl"

def answer(query: str, k: int = 5) -> str:
    trace = {"id": str(uuid.uuid4()), "ts": time.time(), "query": query, "k": k}

    t0 = time.perf_counter()
    hits = retrieve(query, k=k)  # your vector DB call -> list of dicts
    trace["retrieve_ms"] = round((time.perf_counter() - t0) * 1000)

    # Log the full chunk text, not only IDs: you'll read these by hand.
    trace["hits"] = [
        {"rank": i + 1, "chunk_id": h["id"], "source": h["source"],
         "score": round(h["score"], 4), "text": h["text"]}
        for i, h in enumerate(hits)
    ]

    prompt = build_prompt(query, hits)
    trace["prompt"] = prompt  # the exact string sent, after any truncation

    reply = generate(prompt)
    trace["answer"] = reply

    with open(LOG_PATH, "a", encoding="utf-8") as f:
        f.write(json.dumps(trace, ensure_ascii=False) + "\n")
    return reply

A single line from a log of an HR handbook demo:

{"query": "How many days of parental leave do contractors get?",
 "hits": [
  {"rank": 1, "chunk_id": "handbook.pdf#p12-c3", "score": 0.8123, "text": "Employees are entitled to 16 weeks of parental leave..."},
  {"rank": 2, "chunk_id": "benefits.html#c7", "score": 0.7990, "text": "Parental leave requests must be filed 30 days..."}],
 "answer": "Contractors get 16 weeks of parental leave."}

The answer looks fluent. The log shows that no retrieved chunk mentions contractors at all, so the model applied the employee rule to them.

Gotcha: scores aren't comparable across stores. Some stores return a similarity (higher is better), others a distance (lower is better). Check which kind yours returns before you read anything into 0.81. Even then, scores mean little across different queries. Use them to compare chunks within one query.

Gotcha: log the prompt after assembly. If your code truncates chunks to fit a token limit, the hits list and the prompt differ. That gap is failure point 3.

Walkthrough: sort failures into buckets

For each failed query, write down a short phrase that a correct answer must rest on (for example "contractors are not eligible"). Then do a first rough sort:

def triage(trace: dict, evidence: str) -> str:
    ev = evidence.lower()
    in_hits = any(ev in h["text"].lower() for h in trace["hits"])
    in_prompt = ev in trace["prompt"].lower()
    if not in_hits:
        return "retrieval"         # look upstream: corpus, parse, chunk, embed, rank
    if not in_prompt:
        return "context assembly"  # retrieved, then dropped or truncated
    return "generation"            # evidence was in front of the model

fails = [json.loads(l) for l in open(LOG_PATH, encoding="utf-8")]
# pair each failed trace with its evidence phrase, then count buckets

The substring check is crude, because evidence may be paraphrased or split across chunks. Use it to sort quickly, then confirm each case by reading the chunks. A "retrieval" result also covers the case where the answer was never in the corpus at all (failure point 1). Search your raw files for the phrase to tell those apart.

In practice, when engineers sort their first batch this way, the retrieval bucket is often the biggest. Treat that as a rule of thumb rather than a measured law, and let your own counts decide.

Hands-on exercise

  1. Draw your demo's pipeline as boxes, one per stage in the table above. Under each box, write its real input and output (for example, Chunk: Markdown text → 512-token passages, 50-token overlap). Mark any stage your demo skips.
  2. Add the answer() wrapper to your script and run 20 or more real questions through it.
  3. Pick ten wrong or missing answers. Write an evidence phrase for each, run triage, then read every trace by hand and fix any wrong labels.
  4. Record the counts: retrieval / context assembly / generation / not in corpus. Keep this file, because later levels build on it.

Key takeaways

  • A RAG system has eight stages: ingest, parse, chunk, embed, index, retrieve, rerank, generate. A wrong answer can start at any of them.
  • The model only sees what retrieval hands it. Check the retrieved chunks before you touch the prompt or the model.
  • Log the query, every chunk with its score and text, the final assembled prompt and the answer, one JSON line per query.
  • Sort failures by asking: was the evidence retrieved? Did it reach the prompt? Did the model use it?
  • Scores depend on the store (similarity or distance), so compare them within one query, not across queries.

A 6-question knowledge check follows this lesson in the app, free and without an account.

More like this