# Build a Simple RAG Pipeline in Python

> How to build a RAG pipeline in Python without a framework or API key: chunk Markdown by heading, embed with Ollama, retrieve with NumPy, prompt a local LLM, and chart retrieval accuracy.

Source: https://www.pythoncharts.com/ai/simple-rag-pipeline-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: AI | Tags: llm, rag, retrieval augmented generation, embeddings, ollama, semantic search

A RAG (retrieval augmented generation) pipeline has four steps: split your documents into chunks, turn each chunk into an embedding vector, find the chunks closest to a question, and give those chunks to a language model to answer from. This version uses `ollama.embed()`, a NumPy dot product, and `ollama.chat()`, with no framework, vector database, or API key.

## Quick Example

The documents are a short, made-up handbook for a bike co-op, so the model can't already know the answers. Install [Ollama](https://www.pythoncharts.com/ai/run-local-llms-ollama-python/), then download the two models (about 3.7 GB together):

```bash
ollama pull embeddinggemma-2:270m
ollama pull qwen3.5:4b-q4_K_M
pip install ollama numpy pandas matplotlib
```

```python
import numpy as np
import ollama
import pandas as pd

HANDBOOK = """
# Membership
## Plans and prices
Harbor Bike Co-op has three plans. A Day Pass costs $9. A Monthly membership costs $24, and an Annual membership costs $180. Students pay half price on the Annual plan.
## Joining requirements
Riders must be at least 16 years old. Riders aged 16 or 17 need a guardian to sign the waiver. A government photo ID is checked at the first pickup.
## Cancelling
Monthly members can cancel at any time and keep access until the paid period ends. Annual members get a prorated refund for unused full months, minus a $15 processing fee.
## Pausing
A membership can be paused for one to three months per calendar year. Paused months are added to the end of the term.

# Rentals
## Ride time limits
Each trip includes 45 minutes on a standard bike and 30 minutes on an e-bike. After that, every extra 15 minutes costs $3.
## Reservations
Members can reserve a bike up to 20 minutes ahead in the app. A reservation that isn't unlocked in time is cancelled, and three missed reservations in a week block booking for seven days.
## Returning a bike
A ride ends when the bike clicks into a dock and the dock light turns green. If a station is full, the app grants 15 free minutes to reach another one.
## Cargo bikes
Cargo bikes can be booked for up to 4 hours and carry at most 80 kilograms of load. Booking one requires having completed five rides.

# Safety
## Helmets
Helmets are free to borrow at the Pier Street and Library stations. Riders under 18 must wear one.
## Reporting a crash
Report any crash in the app within 24 hours, even without injuries. Call emergency services first if anyone is hurt.
## Night riding
All bikes have lights that switch on automatically. E-bikes are limited to 15 kilometers per hour between 10 pm and 5 am.

# Fees and damage
## Late and lost bikes
A bike not returned within 24 hours is treated as lost and the rider is charged $1,200. The charge is reversed, minus a $50 recovery fee, if the bike is found within 30 days.
## Damage
Normal wear is free. Riders pay up to $150 for damage caused by careless use, such as leaving a bike in water.
## Disputing a charge
Disputes must be sent through the app within 14 days of the charge. The billing team replies within five business days.

# Volunteering
## Repair nights
Repair nights run on the first and third Wednesday of each month from 6 to 9 pm at the Dock 4 workshop. No experience is needed.
## Ride credits
Each volunteer shift earns a $10 ride credit. Credits expire after 12 months.
"""

def chunk_by_heading(markdown):
    """One chunk per "##" section, remembering which "#" document it came from."""
    chunks = []
    for line in markdown.strip().splitlines():
        if line.startswith("## "):
            chunks.append({"doc": doc, "section": line[3:], "text": ""})
        elif line.startswith("# "):
            doc = line[2:]
        elif line.strip():
            chunks[-1]["text"] = (chunks[-1]["text"] + " " + line).strip()
    return pd.DataFrame(chunks)

EMBED_MODEL = "embeddinggemma-2:270m"
CHAT_MODEL = "qwen3.5:4b-q4_K_M"

def embed(texts):
    return np.array(ollama.embed(model=EMBED_MODEL, input=texts).embeddings)

# 1. Chunk and 2. embed (once)
chunks = chunk_by_heading(HANDBOOK)
chunk_vectors = embed([f"title: {c.doc} - {c.section} | text: {c.text}" for c in chunks.itertuples()])

# 3. Retrieve
def retrieve(question, k=3):
    query_vector = embed(["task: search result | query: " + question])[0]
    scores = chunk_vectors @ query_vector  # cosine similarity: the vectors have length 1
    top = np.argsort(-scores)[:k]
    return chunks.iloc[top].assign(score=scores[top])

# 4. Generate
INSTRUCTIONS = ("Answer the question using only the handbook excerpts. Be brief and name the section you used. "
                "If the excerpts don't contain the answer, reply exactly: I don't know.")

def ask(question, instructions=INSTRUCTIONS, k=3, think=False):
    excerpts = "\n\n".join(f"[{c.section}]\n{c.text}" for c in retrieve(question, k).itertuples())
    response = ollama.chat(
        model=CHAT_MODEL,
        messages=[{"role": "system", "content": instructions},
                  {"role": "user", "content": f"Excerpts:\n{excerpts}\n\nQuestion: {question}"}],
        think=think,
        options={"temperature": 0, "seed": 1},
    )
    return response.message.content

question = "What does Harbor Bike Co-op charge if I lose a bike?"
print(ask(question))
```

