A large language model (LLM) does not know your internal documents, and they do not all fit into a prompt. Retrieval-augmented generation (RAG) solves this by retrieving the relevant passages first and sending only those along with the question. This tutorial shows how to build a local RAG with Python from scratch: no cloud API, no LangChain and no vector database, just the Python standard library and two llama serve instances. The whole local RAG pipeline is chunking, vector embeddings, similarity search and one request to the LLM, all running on your local machine with open-source models. I tested it with llama.cpp 1.1.0-dev (build 12826), the embedding model bge-m3 (Q8_0) and Qwen3.5-4B (Q4_K_M), both downloaded from Hugging Face, and Python 3.13.5 on a machine with 8 CPU cores and no GPU. The documents are five tutorials from this site. All outputs are from 2 December 2026.
How RAG works and how a local system is built
The RAG architecture has two phases. When indexing, you split the documents into passages (chunks) and have an embedding model compute a vector for each one. When a question comes in (the query), you compute its vector, retrieve the most similar chunks, and send these relevant chunks to the LLM together with the question. The LLM sees the retrieved context instead of the whole collection. The idea comes from the paper Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. For the concept and for when this approach makes sense, see our article on how to build your own RAG system. This tutorial is about the implementation with local language models, step by step and with measured results. The server options we use are listed on GitHub in the README of the llama.cpp server.
You need two models, which is typical for a RAG system built from scratch: one for embeddings and one for answers. You start both with llama serve, as described in the tutorial Run a Local LLM with llama.cpp Server. An embedding model is not a chat model, and it has to place relevant texts close together for the search to work. For a text it returns a vector of fixed length, and texts with a similar meaning end up close to each other.
Start both servers: embeddings and chat
For the embeddings I used bge-m3. It is multilingual, which matters for German documents, and it is available as a GGUF with Q8_0 quantization. The answers come from Qwen3.5-4B on a second port, with --reasoning off so the text lands in the content field:
llama serve -hf ggml-org/bge-m3-Q8_0-GGUF --embeddings -ub 2048 -b 2048 --port 9941 &
llama serve -hf ggml-org/Qwen3.5-4B-GGUF --no-mmproj --reasoning off -c 8192 --port 9931 &
I hit two pitfalls myself. First, my shell still had the variable LLAMA_API_KEY from an earlier test. The server picked it up automatically, and every request ended with {"error":{"message":"Invalid API Key","type":"authentication_error","code":401}}. If you get a 401, check with env | grep LLAMA. Second, without -ub 2048 -b 2048 the embedding server limits the input to 512 tokens. A longer chunk ended with HTTP 500, and the server log said input (556 tokens) is too large to process. increase the physical batch size (current batch size: 512). With the two parameters the server handles larger chunks. Whether you need them depends on how long your chunks get.
A quick test that the embedding server responds:
curl -s localhost:9941/v1/embeddings -H 'Content-Type: application/json' \
-d '{"input": ["Hello world"], "model": "embed"}'
The response contains a vector of 1024 numbers per text. I checked the length: the vectors are normalized to 1.0, so a plain dot product is enough later to compute the cosine similarity.
Local RAG with Python: the complete script
The documents are Markdown files in the folder docs. The script splits them at the headings, caps the chunks at a character limit, indexes them and answers questions. It needs only the standard library:
import json, pathlib, sys, time, urllib.request
EMBED_URL = "http://127.0.0.1:9941/v1/embeddings"
CHAT_URL = "http://127.0.0.1:9931/v1/chat/completions"
DOCS = pathlib.Path("docs")
INDEX = pathlib.Path("index.json")
def post(url, payload):
req = urllib.request.Request(
url, json.dumps(payload).encode(), {"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=300) as resp:
return json.load(resp)
def chunk_file(path, max_chars=2000):
heading, buf, chunks = path.stem, [], []
def flush():
text = "\n\n".join(buf).strip()
if text:
chunks.append({"source": path.name, "heading": heading, "text": text})
buf.clear()
for block in path.read_text().split("\n\n"):
if block.startswith("## "):
flush()
heading = block[3:].strip()
continue
if sum(len(b) for b in buf) + len(block) > max_chars:
flush()
buf.append(block)
flush()
return chunks
def embed(texts, batch=16):
vectors = []
for i in range(0, len(texts), batch):
data = post(EMBED_URL, {"input": texts[i : i + batch], "model": "embed"})["data"]
vectors += [d["embedding"] for d in sorted(data, key=lambda d: d["index"])]
return vectors
def build_index():
chunks = [c for p in sorted(DOCS.glob("*.md")) for c in chunk_file(p)]
start = time.time()
vectors = embed([f"{c['heading']}\n{c['text']}" for c in chunks])
for c, v in zip(chunks, vectors):
c["vector"] = v
INDEX.write_text(json.dumps(chunks))
print(f"{len(chunks)} chunks embedded in {time.time() - start:.1f} s")
def search(question, k=4):
chunks = json.loads(INDEX.read_text())
q = embed([question])[0]
scored = [(sum(a * b for a, b in zip(q, c["vector"])), c) for c in chunks]
return sorted(scored, key=lambda s: s[0], reverse=True)[:k]
def ask(question, k=3, min_score=0.45):
hits = [h for h in search(question, k) if h[0] >= min_score]
if not hits:
return "I could not find anything about that in the documents.", []
context = "\n\n".join(f"[{i}] ({c['source']}) {c['text']}" for i, (_, c) in enumerate(hits, 1))
messages = [
{"role": "system", "content": (
"Answer only from the numbered context. Cite the numbers like [1]. "
"If the context does not contain the answer, say so.")},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
]
reply = post(CHAT_URL, {"model": "local", "messages": messages, "temperature": 0})
return reply["choices"][0]["message"]["content"], hits
if __name__ == "__main__":
if sys.argv[1] == "index":
build_index()
else:
answer, hits = ask(" ".join(sys.argv[1:]))
print(answer)
for score, c in hits:
print(f" [{score:.2f}] {c['source']} / {c['heading']}")
Here is how it works. chunk_file splits a file at blank lines, starts a new chunk at every ## heading and fills a chunk until the character limit is reached. Paragraphs and code blocks are never cut in the middle. The heading is put in front of the text before embedding, because it often holds the most important keyword. search computes the dot product of the query with all chunks and returns the best k. For five documents with about 10,000 words in total, this similarity search is fast enough without a vector database. An index such as the one in ChromaDB or another vector store only pays off with very many chunks.
Indexing the five tutorials took this long on my CPU:
python3 docs_qa.py index
# 61 chunks embedded in 16.0 s
Now a query whose answer is in one of the documents (example output; the model’s wording changes from run to run):
python3 docs_qa.py Which uv option stops source distributions from being built?
# The `no-build` option stops source distributions from being built. It can be set globally in
# `pyproject.toml` under `[tool.uv]` or used temporarily with the `--no-build` flag during installation.
# [0.59] python-uv.md / Step 4: do not build source packages
# [0.50] python-uv.md / Step 3: delay new releases with exclude-newer
# [0.48] python-uv.md / All of it as a CI recipe
The answer arrived after roughly nine seconds. The first source is exactly the relevant chunk that holds the answer. The source line with file, heading and score is the real strength of the method: you can check every statement.
What ends up in the prompt and what it costs
The function ask builds a numbered context from the hits: [1] (python-uv.md) text …. The model is asked to cite the numbers in its answer so you can map them to the sources. With three chunks of up to 2000 characters each, the prompt was about 950 tokens long in one test and the answer 53 tokens. That is why the method is practical with a small model on a CPU at all: the model reads a few chunks instead of all five documents. The timings on my 8 cores without a GPU: indexing 61 chunks took 16 seconds, embedding a query plus the search over all chunks about 0.1 to 0.2 seconds (measured on the question without a hit, where the LLM is not called), and the LLM’s answer five to thirteen seconds.
To use your own documents, put Markdown files into docs and run python3 docs_qa.py index again. The script always re-embeds all chunks. For a larger collection that changes, you would index only changed files; I left that out on purpose.
When a framework or a vector database makes sense
I deliberately avoided LangChain or LlamaIndex and a vector database so that every line stays easy to follow. A framework like LangChain ships ready-made building blocks for loaders, chunking and retrievers. Vector databases such as ChromaDB or Qdrant store the vectors persistently, manage them in collections and stay fast with hundreds of thousands of chunks. I did not test any of them here, so I cannot say anything about their speed or setup. If you prefer to use Ollama over llama.cpp to run local LLMs and other large language models, you would change only the two URLs and the model names in the script; whether another server offers the same interface in the same way is for you to check. PDFs are a topic of their own as well, because the text has to be extracted before chunking.
Questions without an answer in the documents
A typical problem: the model answers even when nothing relevant was found. Two measures help, and both are in the script. The system prompt demands answering only from the context and saying so otherwise. In addition, ask discards all hits below a minimum score, and without hits the LLM is not asked at all. I did not guess that value but measured it. In my five documents, questions with an answer scored between 0.48 and 0.72, while unrelated questions (about sourdough, the weather or capital cities) scored at most 0.39. I chose 0.45:
python3 docs_qa.py How do I bake sourdough bread?
# I could not find anything about that in the documents.
The answer came back in 0.23 seconds because the local LLM was not called. As a counter-test I set the minimum score to 0. The LLM then said for the question about the capital of France that the context does not contain the answer. In this test the system prompt alone was enough. I would not rely on that, though, because the threshold is valid only for this embedding model and this document set. With other documents you have to measure it again.
How big should the chunks be? A measurement
Chunk size affects retrieval quality more than I expected. I wrote twelve questions, each with one keyword that must appear in the right passage, for example --reasoning off for the question about the thinking switch. A question counts as a hit if the keyword is in one of the top chunks. I varied the limit max_chars from 300 to 4000 characters:
| max_chars | Chunks | Hit at rank 1 | Hit in the top 3 |
|---|---|---|---|
| 300 | 186 | 7 of 12 | 8 of 12 |
| 600 | 134 | 5 of 12 | 8 of 12 |
| 1000 | 94 | 8 of 12 | 11 of 12 |
| 2000 | 61 | 11 of 12 | 12 of 12 |
| 4000 | 57 | 11 of 12 | 12 of 12 |
With 2000 characters, the top 3 found the right passage for every question. Smaller chunks did worse, presumably because they separate a term from its explanation. Between 2000 and 4000 there was no difference, because my script does not split paragraphs and code blocks, so the limit hardly takes effect any more. This holds only for these twelve questions and these five documents. Twelve questions is a small sample, and the top-3 value for 600 characters differed by one question in a first run with other server settings. Measure with your own questions before you fix a size. The method is the same: questions, expected keyword, hit rate for different parameters.
German questions against English documents
bge-m3 is multilingual, so I tested whether that holds up in search. The same twelve questions, once in German against the English documents and once in English against the German documents, each with 2000 characters per chunk:
| Questions | Documents | Hit at rank 1 | Hit in the top 3 |
|---|---|---|---|
| German | German | 10 of 12 | 12 of 12 |
| English | English | 11 of 12 | 12 of 12 |
| German | English | 9 of 12 | 11 of 12 |
| English | German | 11 of 12 | 11 of 12 |
Cross-language search works, but it is slightly worse than within one language. If your documents and questions share a language, use that. If not, a multilingual embedding model like this one is a workable solution, but you should measure with your own questions. I did not test the answer side across languages; the LLM would have to understand the language of the sources as well.
What this setup cannot do
The local LLM with document search here is a learning example, not a production system. It reads only Markdown. For PDF documents you need a separate step that extracts text, and that can go wrong with tables and columns. It stores the index as a single JSON file and reloads it for every question. It only finds passages that resemble the question. If someone asks something that follows only from two chunks together, the answer depends on whether both are among the top 3. And it does not guarantee that the documents themselves are trustworthy: if a document contains an instruction aimed at the model, it ends up in the prompt. For anything delivered to users you also need per-document access rights and a check of the sources.
If you later want to connect the model with tools, the tutorial Build an MCP Server in Python shows one way to offer the document search as a tool for AI assistants. The local models in this tutorial also fit the GPU-free local LLM setup measured in the llama.cpp tutorial.



