How to build RAG with Python, step by step
What RAG is and how to build a system that answers from your documents: chunking, embeddings, retrieval, cited answers and testing.

What is RAG?
RAG (retrieval-augmented generation) makes a model answer from your documents: first find the passages that match the question, then give them to the model to write the answer from.
It is an open-book exam: the student doesn't memorise everything, but finds the right page and answers.
When you need it
- Answers from your company files, lessons or policies.
- Information that keeps changing.
- A source next to every answer.
The six steps
- Collect documents, each with a source name.
- Chunk them into small overlapping pieces.
- Embed each chunk (numbers that represent meaning) and store them.
- Retrieve the chunks closest to the question.
- Answer from those chunks only, naming the source.
- Test retrieval and answers.
Install
pip install -U langchain-core langchain-ollama langchain-text-splitters numpy
ollama pull qwen2.5:3b
ollama pull embeddinggemma
The full code
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_ollama import ChatOllama, OllamaEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
# 1) your documents (read them from files in a real project)
docs = [
Document(page_content="Refunds are accepted within 14 days of purchase with a receipt.", metadata={"source": "refunds.md"}),
Document(page_content="Standard shipping takes 3 to 5 working days. Express shipping takes 1 day.", metadata={"source": "shipping.md"}),
Document(page_content="Support is open Sunday to Thursday, from 9 AM to 6 PM.", metadata={"source": "support.md"}),
]
# 2) split into chunks, 3) embed them and store the vectors
chunks = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=80).split_documents(docs)
store = InMemoryVectorStore(OllamaEmbeddings(model="embeddinggemma"))
store.add_documents(chunks)
model = ChatOllama(model="qwen2.5:3b", temperature=0)
def ask(question: str) -> str:
# 4) retrieve the closest chunks
hits = store.similarity_search(question, k=2)
context = "\n\n".join(f"[{d.metadata['source']}]\n{d.page_content}" for d in hits)
# 5) answer from those chunks only
messages = [
("system", "Answer in one sentence using only the context, then write the source file name in brackets. If the answer is not there, say you don't know."),
("human", f"Context:\n{context}\n\nQuestion: {question}"),
]
return model.invoke(messages).content
print(ask("How many days do I have to get a refund?"))
# 6) test retrieval before judging the answers
tests = [
("Can I return an item?", "refunds.md"),
("When will my parcel arrive?", "shipping.md"),
("What are your working hours?", "support.md"),
]
found = sum(source in [d.metadata["source"] for d in store.similarity_search(q, k=2)] for q, source in tests)
print(f"Retrieval: {found}/{len(tests)} questions found the right file")
The output we got:
You have 14 days to get a refund [refunds.md].
Retrieval: 3/3 questions found the right file
Asked for something that isn't there (the CEO's phone number), it answered: I don't know.
How to improve it
| Problem | Try |
|---|---|
| It misses the right passage | Another chunk size, or a better embedding model for your language |
| Right passage, wrong answer | A clearer prompt or a stronger model |
| It's slow | Fewer, shorter chunks in the context, and time each step |
| It invents answers | Tell it to say "I don't know", and test that |
From my work: I cut a RAG service's response time from 25 seconds to 4-5 by re-engineering chunking, embeddings, prompts and generation. Measure first, then change one step at a time.
Before production
- Replace
InMemoryVectorStorewith a vector database such as Qdrant or FAISS. - Never return passages from files a user isn't allowed to see.
- Build a set of real test questions and grow it over time.
Next guide
LangGraph: agents with memory and human approval
Code tested on 30 November 2026 with Python 3.10, LangChain 1.4 and LangGraph 1.2.