```text
Harbor Bike Co-op charges $1,200 if a bike is not returned within 24 hours. If the bike is found within 30 days, the charge is reversed minus a $50 recovery fee.

Section used: [Late and lost bikes]
```

## What Does the Model Say Without Retrieval?

Ask the same model the same question with no excerpts:

```python
response = ollama.chat(model=CHAT_MODEL, messages=[{"role": "user", "content": question}], think=False,
                       options={"temperature": 0, "seed": 1, "num_predict": 60})
print(response.message.content)
```

```text
Harbor Bike Co-op generally **does not charge a fee** for the loss of a bicycle. Their primary mission is to provide affordable, high-quality bikes to members and the community, and they operate on a non-profit model focused on accessibility rather than profit generation.

However, while there is no
```

It made up a policy, fluently. The reply is cut off by `num_predict=60`. Retrieval gives the model the text it needs, and the instruction to say "I don't know" gives it a way out when the text isn't there.

## Check What Was Retrieved

Look at the retrieved chunks before you judge the answer:

```python
print(retrieve(question)[["section", "score"]].to_string(index=False))
```

```text
            section    score
   Plans and prices 0.836606
             Damage 0.774312
Late and lost bikes 0.770719
```

The chunk with the answer, "Late and lost bikes", came third. The "Plans and prices" chunk ranked first because it is also about charges. With `k=1` this question would have failed.

## How Should You Chunk the Documents?

To compare chunking methods, write questions along with a phrase that the right passage must contain. The **hit rate** is the share of questions where that phrase appears somewhere in the top `k` chunks:

```python
QUESTIONS = [
    ("How much is a yearly membership?","$180"),
    ("Can a 16 year old sign up?","guardian"),
    ("What do I get back if I quit my annual plan early?","$15"),
    ("I'm travelling for two months. Can I freeze my account?","one to three months"),
    ("How long can I ride an electric bike before paying extra?","30 minutes"),
    ("What happens if I don't show up for bikes I booked?","seven days"),
    ("The dock is full. What now?","15 free minutes"),
    ("How heavy a load can the cargo bike take?","80 kilograms"),
    ("Where can I borrow a helmet?","Pier Street"),
    ("I fell off but I'm fine. Do I need to tell anyone?","24 hours"),
    ("Do e-bikes go slower late at night?","15 kilometers"),
    ("What will it cost me if a bike goes missing?","$1,200"),
    ("I dropped a bike in the harbor. What's the most I could pay?","$150"),
    ("How long do I have to contest a bill?","14 days"),
    ("When can I help fix bikes?","Wednesday"),
    ("Do my volunteer credits run out?","12 months"),
]

plain = " ".join(line.lstrip("# ") for line in HANDBOOK.split("\n") if line.strip())
documents = [d.strip() for d in HANDBOOK.split("\n# ") if d.strip()]
METHODS = {
    "Sections (by heading)": [f"{c.section}. {c.text}" for c in chunks.itertuples()],
    "Fixed 100 characters": [plain[i:i + 100] for i in range(0, len(plain), 100)],
    "Fixed 400 characters": [plain[i:i + 400] for i in range(0, len(plain), 400)],
    "Whole documents": documents,
}

query_vectors = embed(["task: search result | query: " + q for q, _ in QUESTIONS])
results = []
for method, texts in METHODS.items():
    vectors = embed(["title: none | text: " + t for t in texts])
    ranking = np.argsort(-(query_vectors @ vectors.T), axis=1)
    for k in (1, 2, 3, 4):
        found = [[texts[i] for i in row[:k]] for row in ranking]
        hit = np.mean([any(phrase in t for t in top) for top, (_, phrase) in zip(found, QUESTIONS)])
        sent = np.mean([sum(map(len, top)) for top in found])
        results.append({"method": method, "k": k, "hit_rate": hit, "characters": sent})
results = pd.DataFrame(results)
print(results.pivot(index="method", columns="k", values="hit_rate").loc[list(METHODS)].round(2))
```

