Code RAG: Retrieval over Codebases

Chunk source code by function, index symbols and answer questions about a repository.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 15 · Lesson 5 of 5 · Advanced

Code RAG: Retrieval over Codebases

Chunk source code by function, index symbols and answer questions about a repository.

Developers ask questions such as "Where do we validate coupon codes?", "How does the retry logic in the payment client work?" or "Which services call send_invoice?". Answering them means retrieving source code, which differs from prose in important ways: it has strict structure, identifiers matter more than natural language, and relationships (calls, imports) carry meaning. This lesson builds a code retrieval system for a Python repository.

What makes code different

  • Chunk by structure. A function or class is the natural unit; splitting one in half makes both halves useless.
  • Identifiers are key. validate_coupon, CouponValidator and coupon_validation should all match "coupon validation". Keyword search needs identifier-aware tokenisation.
  • Context is in the path. billing/payments/retry.py tells you a lot about the code inside.
  • Natural-language descriptions help. Questions are in English; code is not. Docstrings and generated summaries bridge the gap.

Step 1: Chunk a repository by function and class

code_index.py
import ast
from pathlib import Path

SKIP_DIRS = {".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist"}

def python_chunks(repo: str) -> list[dict]:
    chunks = []
    for path in Path(repo).rglob("*.py"):
        if SKIP_DIRS & set(path.parts):
            continue
        source = path.read_text(encoding="utf-8", errors="replace")
        try:
            tree = ast.parse(source)
        except SyntaxError:
            continue
        lines = source.splitlines()
        rel = path.relative_to(repo).as_posix()
        for node in ast.walk(tree):
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
                start = (node.decorator_list[0].lineno if node.decorator_list else node.lineno) - 1
                code = "\n".join(lines[start:node.end_lineno])
                if len(code) > 6000:                       # very large classes: keep the signature part
                    code = code[:6000] + "\n# ... (truncated)"
                chunks.append({
                    "id": f"{rel}:{start + 1}",
                    "text": f"# File: {rel}\n# {type(node).__name__.removesuffix('Def')} {node.name}\n{code}",
                    "metadata": {"file": rel, "symbol": node.name, "start_line": start + 1,
                                 "end_line": node.end_lineno, "doc": ast.get_docstring(node) or ""},
                })
    return chunks

ast.walk also yields methods inside classes, so both the class and its methods are indexed. For other languages, tree-sitter grammars give the same information.

Step 2: Identifier-aware keyword search

Split camelCase and snake_case identifiers into words so that "coupon validation" matches validateCoupon:

import re

def code_tokens(text: str) -> list[str]:
    tokens = []
    for word in re.findall(r"[A-Za-z_][A-Za-z0-9_]*|\d+", text):
        tokens.append(word.lower())                                   # the full identifier
        parts = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", word).replace("_", " ").split()
        if len(parts) > 1:
            tokens += [p.lower() for p in parts]                     # its pieces
    return tokens

print(code_tokens("def validateCoupon(coupon_code):"))
# ['def', 'validatecoupon', 'validate', 'coupon', 'coupon_code', 'coupon', 'code']

Step 3: Hybrid search over code

Combine BM25 over identifier tokens with dense embeddings, fused with RRF. A general text embedding model works reasonably for code; a code-specific embedding model (such as Voyage's code models or Jina's code embeddings) works better.

import numpy as np
from rank_bm25 import BM25Okapi
from hybrid import rrf                  # from the hybrid search lesson
from rag_helpers import embed

class CodeSearch:
    def __init__(self, chunks: list[dict]):
        self.chunks = chunks
        texts = [f"{c['metadata']['doc']}\n{c['text']}" for c in chunks]
        self.bm25 = BM25Okapi([code_tokens(t) for t in texts])
        self.vectors = embed(texts)

    def search(self, query: str, k: int = 6) -> list[dict]:
        bm = self.bm25.get_scores(code_tokens(query))
        dense = self.vectors @ embed(query, query=True)[0]
        fused = rrf([list(np.argsort(-bm)[:40]), list(np.argsort(-dense)[:40])])
        return [self.chunks[i] for i, _ in fused[:k]]

Step 4: Answer with file and line references

from rag_helpers import ask

def ask_codebase(question: str, search: CodeSearch) -> str:
    hits = search.search(question)
    context = "\n\n".join(
        f'<code file="{h["metadata"]["file"]}" lines="{h["metadata"]["start_line"]}-{h["metadata"]["end_line"]}">\n'
        f'{h["text"]}\n</code>' for h in hits)
    return ask(f"{context}\n\nAnswer the developer's question using the code above. Refer to code as "
               "file:line. Quote short snippets where useful. If the code shown is not enough to be "
               f"sure, say what else should be checked.\n\nQuestion: {question}", effort="medium")

search = CodeSearch(python_chunks("path/to/your/repo"))
print(ask_codebase("Where are coupon codes validated, and what happens when one has expired?", search))

Going further

  • Summaries per function: generate one-sentence descriptions and index them (multi-vector retrieval) to match plain-English questions.
  • Repository map: a short list of files with their classes and functions, given to the model, helps it understand the overall structure.
  • Call graphs: index "who calls what" so questions such as "what breaks if I change send_invoice?" can follow edges, as in GraphRAG.
  • Agentic code search: coding agents such as Claude Code often skip vector indexes entirely and explore the repository with grep-style search and file reading tools. For a live codebase that changes constantly, giving an agent good search tools can beat maintaining an index.
  • Freshness: re-index on every merge to the main branch, using file hashes to process only changed files.

Capstone Project 3 turns this into a complete application.

Key takeaways

  • Chunk code by functions and classes with a parser, and include the file path in each chunk.
  • Split identifiers into words for keyword search, and combine it with embeddings.
  • Answer with file:line references so developers can jump straight to the code.
  • Add summaries, repository maps or agentic search for larger and faster-changing codebases.