---
title: "RAG vs Fine-Tuning: How to Build a RAG Pipeline That Works"
url: "https://goremy.ai/blog/articles/build-a-rag-pipeline-that-works"
author: Luis Chavez-Mattos
editor: Luis Chavez-Mattos
editor_title: Director, Product
published: "2026-12-04T12:40:27.552Z"
updated: "2026-12-04T12:40:27.552Z"
topic: Coding and DevOps with AI
description: Build a RAG pipeline step by step, then decide between RAG and fine-tuning with a clear decision table, copy-ready eval prompts, and common failure fixes.
---

# RAG vs Fine-Tuning: How to Build a RAG Pipeline That Works

> Build a RAG pipeline step by step, then decide between RAG and fine-tuning with a clear decision table, copy-ready eval prompts, and common failure fixes.

Edited by Luis Chavez-Mattos, Director, Product · Published 2026-12-04

## What is the difference between RAG and fine-tuning?

RAG (retrieval-augmented generation) gives a model the right information at question time: your system searches your documents, pastes the relevant passages into the prompt, and the model answers from them. Fine-tuning changes the model itself by training it on examples, so it behaves differently: a different format, tone, or skill. Use RAG when the problem is knowledge (facts that are private, large, or changing). Use fine-tuning when the problem is behavior.

Most teams that ask "RAG or fine-tuning?" have a knowledge problem, so they should start with RAG. This post shows how to build a RAG pipeline that holds up outside a demo, then how to tell when fine-tuning is the right next step.

## TL;DR

- **RAG fixes what the model doesn't know; fine-tuning fixes how the model behaves.** Mixing these up is the most common reason projects stall.
- **Build your evaluation set before your pipeline.** Twenty to fifty real questions with known answers and known source passages will guide every decision after that.
- **Chunking and retrieval quality decide most outcomes**, far more than which model writes the final answer. Hybrid search (semantic plus keyword) with a reranker is a strong default.
- **Measure retrieval and generation separately.** If the right passage never reaches the model, no prompt will save you.
- **Fine-tune only after RAG and prompting are working** and you can name a specific behavior gap, with examples, that they can't close.
- **Plan for permissions, freshness and citations from day one.** These are what make internal users trust the tool.

## When should you use RAG, and when should you fine-tune?

Start from the symptom, not the technique.

| Symptom | What's wrong | Start with |
|---|---|---|
| Model invents policies, product details or numbers | Missing knowledge | RAG |
| Answers go stale when documents change | Knowledge changes | RAG (re-index, don't retrain) |
| Users need to see where an answer came from | Need for citations | RAG |
| Different users may see different documents | Access control | RAG with permission filters |
| Output format is inconsistent despite clear instructions and examples | Behavior | Better prompt, then fine-tuning |
| Model needs a specific tone or house style at scale | Behavior | Prompt with examples, then fine-tuning |
| Narrow, repetitive task (classify, extract, route) where you have thousands of labeled examples | Behavior and cost | Fine-tuning, possibly a smaller model |
| Prompts are huge because of long instructions and examples | Cost and latency | Fine-tuning can shorten prompts |
| Model lacks a domain skill, such as an internal query language | Skill | Fine-tuning, often alongside RAG |

Two rules of thumb hold up well:

1. **Facts go in the index, habits go in the weights.** If you'd update it when a document changes, it belongs in retrieval. Training a fact into a model makes it hard to correct, hard to cite and impossible to permission.
2. **Try the cheaper tool first.** A better prompt takes an hour. A RAG pipeline takes days. A fine-tune takes data collection, training runs, evaluation and a plan to repeat it when the base model changes.

## How do you build a RAG pipeline that works?

Here are the steps in order. The order matters: the evaluation set comes first because everything else gets tuned against it.

### Step 1: Write the questions before you write the code

Collect 20 to 50 real questions from the people who will use the system. Pull them from support tickets, chat threads, search logs or interviews. For each one, record:

- The question as a user would phrase it
- The correct answer, in a sentence or two
- The document and passage where that answer lives
- Whether it's easy (one passage), hard (needs several passages), or unanswerable (the documents don't say)

Include unanswerable questions. A good system says "I couldn't find that" instead of guessing, and you can only test that if you have cases for it.

If you don't have questions yet, an AI can draft candidates from your documents. Use this prompt, then have a subject-matter expert correct the results:

```
Below is a passage from our internal documentation. Write 3 questions an
employee might realistically ask that this passage answers. Use casual,
natural phrasing, not words copied from the passage. For each question give:
(1) the question, (2) the correct answer in 1-2 sentences, (3) the exact
sentence from the passage that supports it.

Passage:
[paste passage]
```

Check these carefully. AI-written questions tend to echo the passage's wording, which makes retrieval look easier than it will be with real users. Rewrite a third of them in plainer, vaguer language.

### Step 2: Collect and clean the documents

Decide what's in scope and who owns each source. Then clean:

