Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

RAG over a codebase

Index a codebase into Telys — chunk files, add them with path and line metadata, retrieve with natural-language search, and hand the results to an LLM.

Run RAG over source code entirely on your machine — proprietary code never leaves it. Telys' lexical multigram embedder is strong at natural-language-to-code retrieval ("where do we validate the session token?" → the right function). The loop:

  1. Chunk files into overlapping line windows.

  2. Add each chunk with add_texts, carrying path, start_line, and lang as metadata.

  3. Retrieve with search_text, optionally filtered by language or file.

  4. Assemble the hits into a prompt for an LLM.

Install with pipx install telys, sign in with telys login, then verify with telys runtime verify — the embedder needs the native kernel from the verified runtime. See Install Telys.

Why lexical multigram for code

Dense sentence embedders are tuned for prose. Code is full of identifiers, snake_case, camelCase, and punctuation that dense models tokenize poorly. AlgentaMultigramEmbedder concatenates L2-normalized unigram, bigram, and trigram hashes, so parse invoice date lands near def parse_invoice_date(...) on substring and token overlap. Use it for natural-language-to-code retrieval on-device. See Lexical vs dense embeddings and AlgentaMultigramEmbedder.

Chunk and index

Chunk by fixed line windows with a small overlap, so a symbol split across a boundary stays retrievable. Store enough metadata to point back at the source.

index_codebase.py
from pathlib import Path

from telys import Telys, Eq
from telys.embedding import AlgentaMultigramEmbedder

EXTS = {".py": "python", ".ts": "typescript", ".go": "go", ".rs": "rust", ".md": "markdown"}
WINDOW, OVERLAP = 40, 10  # lines per chunk, lines of overlap


def chunk_file(path: Path):
    lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
    step = WINDOW - OVERLAP
    for start in range(0, max(1, len(lines)), step):
        body = "\n".join(lines[start:start + WINDOW])
        if body.strip():
            yield start + 1, body  # 1-based start line


def build_index(repo: str, store: str = "./code-index", name: str = "code"):
    emb = AlgentaMultigramEmbedder()
    telys = Telys(store)
    col = telys.create_collection(
        name,
        dim=emb.profile.dimension,
        partition_by="repo",                 # one partition per repository
        embedder=emb,
        filter_columns=("path", "lang", "start_line", "text"),  # round-trip via with_metadata; filter on path/lang
    )

    texts, ids, metas = [], [], []
    for path in Path(repo).rglob("*"):
        lang = EXTS.get(path.suffix)
        if not lang or not path.is_file():
            continue
        rel = str(path.relative_to(repo))
        for start_line, body in chunk_file(path):
            texts.append(body)
            ids.append(f"{rel}:{start_line}")
            metas.append({
                "repo": name,
                "path": rel,
                "lang": lang,
                "start_line": start_line,
                "text": body,           # keep the chunk so we can rebuild context
            })

    # Insert in batches to bound memory, then commit once.
    for i in range(0, len(texts), 512):
        col.add_texts(texts[i:i + 512], ids[i:i + 512], metas[i:i + 512])
    col.save()
    print(f"indexed {len(texts)} chunks from {name}")
    return telys, col


if __name__ == "__main__":
    build_index(repo=".")

Retrieve for a question

Retrieval is one search_text call. Pass with_metadata=True so each hit carries the path, start_line, and stored text you need to cite and build the prompt. Add Eq to scope to one language or file.

What you will see

Indexing prints the chunk count. Retrieval prints ranked source locations, the token-validation function highest:

build_prompt assembles those snippets into a citable context block for a chat model.

Scaling to large repositories

For tens of thousands of chunks, build the IVF index after loading to keep searches fast at high recall. build_ivf is a no-op below its min_rows threshold, so calling it unconditionally is safe:

See Build the IVF index and Search internals (IVF).

Next steps

Last updated

Was this helpful?