```text
k                         1     2     3     4
method                                       
Sections (by heading)  0.88  1.00  1.00  1.00
Fixed 100 characters   0.69  0.75  0.88  0.88
Fixed 400 characters   0.62  0.94  1.00  1.00
Whole documents        0.94  1.00  1.00  1.00
```

Comparing methods at the same `k` favors big chunks, because three whole documents are far more text than three sections. Plot hit rate against the amount of text sent to the model instead:

```python
import matplotlib.pyplot as plt

chunk_fig, ax = plt.subplots(figsize=(8, 4.6))
styles = zip(METHODS, ["#1b6ca8", "#c8553d", "#8a9a5b", "#7b5ea7"], ["o", "s", "^", "D"])
for method, color, marker in styles:
    part = results[results["method"] == method]
    ax.plot(part["characters"], part["hit_rate"], marker=marker, color=color, label=method, lw=2)
ax.set_xlabel("Characters of context sent to the model (average, for k = 1 to 4)")
ax.set_ylabel("Hit rate over 16 questions")
ax.set_title("Retrieval hit rate by chunking method")
ax.spines[["top", "right"]].set_visible(False)
ax.grid(alpha=0.25)
ax.legend(frameon=False, loc="lower right")
chunk_fig.tight_layout()
plt.show()
```

