Ollama RAG: local private knowledge base Q&A
In this chapter we combine the embedding, retrieval, and generation capabilities learned earlier into a truly usable application: feed your documents to the local model, let it answer questions based only on your materials, and cite the sources.
The complete code is under 100 lines, with zero external vector database dependencies—copy and run.
Requirements breakdown and technology selection
First clarify the problem: the large model doesn't know the materials on your hard drive; asking directly only yields fabricated answers. The idea of RAG (Retrieval-Augmented Generation) is an "open-book exam"—first retrieve relevant passages from the materials, stuff them into the prompt, and let the model answer accordingly.
Technology selection follows the "minimal dependencies" principle:
| Stage | Selection | Reason |
|---|---|---|
| Embedding model | embeddinggemma | Small size, fast locally; alternative: qwen3-embedding |
| Generative models | qwen3.5:4b | Good at Chinese, runs on 16GB memory |
| Vector storage | Python list + cosine similarity | Zero dependencies, clear for teaching; for large volumes switch to professional libraries like Chroma |
| Document format | txt / md | Plain text is enough to explain the principles; see the extension at the end for PDF |
Two models need to be pulled:
ollama pull embeddinggemma
ollama pull qwen3.5:4b
EmbeddingGemma is a lightweight multilingual text embedding (Embedding) model open-sourced by Google, specifically for converting text into vectors. It's very suitable for offline deployment on local devices, and Ollama has adapted and wrapped it so it can be pulled and used directly.
Step 1: document parsing and chunking
The model's context is limited and a whole document won't fit, so it needs to be cut into small chunks. The chunking strategy uses the simplest "fixed length + overlap": 300 characters per chunk, with 50 characters of overlap between adjacent chunks to avoid cutting key sentences.
Example
File path: rag.py
import
os
def
load_chunks
(
folder
,
size
=
300
,
overlap
=
50
)
:
"""Read all txt/md files in the folder and cut them into chunks with source markers"""
chunks
=
[
]
for
name
in
sorted
(
os
.
listdir
(
folder
)
)
:
if
not
name.
endswith
(
(
'.txt'
,
'.md'
)
)
:
continue
path
=
os
.
path
.
join
(
folder
,
name
)
text
=
open
(
path
,
encoding
=
'utf-8'
)
.
read
(
)
.
strip
(
)
Sliding window chunking: step = size - overlap
step
=
size - overlap
for
i
in
range
(
0
,
len
(
text
)
,
step
)
:
piece
=
text
[
i:i + size
]
.
strip
(
)
if
len
(
piece
)
20
:
Filter out fragments that are too short
chunks.
append
(
{
'file'
: name
,
'text'
: piece
}
)
return
chunks
Step 2: vectorization and retrieval
Convert all chunks and the user question into vectors, and use cosine similarity to find the top-k chunks most relevant to the question.
Example
import
ollama
EMBED_MODEL
=
'embeddinggemma'
def
embed
(
texts
)
:
"""Batch generate vectors (input list, output vector list)"""
result
=
ollama.
embed
(
model
=
EMBED_MODEL
,
input
=
texts
)
return
result
[
'embeddings'
]
def
cosine
(
a
,
b
)
:
"""Cosine similarity: the closer to 1, the more similar"""
dot
=
sum
(
x * y
for
x
,
y
in
zip
(
a
,
b
)
)
na
=
sum
(
x * x
for
x
in
a
)
**
0.5
nb
=
sum
(
x * x
for
x
in
b
)
**
0.5
return
dot /
(
na * nb
)
def
search
(
question
,
chunks
,
vectors
,
top_k
=
3
)
:
"""Retrieval: return the k most relevant chunks and their similarity"""
q_vec
=
embed
(
[
question
]
)
[
0
]
scored
=
[
(
cosine
(
q_vec
,
v
)
,
c
)
for
v
,
c
in
zip
(
vectors
,
chunks
)
]
scored.
sort
(
key
=
lambda
x: -x
[
0
]
)
return
scored
[
:top_k
]
embeddinggemma outputs L2-normalized vectors; here the full cosine formula is kept to make the principle clear; switching to dot product gives the same result.
Step 3: assemble the prompt and generate a cited answer
Write the retrieved chunks together with their source numbers into the prompt, explicitly requiring the model to "answer based only on the materials" and to mark citations.
Example
from
ollama
import
chat
GEN_MODEL
=
'qwen3.5:4b'
def
answer
(
question
,
chunks
,
vectors
)
:
hits
=
search
(
question
,
chunks
,
vectors
,
top_k
=
3
)
Concatenate the chunks and source numbers into the context
context
=
'\n\n'
.
join
(
f
'[Material {idx}] (from {c["file"]})\n{c["text"]}'
for
idx
,
(
score
,
c
)
in
enumerate
(
hits
,
1
)
)
prompt
=
f
'''Answer questions based only on the following materials, and mark the material numbers used.
If the materials are insufficient to answer, simply say you don't know.
Materials:
{context}
Question: {question}'''
response
=
chat
(
model
=
GEN_MODEL
,
messages
=
[
{
'role'
:
'user'
,
'content'
: prompt
}
]
,
options
=
{
'temperature'
:
0.2
}
,
Low temperature to reduce improvisation
)
(
response.
message
.
content
)
(
'\nReference Source: '
)
for
idx
,
(
score
,
c
)
in
enumerate
(
hits
,
1
)
:
(
f
' [Material {idx}] {c["file"]} (similarity {score:.3f})'
)
Complete run: main program entry
Example
Append to the end of rag.py
if
name
==
'main'
:
folder
=
'docs'
Put your txt/md documents into the docs folder
chunks
=
load_chunks
(
folder
)
Offline indexing: vectorize all chunks at once
(
f
'Indexing {len(chunks)} chunks...'
)
vectors
=
embed
(
[
c
[
'text'
]
for
c
in
chunks
]
)
(
'Indexing complete.\n'
)
Online Q&A loop
while
True
:
q
=
input
(
'Question (type exit to quit): '
)
.
strip
(
)
if
q.
lower
(
)
==
'exit'
:
break
if
q:
answer
(
q
,
chunks
,
vectors
)
(
)
Prepare materials and run:
mkdir docs
cp RUNOOB-python-notes.md docs/
python rag.py
Output:
$ python rag.py
正在索引 42 个片段...
索引完成。
问题(exit 退出):Python 的切片是什么?
Python 切片是用 [start:stop:step] 从序列截取子序列的语法 [资料1]。
例如 s[1:4] 取索引 1 到 3 的字符 [资料2]。
参考Source:
[资料1] RUNOOB-python-notes.md(相似度 0.712)
[资料2] RUNOOB-python-notes.md(相似度 0.668)
Note the source markers at the end of the answer: every sentence can be traced to a specific file in your docs directory—this is the core value of RAG compared to "asking the model directly".
Effect tuning and common issues
When RAG performs poorly, 80% of the time the problem is in retrieval rather than generation. Tuning levers sorted by impact:
| Lever | Default value | Adjustment direction |
|---|---|---|
| Chunk size size | 300 characters | If answers are too fragmented, increase it; too large hurts retrieval accuracy—empirical range 200~500 |
| Overlap overlap | 50 characters | Increase when sentences are frequently cut off |
| Number of retrievals top_k | 3 | Increase when materials are dense, but it uses more context |
| Similarity threshold | Not enabled | Filter out chunks with too-low similarity to reduce irrelevant noise |
| Generation temperature | 0.2 | Keep it low; a knowledge base doesn't need creativity |
Quick reference for frequent issues:
| Symptom | Reason | Countermeasure |
|---|---|---|
| Answer unrelated to the materials | Retrieval missed | Check whether chunks are too small/large, and confirm the question language matches the materials |
| Model still fabricates answers | Insufficient prompt constraints | Strengthen the "based only on materials" wording; when nothing is retrieved, answer "don't know" directly |
| Indexing is very slow | Too many chunks embedded one by one | Use batch embed; for large document volumes switch to a professional vector database and incremental indexing |
| Answers get worse for long documents | Key information is chopped up | Chunk by semantic boundaries such as headings/paragraphs instead of pure fixed length |
Production roadmap: when document volume reaches tens of thousands or PDF parsing is needed, replace the "list vector store" with a professional vector database like Chroma (providing persistence and efficient nearest-neighbor search), use pypdf to extract PDF text, and leave the rest of the code skeleton unchanged—this is exactly the point of decoupling each component in this article.