Codebase Q&A With Embeddings: Ask Questions About Your Own Code

Build codebase Q&A with embeddings in six steps: chunk your code, embed it, retrieve the closest chunks and answer from real files, with citations.

By Galactic News Editorial · Published 2026-11-22T04:53:21+00:00 · Updated 2026-11-22T04:53:21+00:00

Codebase Q&A embeddings pipeline searching code and returning answers

Codebase Q&A with embeddings lets you ask questions about your own code and get answers grounded in the actual files. The idea is simple. Turn each chunk of code into an embedding, a list of numbers that captures its meaning. Store those vectors in a database. When you ask a question, embed the question too, find the closest code chunks, and hand them to a language model with the question. The model answers from your code, not from general knowledge. This tutorial builds that pipeline in six steps.

How codebase Q&A embeddings work

An embedding model converts text into a vector of floating point numbers. The distance between two vectors measures how related the texts are. Small distances mean high relatedness. OpenAI's text-embedding-3-small produces 1,536 numbers per chunk by default, and accepts up to 8,192 input tokens per call. OpenAI's own guide notes it handles roughly 62,500 pages of text per dollar at typical token counts. That makes embedding a whole codebase cheap.

The pipeline has four parts. First, split the codebase into chunks. Second, embed each chunk and store the vector with the chunk's text and file path. Third, embed the user's question and retrieve the nearest chunks. Fourth, send the question plus the retrieved chunks to a language model and return the answer. The retrieval step is what keeps answers honest. If the answer is not in the retrieved code, the model should say so.

For storage, pgvector adds vector similarity search to PostgreSQL. It supports exact and approximate nearest neighbor search, with cosine distance, L2 distance, inner product, and other measures. You enable it with CREATE EXTENSION vector, add a vector column to a table, and query with the cosine distance operator. The advantage over a separate vector database is that vectors live with the rest of your data, so you can combine similarity search with ordinary SQL filters and joins.

Step 1: Pick the embedding model and the vector store

Choose text-embedding-3-small for most codebases. It is fast, cheap, and supports a dimensions parameter if you want shorter vectors. Record the model name and the dimension count in your config. The dimension count must match the vector column in your database. If you switch models later, re-embed everything. Mixing vectors from different models gives meaningless distances.

Pick the vector store next. If the team already runs PostgreSQL, pgvector is the simplest choice. It needs no new service and no data sync. For a standalone project, a local vector database such as LanceDB works well and needs no server. Avoid adding a hosted vector database until the codebase is large enough to need it. A few thousand chunks run fine in Postgres.

Step 2: Chunk the code by function, not by line count

Chunking decides answer quality. A chunk that cuts a function in half loses context. A chunk that holds an entire file is too broad to match a specific question. The best unit for code is usually one function or one class, plus its docstring and a short header naming the file. For config files and docs, split on headings or sections instead.

Keep chunks under the model's token limit. Text-embedding-3-small accepts 8,192 tokens per input, but smaller chunks retrieve better. Aim for 200 to 500 tokens per chunk. Store the file path, the start and end lines, and the chunk text alongside each vector. The file path is what lets the answer cite real locations in the codebase.

Skip generated files, vendored code, and build output. They add noise and cost. Exclude node_modules, dist, and lockfiles before indexing. Re-index a file when it changes, and delete vectors for deleted files. A stale index answers questions about code that no longer exists.

Step 3: Embed the chunks and store the vectors

Write a small indexing script. It walks the repository, chunks each file, calls the embeddings API in batches, and inserts the results. Batching matters. The API accepts up to 2,048 inputs per request, with a 300,000-token cap across all inputs in one request. Keep batches small enough to stay under that cap.

import psycopg
from pgvector.psycopg import register_vector
from openai import OpenAI

client = OpenAI()
conn = psycopg.connect("postgresql://localhost:5432/codebase")
register_vector(conn)

def embed(texts):
    response = client.embeddings.create(
        model="text-embedding-3-small",
        input=texts,
    )
    return [item.embedding for item in response.data]

cur = conn.cursor()
cur.execute("CREATE EXTENSION IF NOT EXISTS vector")
cur.execute("""CREATE TABLE IF NOT EXISTS code_chunks (
    id BIGSERIAL PRIMARY KEY,
    path TEXT NOT NULL,
    start_line INT,
    content TEXT NOT NULL,
    embedding vector(1536)
)""")
conn.commit()

Store the embedding in the same row as the chunk text. That keeps the vector and its source together. If the embedding call fails, retry that batch before moving on. Log how many chunks were embedded and how many failed. A silent failure leaves gaps in the index.

Step 4: Retrieve the closest chunks for each question

At query time, embed the question with the same model. Then run a similarity search. In pgvector, the cosine distance operator is <=>. Order by distance ascending and take the top five to eight chunks. Cosine distance of 0 means identical, so 1 minus distance gives a similarity score between 0 and 1.

SELECT path, start_line, content,
       1 - (embedding <=> %s) AS similarity
FROM code_chunks
ORDER BY embedding <=> %s
LIMIT 5;

Filter by file type or directory when the question is specific. A question about authentication should search the auth module first. pgvector lets you add a WHERE clause to the same query, which a separate vector database may not. For larger tables, add an HNSW index on the embedding column to keep searches fast. Without an index, every query scans every row.

Step 5: Answer with the retrieved code as the only source

Build the prompt from the question and the retrieved chunks. Include the file path and line numbers for each chunk. Tell the model to answer only from the provided code, and to say it does not know when the code does not contain the answer. That instruction is the main defense against hallucinated answers.

Return citations with the answer. Each claim should name the file and line range it came from. A developer who can click through to the source can verify the answer in seconds. An answer without citations is a guess, even when it is right.

For a working example without building the pipeline, Continue.dev is an open-source editor extension that indexes a codebase and answers questions with its @codebase command. It runs in VS Code and JetBrains, uses embeddings for retrieval, and works with local models through Ollama or with hosted models through their APIs. It is a useful reference for how the pieces fit together.

Step 6: Evaluate the answers before trusting them

Build a small test set of questions with known answers. Include questions about how a feature works, where a piece of logic lives, and what a function returns. Run the pipeline over the test set and check each answer by hand. Track two scores: whether the right chunks were retrieved, and whether the answer was correct.

Common failures have clear fixes. Wrong chunks usually mean the chunking is too coarse or the query needs more context. Correct chunks with wrong answers usually mean the prompt is too loose. Tighten the instruction to answer only from the retrieved code. Re-run the test set after every change to the chunking, the model, or the prompt.

ChoiceSimple optionWhen to upgrade
Embedding modeltext-embedding-3-small, 1,536 dimensionsLarger model for multilingual or very large codebases
Vector storepgvector inside existing PostgreSQLDedicated vector database past roughly 100,000 chunks
Chunk unitOne function or class with its docstringSmaller chunks when retrieval misses the right code
RetrievalTop 5 chunks by cosine similarityHybrid search with keyword matching for exact names
Answering modelAny chat model with a large context windowA stronger model when answers need deep reasoning

Bottom line

Codebase Q&A with embeddings is four parts: chunk the code, embed it, retrieve the closest chunks, and answer from them. Start with text-embedding-3-small and pgvector. Chunk by function. Cite file paths in every answer. Test with known questions before trusting the system. The pipeline is small enough to build in a day, and useful enough to keep.