Intelligent code exploration through grounded retrieval.
A retrieval-augmented AI system that enables developers to ask natural-language questions about Python and JavaScript repositories and receive answers supported by retrieved source code. The project explores hybrid retrieval, structured code parsing, citation validation, asynchronous backend development and agentic workflows with persistent human review.
Codebase Q&A Assistant / Application Click to enlarge
The web application: ingest a public GitHub repository, then ask a question and choose a model provider.
Project at a glance
Project type
Personal engineering project
Languages indexed
Python and JavaScript
Retrieval
Exact-symbol search and pgvector semantic search, merged with Reciprocal Rank Fusion
Model providers
Groq (default), Azure AI Foundry and AWS Bedrock, chosen per request
Agent
Standalone LangGraph workflow, separate from the public web routes
Deployment
Docker; Render deployment history; a completed and since torn-down AWS EC2 and RDS exercise
Problem and objective
Understanding an unfamiliar codebase often requires navigating multiple files, identifying relevant functions and tracing relationships between components.
General-purpose language models can explain programming concepts, but without access to the actual repository, their responses may not reflect the implementation being investigated.
I built the Codebase Q&A Assistant to explore how structured source-code parsing and hybrid retrieval can provide more relevant context to a language model, allowing developers to ask questions about an indexed repository and inspect the supporting source references.
Web application architecture
The web application is an asynchronous FastAPI service with two working routes: POST /ingest and POST /ask. Ingestion clones a public GitHub repository, splits each file into code chunks, embeds them with FastEmbed (BAAI/bge-small-en-v1.5, 384 dimensions) and stores the chunks and vectors in PostgreSQL with pgvector.
Python files are parsed with the standard-library ast module and JavaScript files with tree-sitter. Both are dispatched by file extension from one chunking entry point, so retrieval does not need to know which language it is searching. A synthetic module chunk captures top-level imports and constants.
Web application / source ingestionFIG. 01
Read diagram as text
A public GitHub repository enters the FastAPI ingestion endpoint. Python AST or JavaScript tree-sitter extracts code units. FastEmbed embeds the chunks, which are saved in PostgreSQL with pgvector.
Question answering runs two searches. Exact-symbol search finds chunks whose symbol name matches the question, and semantic search compares the question embedding with the stored vectors. Exact matches are placed first and the remaining results are merged with Reciprocal Rank Fusion. The retrieved chunks become the context for the provider selected for that request.
Before an answer is returned, citation validation compares each generated reference with the chunks that were actually retrieved and removes references that do not match.
Web application / question answeringFIG. 02
Read diagram as text
A question is searched in two ways: exact-symbol search and semantic vector search. Exact matches are prioritized and the remaining results are merged with Reciprocal Rank Fusion. The retrieved context goes to the model provider selected for the request. Citation validation checks generated references against the retrieved chunks before the answer and its source references are returned.
Standalone agent architecture
Separately from the web application, a standalone LangGraph workflow explores agentic orchestration over the same retrieval capability. It is not connected to the public FastAPI routes; the application’s API documentation lists only the home page, /ingest and /ask.
Standalone LangGraph agentFIG. 03
Read diagram as text
The agent starts at the reasoner. A tool call runs search_codebase and returns to the reasoner; without a tool call, the critic reviews the response. If revision is needed, the critic returns it to the reasoner; otherwise it proceeds to finalize. Valid citations lead to the end. The first invalid citation check sends the agent back to the reasoner. A second consecutive invalid check pauses execution for human review, and the approval or rejection resumes finalization.
Reasoner
A tool-calling model that decides whether to search again or to answer.
Search tool
The existing retrieval capability exposed as an MCP tool and called through a real MCP client over stdio. The repository scope is injected by the graph and hidden from the model, so the model cannot override it.
Critic
A separate reviewer with no tool access. It returns structured feedback and can send an answer back to the reasoner for revision.
Finalize
Checks citations. A first invalid check retries with corrective feedback; a second consecutive invalid check pauses the run for human review. Approving or rejecting resumes finalization.
Checkpointing
PostgreSQL-backed checkpoints keep a paused run resumable after the process that paused it has exited.
Search cap
After five searches the reasoner is called with its tools removed, which forces a final answer. Live testing showed the model could otherwise repeat near-identical searches.
Citation handling differs between the two systems. In the web application, invalid references are removed from the answer. In the standalone agent, an invalid citation check triggers a retry and, if it repeats, escalation to a human reviewer.
Supporting evidence: the LangGraph workflow reference, an MCP Inspector session and a human-review run are shown in the screenshots section below.
Key engineering decisions and trade-offs
01
Structure-aware code chunking
Arbitrary line-based splitting can separate functions, classes and surrounding context. Python AST and JavaScript tree-sitter parsing extract meaningful units, and language dispatch supports both without separate retrieval pipelines.
Class and method chunks can intentionally overlap, and synthetic module chunks can have approximate line boundaries. Both are accepted trade-offs of keeping whole units together.
02
Hybrid retrieval with Reciprocal Rank Fusion
Semantic retrieval alone can miss identifiers, while exact matching is less effective for natural-language questions. The system runs both and merges their ranked lists with Reciprocal Rank Fusion, which avoids calibrating raw scores from two different search methods against each other.
03
Exact-match pinning
Testing showed that pure RRF could rank weaker results above a chunk whose symbol name exactly matched the question. Exact matches are now pinned to the top of the result list and RRF orders the rest.
04
Deterministic ranking
Equal RRF scores were originally ordered by insertion order, so the same question could produce a different ranking. Ties now break by agreement across result lists, then best individual rank, then chunk ID.
05
Citation validation and its limits
The system checks generated citations against the source chunks actually retrieved. Removing an invalid citation does not necessarily remove the unsupported statement it accompanied, and valid references do not establish that every generated claim is correct.
06
Asynchronous I/O
Database access, LLM requests and Git subprocess operations use async SQLAlchemy, asyncpg, AsyncGroq and asynchronous subprocess handling. CPU-bound parsing and embedding inference remain synchronous, and ingestion still holds its HTTP request open, so large repositories can still affect responsiveness.
07
Retrieval as an MCP tool
Exposing retrieval as a standalone MCP server with structured output lets other clients and agents use it independently of the web application. The LangGraph adapter library required MCP 1.x, so the server was moved to the 1.x FastMCP API after checking that the protocol-level behaviour was unchanged.
08
Persistent human review
A review that waits on a person must survive a process restart. PostgreSQL checkpointing, rather than in-memory state, lets a paused run be resumed from a different process, and both the approve and reject paths were exercised.
09
Live testing beyond mocks
Mocked tests passed while a real defect remained: the reasoner was never shown the retrieved code, only a count of results. It surfaced when a live model honestly reported that it lacked content the system had technically found. The fix was to return formatted code context in the tool result, and it is the clearest reason this project keeps both kinds of testing.
Evaluation and observability
I built a 40-question golden evaluation dataset: 15 straightforward lookups, 15 paraphrased or cross-chunk questions and 10 deliberately out-of-scope questions that test whether the system declines to answer.
Retrieval was measured with precision, recall and mean reciprocal rank against expected chunks. Generated answers were scored for faithfulness and relevance by a separate LLM judge running a different model from the production generator.
Two findings matter more than any score. First, weak retrieval numbers traced largely to the golden set itself: several hand-picked line ranges were narrower than any chunk the chunker can produce, so correct retrievals counted as misses. I logged this as a follow-up instead of adjusting the dataset after seeing the results. Second, one answer was a genuine hallucination: asked about an endpoint that does not exist, the model described agent internals as though they were a live route, and my judge under-penalized it.
For these reasons the aggregate scores are not presented here as application accuracy. The retrieval ground truth and the judge prompt both need further work.
40 questions in the golden evaluation dataset
Observability
The web request path is instrumented with Langfuse, so each /ask request produces one trace with retrieval and generation spans. The tracing was checked to degrade gracefully: a failed export does not affect the API response.
Deployment and verification
The application is containerized with Docker, and GitHub Actions runs its automated tests against PostgreSQL with pgvector. It was deployed on Render and checked with a real ingestion and question run through the browser interface.
A separate AWS exercise ran the application on EC2 with a private RDS PostgreSQL instance reachable only from the instance’s security group. The data was migrated with pg_dump and pg_restore and the application was verified against it. The exercise was temporary, and the AWS resources were afterwards removed to avoid ongoing cost.
The Render deployment is linked for reference. Its availability is not guaranteed, and a service that has been idle may take a while to respond.
Docker and CI
Containerized; GitHub Actions tests run against PostgreSQL with pgvector
Render
Historically documented deployment; hosted demo linked for reference
AWS EC2 and RDS
Completed exercise; resources torn down
Groq
Live-verified; default provider
Azure AI Foundry
Live-verified
AWS Bedrock
Implemented and tested with a mocked client; not live-verified
LangGraph agent
Verified live against Groq; standalone, not exposed by the web application
Known limitations and future improvements
Known limitations
Module-level citations are approximate, because the synthetic module chunk can contain non-contiguous lines.
Invalid citations are removed silently; the unsupported statement they accompanied remains in the answer.
Ingestion is synchronous request-and-response work, and CPU-bound parsing and embedding are not offloaded, so large repositories are slow.
Only public repositories are supported, and there are no repository size limits or rate limiting.
Only Python and JavaScript are supported.
AWS Bedrock has been tested only against a mocked client.
The evaluation ground truth uses hand-picked line ranges that need regenerating, and the judge prompt needs recalibrating.
Future improvements
Regenerate expected chunks from real chunk spans and recalibrate the judge prompt.
Move ingestion to background jobs with progress reporting and incremental indexing.
Show verified and unverified citations to users and highlight unsupported claims.
Improve duplicate suppression and add private-repository authentication.
Supporting screenshots
Genuine captures from the project. Select any image to open the viewer.
Codebase Q&A Assistant / Grounded answer Click to enlarge
A grounded answer with code excerpts and source references. Local file paths in the source list were redacted for publication; filenames and line ranges are preserved.
Codebase Q&A Assistant / API documentation Click to enlarge
Automatically generated API documentation for the web application: GET /, POST /ingest and POST /ask.
Codebase Q&A Assistant / MCP Inspector Click to enlarge
MCP Inspector connected to the standalone MCP server over STDIO, showing a successful tool call that returns structured results with file path, symbol, line range and citation.
Codebase Q&A Assistant / Agent workflow Click to enlarge
Reference rendering of the standalone LangGraph workflow (graph.py): reasoner, search tool, critic and finalize, with conditional retry and human-review paths.
Codebase Q&A Assistant / Human review Click to enlarge
Terminal output from a standalone-agent run that paused for human review and was resumed with a reject decision; the final answer was marked as not approved for delivery.
Codebase Q&A Assistant / Langfuse trace Click to enlarge
One historical request in Langfuse, with retrieval and generation spans. The model declined to describe the ingest function because the retrieved snippets did not include its implementation. The timings belong to this single request and are not averages.