# Build a Hybrid RAG Engine in Python: AST Code Chunking, SQLite FTS5 & Reciprocal Rank Fusion
Most Retrieval-Augmented Generation (RAG) tutorials start with a single bad habit: splitting every file into fixed 500-character blocks and tossing them into a vector database.
That works fine for short blog posts. The moment you point it at real engineering docs, API specs, or Python source files, retrieval accuracy falls apart. Fixed character splits slice Python functions in half, separate markdown headings from their examples, and blur exact identifiers like `ERR_4091` or `ORD-1001` into vague semantic averages.
In this tutorial, we build a self-contained Hybrid RAG engine in plain Python and SQLite with zero managed vector databases or heavy orchestration frameworks. Our working use case is an internal engineering and support knowledge search index that:
1. Splits Python files on AST function and class boundaries so no function is ever cut in half.
2. Splits Markdown guides on section headings so each chunk keeps its title and context together.
3. Indexes every chunk into SQLite FTS5 for fast BM25 keyword matching on exact error codes and symbol names.
4. Computes cosine similarity over deterministic local vectors and merges both ranked lists with Reciprocal Rank Fusion (RRF).
If you already built our Production-Style AI Agent Harness in Python, you can drop this search store straight behind an MCP `search_docs` tool.
—
Why Pure Vector Search Misses Exact Engineering Queries
Dense embeddings are built to capture broad meaning. If a developer asks *"how do retries work when rate limited"*, vector similarity finds paragraphs discussing backoff and HTTP 429 even if those exact words differ.
The blind spot shows up when someone searches for an exact symbol or error code:
- `ERR_4091`
- `PRAGMA journal_mode=WAL`
- `create_refund`
To a dense embedding model, `ERR_4091` and `ERR_4092` look almost identical. BM25 keyword search does the opposite: it nails exact tokens immediately, while missing synonyms. Combining both with Reciprocal Rank Fusion gives you the strengths of both without training a reranker. For a broader comparison of vector frameworks, see our Top RAG Frameworks guide.
—
Step 1: Structure-Aware Chunking (AST + Headings)
Never split source code by raw line count or character length. Python's built-in `ast` module parses syntax trees in microseconds and lets you extract each top-level function or class cleanly with `ast.get_source_segment`:
import ast
import hashlib
import re
from dataclasses import dataclass
@dataclass
class Chunk:
chunk_id: str
source: str
kind: str
text: str
def chunk_python_ast(source: str, path: str) -> list[Chunk]:
"""Split Python source on top-level functions/classes via AST."""
tree = ast.parse(source)
chunks: list[Chunk] = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
seg = ast.get_source_segment(source, node)
if seg:
cid = hashlib.sha256(f"{path}:{node.name}:{seg}".encode()).hexdigest()[:12]
chunks.append(Chunk(cid, path, "python_ast", seg))
if not chunks and source.strip():
cid = hashlib.sha256(f"{path}:module".encode()).hexdigest()[:12]
chunks.append(Chunk(cid, path, "python_ast", source.strip()))
return chunks
def chunk_markdown_headings(text: str, path: str) -> list[Chunk]:
"""Split Markdown by ## headings, keeping heading with its body."""
sections = re.split(r"(?=^##\s+)", text.strip(), flags=re.MULTILINE)
chunks: list[Chunk] = []
for i, sec in enumerate(sections):
cleaned = sec.strip()
if not cleaned:
continue
cid = hashlib.sha256(f"{path}:sec{i}:{cleaned}".encode()).hexdigest()[:12]
chunks.append(Chunk(cid, path, "markdown_section", cleaned))
return chunks
Notice how `chunk_id` is a deterministic SHA-256 hash of `(path, symbol/section, text)`. That lets the indexer skip unchanged chunks automatically on re-runs instead of duplicating rows.
—
Step 2: SQLite WAL + FTS5 Schema & Indexing
Standard Python ships with SQLite's FTS5 full-text search extension compiled in. By storing both the vector payload (`chunks`) and the full-text index (`chunks_fts`) inside one local SQLite WAL database, you eliminate network hops and extra Docker containers for small-to-medium knowledge bases:
import json
import sqlite3
def init_hybrid_db(db_path: str) -> sqlite3.Connection:
conn = sqlite3.connect(db_path, timeout=10.0)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS chunks (
chunk_id TEXT PRIMARY KEY,
source TEXT NOT NULL,
kind TEXT NOT NULL,
text TEXT NOT NULL,
vec_json TEXT NOT NULL
);
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
chunk_id UNINDEXED,
source,
text
);
"""
)
conn.commit()
return conn
Using `chunk_id UNINDEXED` in `chunks_fts` keeps the ID retrievable in `SELECT` queries without wasting index space tokenizing hashes.
—
Step 3: Reciprocal Rank Fusion (RRF) Search
Once we have a ranked list from SQLite FTS5 (`bm25_ids`) and a ranked list from cosine similarity (`vec_ids`), Reciprocal Rank Fusion merges them using one simple formula:
`score(doc) = sum(1 / (60 + rank_i))`
You do not have to normalize raw BM25 scores against cosine similarity scores, because RRF only cares about each document's rank position in each list:
def fuse_rrf(bm25_ids: list[str], vec_ids: list[str], top_k: int = 3, rrf_k: int = 60) -> list[tuple[str, float]]:
rrf_scores: dict[str, float] = {}
for rank, cid in enumerate(bm25_ids, 1):
rrf_scores[cid] = rrf_scores.get(cid, 0.0) + 1.0 / (rrf_k + rank)
for rank, cid in enumerate(vec_ids, 1):
rrf_scores[cid] = rrf_scores.get(cid, 0.0) + 1.0 / (rrf_k + rank)
return sorted(rrf_scores.items(), key=lambda item: item[1], reverse=True)[:top_k]
If a chunk ranks `#1` in both BM25 and vector search, its score is `1/61 + 1/61 = 0.03279`. If it ranks `#1` in BM25 and `#2` in vector search, it gets `1/61 + 1/62 = 0.03252`, beating documents that only appear in one list.
—
Step 4: Verified Pytest Output & Recorded Benchmark
Running our test suite in `demos/hybrid_rag_engine/` verifies AST function preservation, Markdown section splitting, duplicate-safe re-indexing, and exact error-code + semantic fusion:
test_rag.py::test_ast_chunking_keeps_functions_intact PASSED [ 33%]
test_rag.py::test_markdown_heading_chunking PASSED [ 66%]
test_rag.py::test_hybrid_rrf_finds_exact_error_code_and_semantic PASSED [100%]
============================== 3 passed in 0.03s ===============================
In our recorded local benchmark querying `"ERR_4091 refund window"` across the indexed Python and Markdown chunks, `search_hybrid` completed in 0.9 ms with a top RRF score of 0.03252, ranking the exact `verify_refund_window` function first.
—
Production Trade-Offs and Scaling Limits
This architecture is intentionally lightweight and works well up to roughly 50,000–100,000 local chunks. Before scaling further:
1. Swap trigram vectors for neural embeddings: Our local 128-dim trigram vector keeps tests zero-cost and offline, whereas real semantic paraphrases benefit from a dedicated embedding model.
2. Add approximate nearest-neighbor indexing: Linearly scanning `vec_json` in Python is sub-millisecond for small repos, but larger corpora should move to `sqlite-vec` or `pgvector`.
3. Add a cross-encoder reranker on top 10: When precision on top-3 results matters most, rerank the RRF candidates before passing them to your LLM.
—
Frequently Asked Questions
Why use RRF instead of weighted score averaging?
BM25 scores in SQLite FTS5 are negative unbounded floats, while cosine similarity sits between `-1` and `1`. RRF uses rank positions instead of raw scores, so you avoid brittle normalization tuning.
Does AST chunking work for non-Python files?
Python's built-in `ast` module handles Python natively. For TypeScript, Go, or Rust, use `tree-sitter` with the same function-and-class extraction rule.




Leave a Reply