- Convert PDFs, slides and web pages to text and check the output by eye. Tables, headers, footers and multi-column layouts often come out garbled.
- Remove boilerplate that repeats on every page (navigation, legal footers), which pollutes search results.
- Keep metadata: title, source URL or file path, author, last-updated date, department, and access level. You'll need it for filtering, citations and freshness.
- Deduplicate. Five copies of last year's handbook will crowd out the current one.

### Step 3: Chunk the documents

Chunking means splitting documents into pieces small enough to retrieve precisely. It's the step teams most often get wrong.

- **Split on structure first.** Break at headings and sections, then at paragraphs. Only split mid-paragraph when a section is too long.
- **Start with chunks of a few hundred tokens**, with a small overlap (roughly 10 to 20 percent) so a sentence cut at a boundary still appears whole somewhere. Treat these as starting values and tune them against your evaluation set.
- **Attach context to every chunk.** Prepend the document title and section heading to the chunk text. A chunk that says "The limit is 5,000" is useless without knowing what it's the limit of.
- **Keep tables and lists intact** where you can. A table split across chunks loses its meaning.

### Step 4: Embed and index

An embedding model turns each chunk into a list of numbers that represents its meaning, so similar text lands close together. You store those vectors in a vector index alongside the original text and metadata.

Practical notes:

- Use the same embedding model for indexing and for queries. Changing it later means re-embedding everything.
- Store the metadata from Step 2 with each chunk so you can filter on it.
- Keep a record of which document version each chunk came from, so updates replace old chunks instead of stacking up beside them.

### Step 5: Retrieve with hybrid search and rerank

Pure semantic search is good at meaning and bad at exact strings: product codes, error numbers, names, acronyms. Keyword search (BM25 and similar) is the reverse. Run both and merge the results. This is called hybrid search, and it's a strong default for business documents.

Then add a reranker: a second model that takes the top 20 to 50 candidates and re-scores them against the question more carefully. Send only the best few chunks to the language model. Reranking is often the cheapest big improvement you can make to a pipeline that is "almost working."

Apply metadata filters before or during search (department, region, access level, date), not after generation.

### Step 6: Write a grounded prompt

The prompt should tell the model to answer only from the supplied passages, cite them, and admit when they don't contain the answer. A solid starting template:

```
You answer questions using only the numbered sources below.

Rules:
- If the sources do not contain the answer, say "I couldn't find that in
  the documents" and stop. Do not guess.
- Cite the source number after each claim, like [2].
- If sources conflict, say so and name both, with their dates.
- Keep the answer short and in plain language.

Sources:
[1] (title, last updated: date) passage text...
[2] (title, last updated: date) passage text...

Question: {user question}
```

Include the document date in each source. It lets the model, and the reader, notice that one answer comes from a 2021 policy.

### Step 7: Evaluate retrieval and generation separately

This is the step that separates pipelines that work from pipelines that merely demo well. Run your evaluation set and score two things independently:

1. **Retrieval:** Did the correct passage appear in the top results? Track how often it's in the top 5 and top 20. If this number is low, fix chunking, search or reranking. Don't touch the prompt yet.
2. **Generation:** Given the correct passage, did the model answer correctly, cite correctly and stay within the sources? If retrieval is good but answers are bad, fix the prompt or try a different model.

Also check the unanswerable questions: does the system decline, or does it fabricate?

You can use an AI model as a first-pass grader, but only as a screen:

```
You are grading an answer from a document Q&A system.

Question: {question}
Reference answer (correct): {reference}
System answer: {answer}
Sources the system was given: {sources}

Grade each item as PASS or FAIL with one sentence of reasoning:
1. Does the system answer agree with the reference answer?
2. Is every claim in the system answer supported by the given sources?
3. Are the citations pointing to sources that actually support the claim?
```

Read every FAIL yourself and a sample of PASS results. AI graders are generous, especially toward answers written by a similar model.

### Step 8: Prepare for real use

Before you release it to colleagues:

- **Permissions.** Filter retrieval by what the signed-in user is allowed to see. Don't rely on the model to withhold information it was handed.
- **Freshness.** Decide how updates reach the index (on a schedule, on document change) and how deleted documents get removed.
- **Citations in the interface.** Link each citation to the source document so users can verify.
- **Logging.** Record questions, retrieved passages and answers. Failed questions become next month's evaluation cases.
- **Feedback.** A thumbs up or down with an optional comment gives you labeled data for free.

## Why do RAG pipelines fail, and how do you fix each one?

Diagnose by looking at what the model was actually given for a failed question.

