This is the final part of the Local AI Model Deployment series. The previous three parts produced an inference service that is reachable from the internet and wired into your daily tools. This part gives it a knowledge base: answers grounded in your own documents, with citations.
Ingestion and retrieval run on the same machine. After dependencies and models are installed, retrieval uses no external embedding API. The article covers chunking plus vector and lexical retrieval. Its code is a set of core excerpts with several missing connections; corrections are placed beside those excerpts.
Local LLM deployment series (4 parts): ① Model and engine → ② Exposing it → ③ Clients → ④ Knowledge base RAG. This is part 4.
Architecture
Ingest: document → split by heading → embed → sqlite-vec + FTS5
Retrieve: query → vector recall + lexical recall → RRF fusion
→ top-k into a system message → model
| Component | Choice | Reason |
|---|---|---|
| Embedding | bge-m3 FP16 (1024 dims) | Multilingual, 8K input; runs on CPU, uses no VRAM |
| Vector store | sqlite-vec | Single file, trivial to back up and move, one fewer daemon |
| Lexical | SQLite FTS5 + trigram | Built in, no extra service |
| Fusion | RRF | Combines ranks, so no normalization between incomparable scores |
Why the embedding model runs on CPU: the generation model already occupies most of the VRAM, and embedding is far lighter — a query embeds a single sentence, which you will never notice, and slower batch ingestion does not matter. Measured, bge-m3 FP16 on CPU uses 1.6 GB of RAM and zero VRAM.
Step 1: Start an embedding service
This deployment uses a second llama.cpp instance for bge-m3 while the generation instance loads Gemma 4. That choice separates two different models. Whether another engine or model can expose both generation and embeddings depends on its version and endpoints.
curl -L --retry 20 -C - \
-o /opt/llm/models/bge-m3-FP16.gguf \
"https://modelscope.cn/models/gpustack/bge-m3-GGUF/resolve/master/bge-m3-FP16.gguf"
Memory allowed FP16 as the embedding baseline here. Measure the retrieval effect of quantization using the chosen model, format and query set; generation quality does not determine that effect. The original download URL is retained. For reproduction, pin its repository revision and verify file size and checksum.
[Unit]
Description=bge-m3 embedding service (knowledge base, CPU)
After=network-online.target
[Service]
Type=exec
User=youruser
Environment=LD_LIBRARY_PATH=/opt/llama.cpp
ExecStart=/opt/llama.cpp/llama-server \
--model /opt/llm/models/bge-m3-FP16.gguf \
--alias bge-m3 \
--embeddings \
--pooling cls \
--host 127.0.0.1 --port 8001 \
--ctx-size 8192 \
--batch-size 8192 --ubatch-size 8192 \
--n-gpu-layers 0 \
--threads 8 \
--no-webui \
--api-key sk-your-key
Restart=on-failure
[Install]
WantedBy=multi-user.target
Three flags that matter:
--n-gpu-layers 0leaves model layers off the GPU. This run recorded 1.6 GB of CPU RAM with no VRAM increase. To disable device offload, the checked b10216 also supports--device none --no-op-offload; confirm allocations in its startup log.--ubatch-size 8192is the setting used for this bge-m3 instance. The recorded physical batch of 512 rejectedinput (573 tokens) is too large to process. The model’s 8192 limit includes special tokens; also check memory requirements for the selected version.--pooling clsmatches bge-m3’s dense embedding path. Other bge models and sparse or multi-vector output use their own implementations.
Verify:
curl -s 127.0.0.1:8001/v1/embeddings \
-H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
-d '{"model":"bge-m3","input":["test text"]}' \
| python3 -c "
import json,sys
v = json.load(sys.stdin)['data'][0]['embedding']
v = v[0] if v and isinstance(v[0], list) else v
print(f'{len(v)} dimensions')"
Expect 1024 dimensions. Note that some versions wrap a single result in an extra list ([[...]]) — handle that in code.
Step 2: Create the store
pip install sqlite-vec
import sqlite3, sqlite_vec
SCHEMA = """
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY, name TEXT NOT NULL,
bytes INTEGER NOT NULL DEFAULT 0,
n_chunks INTEGER NOT NULL DEFAULT 0,
added_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY,
doc_id INTEGER NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
ordinal INTEGER NOT NULL, heading TEXT, text TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_chunks_doc ON chunks(doc_id);
-- trigram is what makes CJK work; the default unicode61 turns a whole
-- sentence into a single token
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
text, content='chunks', content_rowid='id', tokenize='trigram'
);
"""
def connect(path):
con = sqlite3.connect(path, timeout=30)
con.row_factory = sqlite3.Row
con.execute("PRAGMA journal_mode=WAL")
con.execute("PRAGMA foreign_keys=ON")
con.enable_load_extension(True)
sqlite_vec.load(con)
con.enable_load_extension(False)
return con
with connect("kb.db") as con:
con.executescript(SCHEMA)
con.execute(
"CREATE VIRTUAL TABLE IF NOT EXISTS vec_chunks USING vec0("
"chunk_id INTEGER PRIMARY KEY, embedding float[1024])")
tokenize='trigram' supplies substring retrieval here. Default unicode61 does not segment continuous Chinese into words, but whole tokens still match; it does not make every CJK query fail. Other tokenizers are also possible. Trigram MATCH requires at least 3 Unicode characters. The schema uses external-content FTS: writing chunks does not update its index automatically. Maintain FTS and vector rows in the same transaction on insert/update/delete, and rebuild FTS for pre-existing chunks.
Step 3: Chunk the documents
The order of operations here determines retrieval quality.
The intuitive approach is “split recursively by character count, then tag each chunk with a heading”. That fails twice: small documents collapse into a single chunk, destroying granularity; and when a chunk spans several sections, content from the first section gets labelled with the last section’s heading — citations that point at the wrong place, and hard to notice.
The correct order is two-level: split at headings first (semantic boundaries), then subdivide oversized sections.
import re
CHUNK_TARGET = 1100 # target characters per chunk
CHUNK_OVERLAP = 150 # overlap so answers are not cut at a boundary
MAX_CHUNK = 2000
_HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$", re.M)
_FENCE_RE = re.compile(r"^```.*?^```", re.M | re.S)
_SEPARATORS = ["\n# ", "\n## ", "\n### ", "\n\n", "\n",
". ", "! ", "? ", ", ", " "]
def _split_sections(text):
"""Split into (breadcrumb heading, body) pairs at markdown headings."""
# Exclude fenced code blocks — a shell `# comment` is textually
# identical to a heading
spans = [(m.start(), m.end()) for m in _FENCE_RE.finditer(text)]
marks = [m for m in _HEADING_RE.finditer(text)
if not any(a <= m.start() < b for a, b in spans)]
if not marks:
return [(None, text)]
sections, trail = [], {}
if marks[0].start() > 0:
lead = text[:marks[0].start()].strip()
if lead:
sections.append((None, lead))
for i, m in enumerate(marks):
level, title = len(m.group(1)), m.group(2).strip()
trail = {k: v for k, v in trail.items() if k < level}
trail[level] = title
end = marks[i + 1].start() if i + 1 < len(marks) else len(text)
body = text[m.start():end].strip()
content = body[m.end() - m.start():].strip()
# A heading with no body (an H1 immediately followed by H2s) should
# not become its own chunk — those tiny fragments act as noise and
# can outrank the passage that actually answers the question
if len(content) < 20:
continue
sections.append((" › ".join(trail[k] for k in sorted(trail)), body))
return sections
The original regex handles the unindented backtick-fence example. CommonMark also permits tilde fences, indentation and varying fence lengths; a general Markdown importer should use parsed blocks. The len(content) < 20 rule drops genuine short answers as well as empty headings. If a short section may contain a key value, skip only blank content and retain the rest.
Chunking also needs two details:
- Fenced code blocks must be excluded. A
#comment in a shell snippet is indistinguishable from a heading. Without this, a citation breadcrumb readsREADME.md › 3. Remember to remove this afterwards...— which was a line inside a “`bash block. - Skip empty sections. A heading-only section produces a fragment of a dozen characters that behaves as pure noise. In testing such a fragment ranked first, pushing the correct passage out of the results.
Then subdivide within each section, with overlap:
def chunk_text(text):
text = text.replace("\r\n", "\n").strip()
chunks = []
for heading, body in _split_sections(text):
parts = (_split_recursive(body, CHUNK_TARGET, _SEPARATORS)
if len(body) > CHUNK_TARGET else [body])
for i, part in enumerate(parts):
piece = part.strip()
if not piece:
continue
# Overlap within a section only. Overlapping across sections
# would mix in unrelated content and pollute citations.
if i > 0 and CHUNK_OVERLAP:
tail = parts[i - 1][-CHUNK_OVERLAP:].strip()
if tail:
piece = tail + "\n" + piece
# Re-attach the heading to continuation chunks, or the second
# chunk onward loses its context
if heading and not piece.lstrip().startswith("#"):
piece = f"{heading}\n{piece}"
chunks.append({"ordinal": len(chunks),
"text": piece[:MAX_CHUNK], "heading": heading})
return chunks
The original excerpt omits _split_recursive; the correction below provides a bounded character splitter. The original piece[:MAX_CHUNK] can still discard the end of a long heading, overlap or body. Verify that no chunk is truncated, or budget the heading and overlap before splitting again. Character limits must also be checked against the embedding model’s token count.
Step 4: Hybrid retrieval
Hybrid retrieval handles both semantic questions and identifiers. Pure vector search often fails on technical documentation.
The two methods have complementary blind spots:
- For this corpus, vector retrieval found passages for “How do I stop the model from reasoning?” despite different wording in the source. Lexical search can also cover these expressions with synonyms or query rewriting.
reasoning_budget, a specific.gguffilename, a model number — embeddings are notoriously insensitive to identifiers. In testing, vector search could not rank the correct passage; lexical search matched it exactly.
So run both and fuse with Reciprocal Rank Fusion:
import json
def search(con, query, embed_fn, top_k=5, pool=30):
qvec = embed_fn([query])[0]
vec_hits = [r["chunk_id"] for r in con.execute(
"SELECT chunk_id FROM vec_chunks "
"WHERE embedding MATCH ? AND k = ? ORDER BY distance",
(json.dumps(qvec), pool))]
fts_hits = []
for expr in _fts_queries(query):
try:
fts_hits = [r["rowid"] for r in con.execute(
"SELECT rowid FROM chunks_fts WHERE chunks_fts MATCH ? "
"ORDER BY rank LIMIT ?", (expr, pool))]
except sqlite3.OperationalError:
continue # FTS5 rejected this form; try the next
if fts_hits:
break
# RRF: fuse by rank, not score, so no normalization is needed between
# two incomparable scales
K, score = 60, {}
for rank, cid in enumerate(vec_hits):
score[cid] = score.get(cid, 0.0) + 1.0 / (K + rank + 1)
for rank, cid in enumerate(fts_hits):
score[cid] = score.get(cid, 0.0) + 1.0 / (K + rank + 1)
return sorted(score.items(), key=lambda kv: -kv[1])[:top_k]
def _fts_queries(query):
"""Progressively looser FTS5 expressions, tried until one hits.
Under trigram, phrase matching is substring matching, so a
natural-language question matches nothing — the entire lexical arm
contributes zero. Splitting into terms and OR-ing them is what lets
identifiers do their job.
"""
q = query.replace('"', " ").strip()
if not q:
return []
out = [f'"{q}"'] # 1. whole phrase
terms = [t for t in re.split(r"[\s,.?!:;()\[\]]+", q)
if len(t) >= 3] # trigram needs 3+ chars
if terms:
out.append(" OR ".join(f'"{t}"' for t in terms[:8]))
return out
This RRF combines the two ranks with equal weight, avoiding direct addition of incompatible score scales. The vec0 definition above uses default L2 distance, not a declared cosine metric. Set the metric and check normalization explicitly if cosine is intended. K=60 was an empirical choice in the original paper; the candidate pool, retrieval weights and K can still be validated on this corpus.
The original return types do not connect. search returns (chunk_id, score), while build_context expects doc_name, heading and text. Passing one directly to the other raises an error and triggers ordinary-chat fallback. The correction below fetches those fields by ID first. These helpers still need integration with the application and its ingestion path.
Step 5: Build the context
def build_context(hits, max_chars=6000):
"""Assemble retrieved chunks into model context plus a citation list.
Deliberately capped around 6000 characters: filling a small model's
32K window dilutes attention. Three to five precise passages beat a
pile of loosely related ones.
"""
blocks, cites, used = [], [], 0
for i, h in enumerate(hits, 1):
label = h["doc_name"] + (f" › {h['heading']}" if h.get("heading") else "")
block = f"[{i}] Source: {label}\n{h['text']}"
if used + len(block) > max_chars:
break
blocks.append(block); used += len(block)
cites.append({"n": i, "doc_name": h["doc_name"],
"heading": h.get("heading")})
return "\n\n---\n\n".join(blocks), cites
RAG_PROMPT = (
"Below are passages retrieved from a knowledge base. Base your answer "
"on them and cite the number of any passage you use, e.g. [1].\n"
"If the passages do not contain the answer, say so plainly rather than "
"inventing one.\n\n"
)
The last sentence instructs the model to report absent evidence. Measure its effect with answerable, unanswerable and conflicting-source queries, checking each citation against its source. The original 6000-character budget also omits separators between blocks and is not a token limit.
Step 6: Wrap it as an OpenAI-compatible endpoint
This chat-completions route excerpt reuses the earlier authenticated forwarding layer. It depends on application objects such as con, embed_fn and forward and is not a standalone service. Check the client’s supported paths and response fields; compatibility with every /v1 client does not follow from this excerpt.
@app.post("/rag/v1/chat/completions")
async def rag_chat(request: Request):
body = await request.json()
messages = body.get("messages") or []
# Retrieve using the last user message
last = next((m for m in reversed(messages) if m.get("role") == "user"), None)
query = ""
if last:
c = last.get("content")
query = c if isinstance(c, str) else " ".join(
p.get("text", "") for p in (c or []) if p.get("type") == "text")
cites = []
if query.strip():
try:
hits = search(con, query, embed_fn, int(body.pop("rag_top_k", 5)))
if hits:
ctx, cites = build_context(hits)
messages = [{"role": "system",
"content": RAG_PROMPT + ctx}] + messages
body["messages"] = messages
except Exception as exc:
# A knowledge base failure must not break the conversation —
# degrade to a plain answer and report the reason in a header
return await forward(request, body,
{"X-RAG-Error": str(exc)[:200], "X-RAG-Hits": "0"})
# Retrieval work calls for following the sources, not improvising
body.setdefault("chat_template_kwargs", {}).setdefault("enable_thinking", False)
return await forward(request, body, {
"X-RAG-Hits": str(len(cites)),
"X-RAG-Sources": json.dumps([c["doc_name"] for c in cites])[:500],
})
Corrections for fields and headers. The following adds field hydration and the omitted splitting helper, then serializes a valid ASCII JSON source header. Non-Latin-1 names in the Chinese original’s header fail Starlette encoding; both languages’ [:500] truncation can cut JSON. Replace the final header dictionary with rag_headers(cites), log exception details privately and use a fixed public error code. SDK access and browser CORS expose settings determine whether a client can read these custom headers.
# Correction: hydrate the original search() output before build_context().
def hydrate_hits(con, ranked):
hits = []
for chunk_id, score in ranked:
row = con.execute(
"SELECT c.text, c.heading, d.name AS doc_name "
"FROM chunks c JOIN documents d ON d.id=c.doc_id WHERE c.id=?",
(chunk_id,),
).fetchone()
if row is not None:
hits.append({**dict(row), "score": score})
return hits
# The original endpoint's retrieval line becomes:
# hits = hydrate_hits(con, search(con, query, embed_fn, top_k))
# Bounded character splitting helper omitted from the original excerpt.
def _split_recursive(text, target, separators):
if target <= 0:
raise ValueError("target must be positive")
parts = []
while len(text) > target:
cut = target
for sep in separators:
pos = text.rfind(sep, 0, target)
if pos > 0:
cut = pos + len(sep)
break
parts.append(text[:cut])
text = text[cut:]
if text:
parts.append(text)
return parts
# ASCII JSON header, bounded without cutting a serialized JSON value.
def rag_headers(cites, limit=500):
names = [c["doc_name"] for c in cites]
selected = []
for name in names:
candidate = json.dumps(selected + [name], ensure_ascii=True)
if len(candidate) > limit:
break
selected.append(name)
return {"X-RAG-Hits": str(len(cites)),
"X-RAG-Sources": json.dumps(selected, ensure_ascii=True),
"X-RAG-Sources-Truncated": "1" if len(selected) < len(names) else "0"}
# Replace the original final header dictionary with rag_headers(cites).
# On failure, log the exception privately; use a fixed public error code:
# {"X-RAG-Error": "retrieval_failed", "X-RAG-Hits": "0"}
Three design decisions:
- Choose an explicit retrieval-failure policy. The original excerpt falls back to ordinary chat. A source-grounded task should return a retrieval failure or have the client show that retrieval was unavailable. Presenting that fallback as a sourced answer would hide the failure. Keep internal exception details in logs.
- Disable thinking by default. Retrieval work is about following sources.
- Report hits in response headers.
X-RAG-HitsandX-RAG-Sourceslet you see which documents were used without modifying any client — invaluable while tuning.
Verification
Ingest a few of your own documents, then ask something only those documents can answer:
curl -sS -D /tmp/h.txt https://your-domain/rag/v1/chat/completions \
-H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
-d '{"model":"gemma4","max_tokens":2048,
"messages":[{"role":"user","content":"What was that specific number in my notes?"}]}' \
| python3 -c "import json,sys; print(json.load(sys.stdin)['choices'][0]['message']['content'])"
grep -i "x-rag" /tmp/h.txt
A good result contains the exact figure from your document, carries a [1]-style citation, and the headers show the hit count and source filenames.
Testing retrieval alone (without generation) is more convenient for tuning — you can see whether each hit came from the vector arm or the lexical arm, which quickly separates a chunking problem from a retrieval-strategy problem.
Known limitations
- No PDF or Word parsing. This is deliberate: better to reject a format than to quietly ingest garbled text, which is extremely hard to diagnose later when retrieval quality degrades. Convert to text yourself.
- No reranker. Top-k goes straight into context. Adding a bge-reranker improves precision at the cost of another model in memory and an extra inference pass.
- This example starts with about 6000 characters of context. Three to five passages is a starting setting; compare it with longer contexts using the questions, retrieval coverage and model. Treat instructions inside retrieved documents as source text, even when those documents are inserted into a system message.
Series recap
Across four parts you now have a complete local inference stack:
- Model and engine — sizing by VRAM, running as a service
- Exposure — tunnel and direct routes, certificates and routing
- Client integration — translation extensions, editors, your own code
- Knowledge base — this article
The failures encountered along the way are catalogued separately in a symptom-indexed troubleshooting article.
Any step that can “succeed” while doing nothing needs an independent factual check afterwards. A download command returning 0 does not establish that the file is complete. A configured flag may not be honoured, and a listening service may not receive packets. Check the values the software actually computed in its logs to identify differences between the configuration and the running system.