Engineering

Building RAG over a Codebase: Chunking, Embeddings, Hybrid Search and Gemini

A practical guide to retrieval-augmented generation for code: chunk by symbol, embed with metadata, hybrid search, prompt with context and evaluate.

By Japan Gor · · 7 min read

Ask a general-purpose language model "where do we validate refund amounts?" and it can only guess, because it has never seen your repository. Retrieval-augmented generation (RAG) fixes that by finding the relevant code first and handing it to the model as context. The idea is simple, but code is a particular kind of text: it has structure, exact identifiers, cross-file references and frequent changes. This guide walks through a practical, model-agnostic design for code RAG (chunking by symbol, embeddings, metadata, hybrid search, prompting and evaluation) with notes on using Google's Gemini embedding API for the vector part.

The pipeline at a glance

Repository
  -> parse files into symbol-level chunks (+ metadata)
  -> embed each chunk           -> vector index
  -> tokenise identifiers/text  -> keyword (BM25) index
Query
  -> embed query + keyword search -> merge results -> (optional) rerank
  -> build prompt with top chunks -> LLM answer with file/line references

Each stage has decisions that matter more than the choice of model.

Step 1: Chunk code by symbol, not by line count

The easiest chunking strategy (split every N characters or lines) works badly for code. It cuts functions in half, separates a method from its class and mixes unrelated code into one chunk.

A better unit is the symbol: a function, method, class or top-level block. Practical approaches:

  • Use a real parser. Python's built-in ast module gives you function and class nodes with line numbers. For many languages at once, Tree-sitter provides parsers and a query language.
  • Keep context with each chunk. Prepend the file path, the enclosing class name and the relevant imports, so a method chunk still makes sense in isolation.
  • Split very large symbols. A 600-line function should be split at logical blocks, with the signature repeated in each piece.
  • Create file-level summary chunks for small files, configs and READMEs, which don't have meaningful symbols.

A minimal Python chunker:

import ast
from pathlib import Path

def chunk_python_file(path: Path):
    source = path.read_text(encoding="utf-8")
    tree = ast.parse(source)
    lines = source.splitlines()
    chunks = []
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
            start, end = node.lineno, node.end_lineno
            body = "\n".join(lines[start - 1:end])
            chunks.append({
                "id": f"{path}:{node.name}:{start}",
                "path": str(path),
                "symbol": node.name,
                "kind": type(node).__name__,
                "start_line": start,
                "end_line": end,
                "docstring": ast.get_docstring(node) or "",
                "text": f"# file: {path}\n{body}",
            })
    return chunks

Note that ast.walk yields both a class and its methods, so a class chunk overlaps its method chunks. That's often useful (class-level questions match the class, specific questions match methods), but you may want to store only the class signature and docstring for large classes.

Step 2: Attach metadata

Metadata turns a fuzzy similarity search into something you can filter and cite. Store, per chunk:

FieldWhy it helps
path, start_line, end_linePrecise citations in answers; links to your code host
symbol, kindExact-match lookups and filters ("only classes")
languageFilter by language in polyglot repos
module / packageScope searches to a service or folder
commit or content hashDetect stale chunks; re-embed only what changed
is_testInclude or exclude tests depending on the question

Hashing each chunk's text means that on every commit you re-embed only chunks whose hash changed, which keeps indexing cheap for large repos.

Step 3: Create embeddings

Embeddings map text to vectors so that semantically similar text lands close together. Any embedding model can work; what matters is that you embed queries and documents in a compatible way and evaluate on your own data.

Using the Gemini embedding API

Google's Gemini embeddings documentation lists the available embedding models and options; check it for the current list, as models are updated. At the time of writing it documents gemini-embedding-001 (text) and a newer multimodal gemini-embedding-2. Relevant details from the docs:

  • Task types (for gemini-embedding-001). You can set a task_type, including RETRIEVAL_DOCUMENT for indexed content, RETRIEVAL_QUERY for search queries and CODE_RETRIEVAL_QUERY for natural-language queries meant to retrieve code. Per the docs, gemini-embedding-2 does not accept task_type; it uses a text prefix in the input instead, so read the current guidance for the model you pick.
  • Output dimensionality. The default is 3,072 dimensions, and you can request a smaller size (the docs recommend 768, 1,536 or 3,072). Smaller vectors cost less to store and search, with some loss of quality you should measure.
  • Normalisation. The docs note that with gemini-embedding-001, vectors at dimensions other than 3,072 should be normalised yourself before computing cosine similarity.

A sketch using the google-genai Python SDK:

