Spaces:
Sleeping
Sleeping
Islam Mamedov commited on
Commit ·
e5e7d99
1
Parent(s): b100e4f
Ship chat UI, update project links, and add MIT license
Browse files123456789101112131415161718192021MIT License
Copyright (c) 2026 Islam Mamedov
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.14 unmodified lines15161718192021107 unmodified lines12913013113213313413514 unmodified linesand 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 the107 unmodified lines## 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.com14 unmodified lines15161718192021107 unmodified lines12913013113213313413514 unmodified linesand 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/islam-mamedov/fastapi-codebase-qaEvery architectural decision in this project was made by measuring, notguessing: a hand-labeled 42-question eval set gates every change, and the107 unmodified lines## Run it yourself```bashgit clone https://github.com/islam-mamedov/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.com
9 unmodified lines10111213141516 unmodified lines3233343536373814 unmodified lines535455565758596061626364652 unmodified lines686970717273747576777879808182831 unmodified line8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321339 unmodified linesimport osimport sysfrom pathlib import Pathfrom dotenv import load_dotenv16 unmodified lines]st.set_page_config(page_title="FastAPI Codebase Q&A", page_icon="⚡",layout="wide")@st.cache_resource(show_spinner="First boot: building the search index "14 unmodified linesensure_index()st.title("⚡ FastAPI Codebase Q&A")st.caption("Retrieval-augmented answers over FastAPI's source code, docs, ""and GitHub issues — every claim cited, honest refusals when ""the corpus doesn't know.")with st.sidebar:st.header("How it works")st.markdown("1. Your question is embedded (`bge-small-en-v1.5`)\n""2. Top-5 chunks retrieved from ~1,350 AST-aware chunks "2 unmodified lines"4. Citations link to the exact GitHub lines")mode = st.selectbox("Retrieval mode", ["dense", "dense_rw", "hybrid"],help="dense won the ablation; others shown for ""comparison")st.divider()st.markdown("**Eval results (42-question set)**\n\n""recall@5 **0.91** · MRR **0.71**\n\n""faithful **0.89** · correct **0.91** · refusal **7/7**")st.markdown("[Source & write-up]""(https://github.com/Pace200413/codebase-rag)")@st.cache_data(show_spinner=False)1 unmodified linereturn retrieve(question, k=5, mode=mode)def generate(question: str, hits: list[dict]) -> str:from groq import Groqapi_key = os.environ.get("GROQ_API_KEY")if not api_key:st.error("GROQ_API_KEY is not set.")st.stop()client = Groq(api_key=api_key)response = client.chat.completions.create(model=LLM_MODEL,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": build_prompt(question, hits)},],temperature=0.1,)return response.choices[0].message.content# --- example question buttons ---st.write("Try one:")cols = st.columns(len(EXAMPLES))for col, ex in zip(cols, EXAMPLES):if col.button(ex, use_container_width=True):st.session_state["question"] = exquestion = st.text_input("Ask about FastAPI's codebase",key="question",placeholder="How do I handle file uploads?")if question:with st.spinner("Searching the codebase..."):hits = cached_retrieve(question, mode)with st.spinner("Writing the answer..."):answer = generate(question, hits)st.markdown(answer)st.divider()st.subheader("Sources")for i, h in enumerate(hits, 1):meta = h["meta"]label = (f"[{i}] {meta['source_type']} · {meta['path']}"+ (f" · {meta['symbol']}" if meta["symbol"] else ""))with st.expander(label):st.markdown(f"[Open on GitHub]({meta['url']})")st.code(h["text"][:1500])9 unmodified lines1011121314151616 unmodified lines33343536373839404142434445464748495051525354555614 unmodified lines7172737475767778792 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111 unmodified line1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002019 unmodified linesimport osimport sysimport timefrom pathlib import Pathfrom dotenv import load_dotenv16 unmodified lines]st.set_page_config(page_title="FastAPI Codebase Q&A", page_icon="⚡",layout="centered")st.markdown("""<style>.stButton > button {border-radius: 12px;border: 1px solid rgba(128, 128, 128, 0.35);font-size: 0.85rem;transition: border-color 0.2s;}.stButton > button:hover { border-color: #f0b429; color: #f0b429; }[data-testid="stMetricValue"] { font-size: 1.4rem; }[data-testid="stExpander"] {border-radius: 10px;border: 1px solid rgba(128, 128, 128, 0.25);}</style>""", unsafe_allow_html=True)@st.cache_resource(show_spinner="First boot: building the search index "14 unmodified linesensure_index()# ---------------- sidebar ----------------with st.sidebar:st.header("⚙️ How it works")st.markdown("1. Your question is embedded (`bge-small-en-v1.5`)\n""2. Top-5 chunks retrieved from ~1,350 AST-aware chunks "2 unmodified lines"4. Citations link to the exact GitHub lines")mode = st.selectbox("Retrieval mode", ["dense", "dense_rw", "hybrid"],help="dense won a 7-configuration ablation; ""others shown for comparison")st.divider()st.subheader("📊 Eval (42-question benchmark)")c1, c2 = st.columns(2)c1.metric("recall@5", "0.91")c2.metric("MRR", "0.71")c3, c4 = st.columns(2)c3.metric("correct", "0.91")c4.metric("refusal", "7/7")st.divider()st.markdown("[💻 Source & write-up]""(https://github.com/Pace200413/codebase-rag)")if st.button("🗑 Clear conversation", use_container_width=True):st.session_state.messages = []st.rerun()# ---------------- header ----------------st.title("⚡ FastAPI Codebase Q&A")st.caption("Ask anything about FastAPI's source code, docs, and GitHub ""issues. Every claim is cited. When the corpus doesn't know, ""it says so.")# ---------------- helpers ----------------@st.cache_data(show_spinner=False)1 unmodified linereturn retrieve(question, k=5, mode=mode)def stream_answer(question: str, hits: list[dict]):"""Yield the answer token by token (looks alive, no behavior change)."""from groq import Groqapi_key = os.environ.get("GROQ_API_KEY")if not api_key:st.error("GROQ_API_KEY is not set.")st.stop()client = Groq(api_key=api_key)stream = client.chat.completions.create(model=LLM_MODEL,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": build_prompt(question, hits)},],temperature=0.1,stream=True,)for chunk in stream:delta = chunk.choices[0].delta.contentif delta:yield deltadef render_sources(hits: list[dict]) -> None:st.markdown("##### 📎 Sources")for i, h in enumerate(hits, 1):meta = h["meta"]icon = {"code": "🧩", "doc": "📄", "issue": "🐛"}.get(meta["source_type"], "📄")label = (f"{icon} [{i}] {meta['path']}"+ (f" · {meta['symbol']}" if meta["symbol"] else ""))with st.expander(label):st.markdown(f"[Open on GitHub ↗]({meta['url']})")st.code(h["text"][:1200])# ---------------- conversation state ----------------if "messages" not in st.session_state:st.session_state.messages = []# render historyfor msg in st.session_state.messages:with st.chat_message(msg["role"]):st.markdown(msg["content"])if msg.get("sources"):render_sources(msg["sources"])if msg.get("timing"):st.caption(msg["timing"])# example buttons (only before the first question, to keep the video clean)pending = Noneif not st.session_state.messages:st.write("**Try one:**")cols = st.columns(2)for i, ex in enumerate(EXAMPLES):if cols[i % 2].button(ex, use_container_width=True):pending = exprompt = st.chat_input("Ask about FastAPI's codebase...") or pendingif prompt:st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)with st.chat_message("assistant"):t0 = time.perf_counter()with st.spinner("Searching 1,352 chunks..."):hits = cached_retrieve(prompt, mode)t_retrieve = time.perf_counter() - t0t1 = time.perf_counter()answer = st.write_stream(stream_answer(prompt, hits))t_answer = time.perf_counter() - t1timing = (f"retrieved in {t_retrieve:.2f}s · "f"answered in {t_answer:.1f}s · mode: {mode}")st.caption(timing)render_sources(hits)st.session_state.messages.append({"role": "assistant","content": answer,"sources": hits,"timing": timing,})
LICENSEAdded+21
README.md+2-2
app.py+110-42