Spaces:
Sleeping
Sleeping
Islam Mamedov commited on
Commit ·
b100e4f
1
Parent(s): 9e3e6cb
Complete ablation table: query rewriting 0.91/0.69, dense confirmed champion
Browse files7 unmodified lines8910111213147 unmodified linespinned: false---# FastAPI Codebase Q&ARAG system over FastAPI's source code, docs, and GitHub issues.Full write-up coming.7 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521537 unmodified linespinned: false---# ⚡ FastAPI Codebase Q&A — an eval-driven RAG systemAsk questions about the [FastAPI](https://github.com/fastapi/fastapi)codebase and get answers grounded in its actual source code, documentation,and GitHub issues — with citations linking to the exact lines, and honestrefusals when the corpus doesn't contain the answer.**Live demo:** https://huggingface.co/spaces/Pace200413/fastapi-codebase-qaEvery architectural decision in this project was made by measuring, notguessing: a hand-labeled 42-question eval set gates every change, and theablation results below include the things that *didn't* work and why.## Architecture```GitHub repo ──► Ingestion ──► Chunking ──► Indexing ──► Retrieval ──► Generationcode clone AST-aware ChromaDB dense LLM withdocs (en) API pull (tree-sitter) bge-small (winner of citations +issues resumable md-aware + BM25 6 ablations) refusal rulesissue-aware│ │└────── Eval harness ◄─────┘recall@5 · MRR · faithfulness ·correctness · refusal accuracy```- **Corpus:** 46 source files, 161 English docs, 175 closed issues →**1,352 chunks** (363 code, 814 doc, 175 issue)- **Chunking:** tree-sitter AST parsing — one chunk per function/class,classes >150 lines split per-method, every chunk carries a context header(`# File: fastapi/routing.py | Symbol: APIRouter`) and exact line numbersfor citations- **Stack:** Python, ChromaDB, sentence-transformers (`bge-small-en-v1.5`),rank-bm25, Groq (LLM), Streamlit — total cost: $0## Evaluation42 hand-labeled questions across four categories: **api_usage** (16),**behavior** (11), **location** ("where is X defined", 8), and**unanswerable** (7 — questions FastAPI's corpus genuinely can't answer,to measure refusal). Gold labels mark which file/symbol contains theanswer; retrieval is scored by recall@5 and MRR, generation by anLLM-as-judge (faithfulness, correctness) plus string-matched refusals.### Retrieval ablations| Configuration | recall@5 | MRR | Verdict ||---|---|---|---|| **dense (bge-small)** | **0.91** | **0.71** | **winner — shipped** || hybrid (dense + BM25, RRF) | 0.86 | 0.70 | BM25 noise displaces gold chunks || hybrid, weighted RRF 2:1 | 0.86 | 0.71 | weighting doesn't recover recall || dense + bge-reranker-base | 0.91 | 0.63 | reranker *hurts* ranking || dense + bge-reranker-v2-m3 | 0.83 | 0.67 | newer reranker also hurts || hybrid + bge-reranker-v2-m3 | 0.86 | 0.68 | — || dense + LLM query rewriting | 0.91 | 0.69 | no gain; noisy expansions add drift |**Why hybrid lost:** diagnostic runs showed dense@20 = hybrid@20 = 0.97 —BM25 contributed zero unique gold candidates on this corpus, while itscommon-token matches (issue chunks full of "request", "body", "json")crowded correct chunks out of the top 5.**Why the rerankers lost:** both generations of cross-encoder demoted rawcode chunks on "where is X defined" questions. A code chunk *is* theanswer without *discussing* the answer — and rerankers are trained toscore passages that discuss. dense@20 recall of 0.97 vs reranked@5 recallof 0.83–0.86 shows they were given the right candidates and ranked themworse.### Generation (dense, llama-4-scout via Groq)| Metric | Score ||---|---|| Faithfulness (LLM judge) | 0.89 || Correctness (LLM judge) | 0.91 || Refusal accuracy (7 unanswerable questions) | 7/7 |Refusal was the most fragile metric: it swung 6/7 → 0/7 → 7/7 across threesystem-prompt variants. The fix was naming the failure mode in the prompt("the context chunks are search results: they may be loosely RELATED tothe question without actually answering it"). Without the eval harnessthis regression would have shipped silently.A score-threshold refusal gate was also tested and **rejected**: top-1similarity scores for answerable (0.74–0.89) and unanswerable (0.72–0.79)questions overlap heavily — semantic similarity can't distinguish "relatedto FastAPI" from "answerable from FastAPI's corpus".## Failure analysis (what still breaks)1. **Common-token queries.** "Where are the Query, Path, and Body parameterfunctions defined?" (`fastapi/param_functions.py`) misses even at k=20in every configuration — all its query tokens are ubiquitous. LLM queryrewriting that injects likely identifiers is the targeted fix.2. **Docs without code.** FastAPI's docs embed examples via`{* ../../docs_src/... *}` include-directives; the referenced snippetsaren't inlined into chunks, so some answers describe code they can'tshow. Resolving the includes at chunking time is the top corpusimprovement.3. **Judge strictness.** Spot-checking answers flagged `[incorrect]` showedat least one (JWT auth) is actually correct — the LLM judge penalizesanswers referencing code the truncated context implies but doesn'tshow. Judge scores are treated as directional, not absolute.## Engineering notes- **Idempotent, resumable ingestion** — issues already fetched are skipped,so network failures mid-run just need a re-run- **Everything cached** — LLM answers, judgments, and query rewrites arecached to disk keyed by (model, prompt), making eval re-runs free onGroq's rate-limited free tier- **Rate-limit resilience** — retry with backoff; eval survived TPM/TPDlimits and a mid-run model deprecation (Groq retired llama-3.3 mid-sprint)- **Self-building deploy** — the HF Space rebuilds the vector index fromcommitted `chunks.jsonl` on first boot; no binary artifacts in git- **Unit-tested chunkers** and an eval suite that doubles as a regressiongate## Run it yourself```bashgit clone https://github.com/Pace200413/codebase-rag && cd codebase-ragpython -m venv .venv && source .venv/bin/activatepip install -r requirements.txt PyGithub tree-sitter tree-sitter-python pytestecho "GROQ_API_KEY=gsk_..." > .env # free key: console.groq.compython src/ingest.py --repo fastapi/fastapi # needs GITHUB_TOKEN for issuespython src/chunk.pypython src/index.pypython src/ask.py "How do I return a custom status code?"python src/eval.py --mode dense --answers # reproduce the numbers abovestreamlit run app.py```## What I'd build next- Resolve `docs_src` include-directives into doc chunks (highest-impactcorpus fix)- Make ingestion repo-agnostic (`--repo any/repo`) — turn the project intoa tool- Embedding-model ablation (bge-small vs bge-base vs code-specific models)- Ingest GitHub Discussions, where most FastAPI Q&A actually lives- CI job that fails the build if recall@5 drops below baseline
README.md+142-3