![Line chart of retrieval hit rate against characters of context for four chunking methods: heading sections reach 100 percent at about 300 characters, while whole documents and 400-character chunks need about 1,000 or more](https://www.pythoncharts.com/ai/simple-rag-pipeline-python/images/rag-retrieval-by-chunking.png)

Splitting by heading reached a 100% hit rate with about 300 characters of context (`k=2`). Whole documents needed about 1,000 characters to get there and 400-character chunks about 1,100. The 100-character chunks stopped at 88%, since a tiny slice often separates a fact from the words that say what it's about, or cuts the phrase in two. This comparison is on one small, tidy handbook with 16 questions, so run it on your own documents before picking a method.

## Can a Similarity Score Detect Unanswerable Questions?

It's tempting to skip the model when the best score is low. Compare the best score for answerable questions with questions the handbook doesn't cover:

```python
UNANSWERABLE = ["Can I bring my dog on a cargo bike?", "Is there a family plan?",
                "What is the capital of France?", "Do you offer scooter rentals?",
                "Can I pay with cash?", "Is there a station at the airport?"]

best = {"Answerable": [retrieve(q)["score"].max() for q, _ in QUESTIONS],
        "Not in the handbook": [retrieve(q)["score"].max() for q in UNANSWERABLE]}

score_fig, ax = plt.subplots(figsize=(8, 3.2))
rng = np.random.default_rng(5)
for y, (label, scores), color in zip((1, 0), best.items(), ["#2a7f62", "#d1495b"]):
    ax.scatter(scores, y + rng.uniform(-0.12, 0.12, len(scores)), s=60, color=color, alpha=0.8)
    print(f"{label}: {min(scores):.2f} to {max(scores):.2f}")
ax.set_yticks((1, 0), best)
ax.set_ylim(-0.5, 1.5)
ax.set_xlabel("Cosine similarity of the best chunk")
ax.set_title("Top retrieval score for each question")
ax.spines[["top", "right"]].set_visible(False)
score_fig.tight_layout()
plt.show()
```

```text
Answerable: 0.68 to 0.85
Not in the handbook: 0.56 to 0.78
```

![Dot plot of best similarity scores: answerable questions range from 0.68 to 0.85 and unanswerable ones from 0.56 to 0.78, so the two groups overlap](https://www.pythoncharts.com/ai/simple-rag-pipeline-python/images/rag-top-scores.png)

The groups overlap. The dog question scores 0.78 because the handbook has a section on cargo bikes, even though it says nothing about dogs. A threshold high enough to reject it would also reject at least 7 of the 16 real questions. A low cutoff can still screen out clearly unrelated questions, but let the model make the final call.

## Is It a Retrieval Problem or a Generation Problem?

Now run every question through the whole pipeline. An answer counts if it contains the expected phrase:

```python
def evaluate(instructions):
    missed = [q for q, phrase in QUESTIONS if phrase not in ask(q, instructions)]
    refused = sum("I don't know" in ask(q, instructions) for q in UNANSWERABLE)
    print(f"{len(QUESTIONS) - len(missed)} of {len(QUESTIONS)} answered, "
          f"{refused} of {len(UNANSWERABLE)} unanswerable declined")
    return missed

for q in evaluate(INSTRUCTIONS):
    print(q, "->", ask(q), "| retrieved:", ", ".join(retrieve(q)["section"]))
```

```text
14 of 16 answered, 6 of 6 unanswerable declined
I'm travelling for two months. Can I freeze my account? -> I don't know. | retrieved: Cancelling, Pausing, Reservations
When can I help fix bikes? -> I don't know. | retrieved: Damage, Late and lost bikes, Repair nights
```

Both misses have the right section in the excerpts ("Pausing" and "Repair nights"), so search did its job. The model refused because the question's words ("freeze my account", "help fix bikes") don't match the handbook's. Loosen the instructions and run the same test:

```python
LOOSER = ("Answer the question using the handbook excerpts. The question may use different words from "
          "the handbook. Be brief and name the section you used. "
          "If the excerpts don't cover the topic, reply exactly: I don't know.")

missed = evaluate(LOOSER)
for q, _ in (QUESTIONS[3], QUESTIONS[14]):
    print(q, "->", ask(q, LOOSER).replace("\n", " "))
```

```text
16 of 16 answered, 6 of 6 unanswerable declined
I'm travelling for two months. Can I freeze my account? -> No, you cannot freeze your account. The handbook only allows pausing memberships for one to three months per calendar year, not for two consecutive months while traveling.  **Section used:** [Pausing]
When can I help fix bikes? -> You can help fix bikes during repair nights, which are held on the first and third Wednesday of each month from 6 to 9 pm at the Dock 4 workshop. (Section: [Repair nights])
```

The score says 16 of 16, but read the first answer. It says "No" when two months falls inside the one to three months allowed, so it's wrong even though it contains the expected phrase. The real result is 15 of 16. A phrase check is a fast first pass, and you still need to read answers (or grade them more carefully) before trusting the number.

Turning on [thinking](https://www.pythoncharts.com/ai/run-local-llms-ollama-python/) with the looser instructions fixes that one, at the cost of a much slower reply:

```python
print(ask("I'm travelling for two months. Can I freeze my account?", LOOSER, think=True))
```

```text
Yes, you can pause your account for up to three months per calendar year ([Pausing]).
```

## When Do You Need More Than This?

| Situation | What to use |
|---|---|
| A few short documents that fit in the context window | Put all of them in the prompt and skip retrieval |
| Up to many thousands of chunks, changing rarely | This approach: vectors in a NumPy array, saved with `np.save` |
| Large or frequently updated collections, filtering by metadata | A vector database such as Chroma, Qdrant, or pgvector |
| Questions with exact codes, names, or IDs | Add keyword search (such as BM25) alongside embeddings |
| The model needs a new tone or output format, not new facts | Better instructions first, then fine-tuning |

## Practical Tips

- Keep the section title in each chunk. It often carries the topic that the body text assumes.
- Use the embedding model's prefixes, one for documents and another for queries, and embed both with the same model.
- Re-embed everything when you change the model or the chunking.
- Save each question with its retrieved chunks. Most debugging starts there.
- Treat retrieved text as untrusted input. A document can contain instructions, so don't let this model call tools that change things.
- To see how your chunks relate to each other, [plot the embeddings with UMAP](https://www.pythoncharts.com/ai/visualize-text-embeddings-umap-plotly/).

## Similar Topics

- [Run Local LLMs in Python with Ollama](https://www.pythoncharts.com/ai/run-local-llms-ollama-python/)
- [Visualize Text Embeddings in Python with UMAP and Plotly](https://www.pythoncharts.com/ai/visualize-text-embeddings-umap-plotly/)
- [Let an LLM Generate Charts from Your DataFrame](https://www.pythoncharts.com/ai/llm-generate-charts-from-dataframe/)