| What you see | Likely cause | Fix |
|---|---|---|
| Right document exists, never retrieved | Chunks too large or too small, vague query, embedding mismatch | Adjust chunking, add hybrid search, rewrite queries before search |
| Exact codes or names not found | Semantic-only search | Add keyword search |
| Right passage retrieved but ranked low | No reranking | Add a reranker, send fewer, better chunks |
| Answer mixes old and new policy | Duplicate or outdated documents | Deduplicate, filter by date, show dates to the model |
| Confident answer, source doesn't say it | Weak grounding instructions | Tighten the prompt, require citations, add "I couldn't find it" cases to your tests |
| Answer needs two documents and gets half | Single-pass retrieval | Retrieve more candidates, or let the system run a second search |
| Fragment makes no sense out of context | Chunk lacks title or heading | Prepend title and section to each chunk |
| Great in testing, poor in production | Test questions were too clean | Rebuild the evaluation set from real user logs |

## When is fine-tuning the right call?

Fine-tuning earns its cost when all of these are true:

1. You have a **specific behavior gap**, written down with examples, that careful prompting and RAG haven't closed.
2. You have **good training data**: hundreds to thousands of high-quality input and output examples, consistently labeled, that reflect what you want. Quality matters more than volume.
3. You have a way to **measure** the improvement against a held-out test set.
4. The behavior is **stable**. If requirements change monthly, retraining becomes a treadmill.

Good candidates:

- **Consistent structured output** for a narrow task, such as extracting fields from invoices or classifying tickets into your categories
- **Matching a house style** across thousands of generated messages
- **Teaching a domain skill** such as an internal query language or specialized notation
- **Cost and latency reduction**: a smaller fine-tuned model can sometimes replace a larger model plus a long prompt on a narrow task

Poor candidates:

- Teaching the model your company's facts. They go stale, can't be cited, and can't be restricted by user.
- Fixing hallucinations on questions the model has no source for. Retrieval plus "say you don't know" works better.
- Anything where you can't produce clean examples.

Check the current terms of your model provider or platform before you plan a fine-tune: which models can be tuned, what data you may upload, and how pricing works vary and change.

## Can you combine RAG and fine-tuning?

Yes, and mature systems often do. The usual pattern: RAG supplies the facts, and a fine-tuned model (or a fine-tuned reranker or embedding model) handles the behavior. For example, a support assistant retrieves the current policy text through RAG, while a model tuned on your best past replies writes in your tone and format.

You can also fine-tune the retrieval components rather than the generator. If your domain has specialized vocabulary and your retrieval metrics are weak despite good chunking and hybrid search, a tuned embedding model or reranker trained on your question and passage pairs can help, and your Step 1 evaluation set doubles as a way to prove it.

The order to follow: prompt, then RAG, then tune what your measurements point to.

## Where should you not trust AI in this process?

- **Evaluation labels.** Use AI to draft questions and screen answers, but have a person confirm the correct answers and sources.
- **Citations.** Models can attach a citation to a claim the source doesn't support. Verify by checking the cited passage, not by trusting the format.
- **Policy, legal, HR and financial answers.** Route high-stakes questions to a human owner, and show the document's date and owner in the answer.
- **"Is my pipeline good?"** Ask your evaluation set, not the model.
- **Confidential data.** Check where your documents and queries are sent before indexing anything sensitive, and follow your company's data rules.

## Do you have to build the retrieval layer yourself?

Not always. If your goal is an internal tool that answers questions from your own documents, the retrieval plumbing (chunking, embedding, hybrid search, reranking, sign-in, permissions, a front end) is a lot to assemble before you reach the part that matters, which is your evaluation set. [Remy](https://goremy.ai) is an AI product agent that builds full-stack apps from a plain-English description, and every app it builds includes managed vector search over documents with hybrid semantic and keyword search, reranking and cited results. You could describe a policy assistant or support knowledge base, get a deployed app with built-in sign-in and role-based access, and spend your time testing it against your questions.

## Frequently Asked Questions

### Is RAG better than fine-tuning?

Neither is better in general. They solve different problems. RAG supplies knowledge the model lacks, with citations and easy updates. Fine-tuning changes behavior such as format, style or a narrow skill. For questions about your own documents, RAG is almost always the right first move.

### Does fine-tuning stop hallucinations?

Not reliably. A fine-tuned model can still produce confident wrong answers, and facts baked into weights can't be traced to a source. Grounding answers in retrieved passages, requiring citations and testing that the system declines when the documents are silent works better.

### How big should my chunks be?

Start with a few hundred tokens, split along headings and paragraphs, with a modest overlap, and put the document title and section heading in every chunk. Then test variations against your evaluation set. The right size depends on your documents and the questions people ask.

### How do I know if my RAG pipeline is working?

Build a set of real questions with known answers and source passages, then measure two things separately: whether the right passage is retrieved, and whether the model answers correctly from it. Include questions the documents can't answer, and confirm the system says so.

### When should I move from RAG to fine-tuning?

When RAG is retrieving the right material, your prompts are well written, and you can still point to a repeatable behavior problem, such as inconsistent formatting or a missing domain skill, with enough clean examples to train on. If the problem is missing or wrong facts, fix retrieval instead.