import numpy as np
from google import genai
from google.genai import types

client = genai.Client()  # reads the API key from the environment
MODEL = "gemini-embedding-001"
DIM = 768

def embed(texts, task_type):
    result = client.models.embed_content(
        model=MODEL,
        contents=texts,
        config=types.EmbedContentConfig(task_type=task_type, output_dimensionality=DIM),
    )
    vecs = np.array([e.values for e in result.embeddings], dtype="float32")
    return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)

doc_vecs = embed([c["text"] for c in chunks], "RETRIEVAL_DOCUMENT")
query_vec = embed(["where are refund amounts validated?"], "CODE_RETRIEVAL_QUERY")[0]
scores = doc_vecs @ query_vec
top = np.argsort(-scores)[:10]

Batch your requests and respect the API's rate and input-size limits; split very long chunks rather than letting them be truncated. For more than a few thousand chunks, store vectors in a vector database or an approximate nearest-neighbour library instead of a NumPy array.

Step 4: Hybrid search

Pure vector search is good at intent ("code that retries failed payments") but weak at exact tokens like validate_refund_amount, error codes or config keys. Keyword search (for example BM25) is the opposite. For code, combining them usually beats either alone, but verify that on your own evaluation set.

Practical tips:

  • Tokenise identifiers for the keyword index: split validateRefundAmount and validate_refund_amount into validate refund amount as well as keeping the original token.
  • Merge rankings with reciprocal rank fusion (RRF). Each result scores the sum of 1 / (k + rank) across the lists it appears in, with k commonly set around 60. It's simple and doesn't require calibrating scores from different systems.
def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        for rank, chunk_id in enumerate(ranking, start=1):
            scores[chunk_id] = scores.get(chunk_id, 0) + 1 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)
  • Use metadata filters before ranking when the user's question implies a scope ("in the billing service").
  • Optionally rerank the top 30 to 50 merged results with a cross-encoder or an LLM, then keep the best handful.
  • Expand with structure. After retrieving a function, consider adding its callers, callees or the class definition it belongs to. A call graph from your parser makes this cheap.

Step 5: Prompt with retrieved context

How you present context affects answer quality as much as what you retrieve:

You are answering questions about the repository below.
Use only the provided code. If the answer is not in the context, say so.
Cite sources as path:start_line-end_line.

<context>
[1] billing/refunds.py:40-78  (function validate_refund_amount)
...code...

[2] billing/models.py:12-35  (class Refund)
...code...
</context>

Question: Where are refund amounts validated, and what limits apply?

Guidelines:

  • Label every chunk with path and line range so the model can cite precisely, and so you can check it.
  • Order matters. Put the most relevant chunks first and keep the total context focused; more irrelevant code tends to dilute answers.
  • Tell the model to admit gaps. "If it isn't in the context, say so" reduces confident guessing, though it doesn't eliminate it.
  • Keep secrets out. Exclude .env files, credentials and generated artefacts at indexing time; anything indexed can end up in a prompt.

Step 6: Evaluate retrieval and answers separately

Without evaluation you can't tell whether a change helped. Split it in two:

Retrieval evaluation

Build a set of 50 to 200 real questions, each labelled with the chunk(s) that answer it. Developers' past questions in chat or code review are a good source. Then measure:

  • Recall@k: how often the correct chunk appears in the top k results.
  • MRR (mean reciprocal rank): how high the first correct chunk ranks.

Run this every time you change chunking, embedding model, dimensionality or fusion settings.

Answer evaluation

For generated answers, check:

  • Groundedness: is every claim supported by the cited chunks?
  • Citation accuracy: do cited paths and lines actually contain the referenced code?
  • Correctness: does a developer familiar with the code agree?

Automated LLM-as-judge scoring can help at scale, but spot-check it with human review, since judge models make mistakes too.

Keeping the index fresh

Code changes constantly. Re-index on merge to the main branch, re-embed only chunks whose hash changed, delete chunks for removed files, and store the commit hash so answers can say which version they describe. If you change embedding models or dimensions, re-embed everything: vectors from different models aren't comparable.

Summary

Good code RAG comes down to a few unglamorous decisions: chunk by symbol with context, store rich metadata, combine vector and keyword search, present labelled context with clear instructions, and evaluate retrieval separately from generation. Gemini's embedding API, with its code-retrieval task type and configurable dimensions, fits neatly into the vector stage, but the same design works with any embedding model. Build the evaluation set early; it's the only reliable way to know which of these knobs actually matter for your codebase.

Try it on GJAM

Open the tool

More guides