Project 3: Codebase Q&A Assistant

Ask questions about a Git repository and get answers that point to files and lines.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 24 · Lesson 4 of 7 · Intermediate

Project 3: Codebase Q&A Assistant

Ask questions about a Git repository and get answers that point to files and lines.

This project builds a command-line assistant that answers questions about a Python repository. It combines the code-aware retrieval from Code RAG with an agent that can search the index and open files to read surrounding code, so it can follow a function call into another file before answering. Answers reference files and line numbers.

Design

  • Index: functions and classes extracted with ast, searchable with identifier-aware BM25 plus dense embeddings, cached to disk.
  • Tools for the agent: search_code(query) and read_file(path, start, end), restricted to the repository folder.
  • Agent: the SDK tool runner decides how to search and what to read, then answers with file:line references.
pip install anthropic sentence-transformers rank-bm25 numpy
code_qa.py
"""Ask questions about a Python repository.   Usage: python code_qa.py path/to/repo"""
import ast
import pickle
import re
import sys
from pathlib import Path

import anthropic
import numpy as np
from anthropic import beta_tool
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer

REPO = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
SKIP = {".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist"}
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
client = anthropic.Anthropic()

# ---------- Indexing ----------
def code_tokens(text: str) -> list[str]:
    tokens = []
    for word in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", text):
        tokens.append(word.lower())
        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]
    return tokens

def extract_chunks(repo: Path) -> list[dict]:
    chunks = []
    for path in repo.rglob("*.py"):
        if SKIP & set(path.relative_to(repo).parts):
            continue
        source = path.read_text(encoding="utf-8", errors="replace")
        try:
            tree = ast.parse(source)
        except SyntaxError:
            continue
        lines, rel = source.splitlines(), 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)
                code = "\n".join(lines[start - 1:node.end_lineno])[:4000]
                chunks.append({"file": rel, "symbol": node.name, "start": start, "end": node.end_lineno,
                               "text": f"# {rel}:{start}\n{code}"})
    return chunks

def load_index(repo: Path) -> dict:
    cache = repo / ".code_qa_index.pkl"
    newest = max((p.stat().st_mtime for p in repo.rglob("*.py")), default=0)
    if cache.exists() and cache.stat().st_mtime > newest:
        return pickle.loads(cache.read_bytes())
    chunks = extract_chunks(repo)
    index = {"chunks": chunks,
             "vectors": embedder.encode([c["text"] for c in chunks], normalize_embeddings=True, batch_size=64),
             "tokens": [code_tokens(c["text"]) for c in chunks]}
    cache.write_bytes(pickle.dumps(index))
    return index

INDEX = load_index(REPO)
BM25 = BM25Okapi(INDEX["tokens"])
print(f"Indexed {len(INDEX['chunks'])} functions and classes in {REPO}")

# ---------- Tools ----------
@beta_tool
def search_code(query: str, k: int = 6) -> str:
    """Search the repository's functions and classes by meaning and by identifier names.

    Returns file paths with line ranges and code. Use specific terms (function names, error
    messages, concepts). Search again with different terms if results are not relevant.

    Args:
        query: What to look for.
        k: Number of results (1-10).
    """
    k = max(1, min(k, 10))
    dense = INDEX["vectors"] @ embedder.encode(
        "Represent this sentence for searching relevant passages: " + query, normalize_embeddings=True)
    sparse = BM25.get_scores(code_tokens(query))
    fused: dict[int, float] = {}
    for ranking in (np.argsort(-dense)[:40], np.argsort(-sparse)[:40]):
        for rank, i in enumerate(ranking, start=1):
            fused[i] = fused.get(i, 0.0) + 1 / (60 + rank)
    best = sorted(fused, key=fused.get, reverse=True)[:k]
    return "\n\n".join(f"--- {INDEX['chunks'][i]['file']}:{INDEX['chunks'][i]['start']}-"
                       f"{INDEX['chunks'][i]['end']} ({INDEX['chunks'][i]['symbol']})\n"
                       f"{INDEX['chunks'][i]['text']}" for i in best)

@beta_tool
def read_file(path: str, start_line: int = 1, end_line: int = 120) -> str:
    """Read lines from a file in the repository, e.g. to see imports or code around a search hit.

    Args:
        path: File path relative to the repository root.
        start_line: First line to return (1-based).
        end_line: Last line to return (at most 300 lines per call).
    """
    target = (REPO / path).resolve()
    if REPO not in target.parents or not target.is_file():
        return "Error: path is outside the repository or does not exist."
    lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
    start = max(1, start_line)
    end = min(len(lines), end_line, start + 299)
    return "\n".join(f"{n:5}  {lines[n - 1]}" for n in range(start, end + 1))

SYSTEM = f"""You answer developers' questions about the Python repository at {REPO.name}.
Use search_code to find relevant code and read_file to inspect surrounding code or follow calls.
Base your answer on code you have actually seen. Reference code as path:line. If you could not
find something, say what you searched for."""

def ask(question: str) -> str:
    runner = client.beta.messages.tool_runner(
        model="claude-opus-5-5", max_tokens=8000, output_config={"effort": "medium"},
        system=SYSTEM, tools=[search_code, read_file],
        messages=[{"role": "user", "content": question}])
    final = None
    for message in runner:
        for block in message.content:
            if block.type == "tool_use":
                print(f"   [{block.name}] {str(block.input)[:90]}")
        final = message
    return "".join(b.text for b in final.content if b.type == "text")

if __name__ == "__main__":
    while question := input("\nQuestion (empty to quit): ").strip():
        print("\n" + ask(question))

Run it

python code_qa.py path/to/some/python/project
Indexed 412 functions and classes in /home/dev/shop-api

Question (empty to quit): How are coupon codes validated, and what happens when one is expired?
   [search_code] {'query': 'validate coupon code expiry'}
   [read_file] {'path': 'shop/discounts/coupons.py', 'start_line': 1, 'end_line': 80}

Coupon codes are validated in CouponService.validate (shop/discounts/coupons.py:42). It looks
up the code, then checks expires_at against the current time (coupons.py:51); an expired coupon
raises CouponExpired, which the checkout view turns into an HTTP 400 response with the message
"This coupon has expired" (shop/api/checkout.py:88).

Why an agent here?

Code questions often need several hops: find the function, then the class it uses, then where its exception is handled. A single retrieval step finds the first hop; the agent's ability to search again and read files lets it follow the chain, the multi-hop pattern from Multi-Hop Retrieval with tools.

Extensions

  1. Support more languages with tree-sitter parsers.
  2. Add a find_references(symbol) tool backed by a simple call graph built from the AST.
  3. Index docstrings and generated one-line summaries for better natural-language matching.
  4. Re-index only changed files using content hashes instead of file times.
  5. Expose the tools through an MCP server (RAG as an MCP Server) so IDE assistants can use them.

Key takeaways

  • Code retrieval works best with structure-aware chunks and identifier-aware hybrid search.
  • Giving an agent both search and file-reading tools lets it follow code across files.
  • Restrict file access to the repository and cap the amount of text each tool returns.