Spaces:
Sleeping
Sleeping
Commit ·
8e72e1f
0
Parent(s):
Codebase Intelligence Agent: code-aware RAG + test-gen agent + eval
Browse files- .gitignore +10 -0
- README.md +138 -0
- app.py +106 -0
- data/eval/testset.json +22 -0
- evaluate.py +79 -0
- requirements.txt +12 -0
- smoke_test.py +63 -0
- src/__init__.py +0 -0
- src/agent/__init__.py +0 -0
- src/agent/tools.py +91 -0
- src/agent/workflow.py +79 -0
- src/evaluation/__init__.py +0 -0
- src/evaluation/evaluator.py +74 -0
- src/generation/__init__.py +0 -0
- src/ingestion/__init__.py +0 -0
- src/ingestion/chunker.py +64 -0
- src/ingestion/parser.py +130 -0
- src/ingestion/scanner.py +98 -0
- src/rag/__init__.py +0 -0
- src/rag/answerer.py +80 -0
- src/rag/bm25_search.py +40 -0
- src/rag/embedder.py +24 -0
- src/rag/hybrid_search.py +74 -0
- src/rag/reranker.py +56 -0
- src/rag/vector_store.py +63 -0
.gitignore
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
venv/
|
| 3 |
+
__pycache__/
|
| 4 |
+
*.pyc
|
| 5 |
+
.env
|
| 6 |
+
data/raw_documents/
|
| 7 |
+
data/eval/results*.json
|
| 8 |
+
.DS_Store
|
| 9 |
+
|
| 10 |
+
.vscode
|
README.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Codebase Intelligence Agent
|
| 3 |
+
emoji: 🧭
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: streamlit
|
| 7 |
+
app_file: app.py
|
| 8 |
+
python_version: "3.11"
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Codebase Intelligence Agent
|
| 13 |
+
|
| 14 |
+
An AI assistant that understands a Python codebase. Upload a repository, ask
|
| 15 |
+
questions and get answers with **exact file + line citations**, or have the
|
| 16 |
+
**agent generate pytest tests** for any function by reading its real source.
|
| 17 |
+
|
| 18 |
+
Built around code-aware retrieval (tree-sitter AST chunking, not naive text
|
| 19 |
+
splitting) and measured with an evaluation harness.
|
| 20 |
+
|
| 21 |
+
## Demo
|
| 22 |
+
|
| 23 |
+

|
| 24 |
+
|
| 25 |
+
- **Ask the codebase** — "where are JWT tokens created?" → grounded answer citing
|
| 26 |
+
`app/core/security.py:38-44`, with the actual code shown as a source.
|
| 27 |
+
- **Generate tests** — name a function → a tool-calling agent reads its real
|
| 28 |
+
source and dependencies, then writes pytest tests grounded in that code.
|
| 29 |
+
|
| 30 |
+
## Evaluation
|
| 31 |
+
|
| 32 |
+
Measured on a real FastAPI backend (74 files, 369 definitions), deterministic
|
| 33 |
+
(`temperature=0`):
|
| 34 |
+
|
| 35 |
+
| Metric | Result |
|
| 36 |
+
|---|---|
|
| 37 |
+
| File-level retrieval accuracy | **90%** |
|
| 38 |
+
| Function-level retrieval accuracy | **75%** |
|
| 39 |
+
| Citation accuracy (answer cites the right file) | **75%** |
|
| 40 |
+
| Median latency | **~3.3s / query** |
|
| 41 |
+
|
| 42 |
+
> Honest miss worth noting: "where is the FastAPI app created?" misses because
|
| 43 |
+
> the app is instantiated at module level (`app = FastAPI()`) rather than in a
|
| 44 |
+
> named function — module-level instantiation is harder to retrieve than named
|
| 45 |
+
> symbols. Indexing top-level assignments specially is the fix (roadmap).
|
| 46 |
+
|
| 47 |
+
## How it works
|
| 48 |
+
|
| 49 |
+
```
|
| 50 |
+
ZIP repo
|
| 51 |
+
|
|
| 52 |
+
v
|
| 53 |
+
File scanner skip venv/.git/__pycache__/node_modules, size cap
|
| 54 |
+
|
|
| 55 |
+
v
|
| 56 |
+
tree-sitter parser AST -> functions, classes, methods (+ exact line numbers)
|
| 57 |
+
|
|
| 58 |
+
v
|
| 59 |
+
Code chunker one chunk per definition + file/line metadata
|
| 60 |
+
|
|
| 61 |
+
v
|
| 62 |
+
Embeddings -------\
|
| 63 |
+
| \
|
| 64 |
+
v v
|
| 65 |
+
FAISS (semantic) BM25 (code-aware tokenizer: matches `jwt.encode`)
|
| 66 |
+
\ /
|
| 67 |
+
v v
|
| 68 |
+
Hybrid retrieval -> cross-encoder rerank -> top-5
|
| 69 |
+
|
|
| 70 |
+
+--------+--------+
|
| 71 |
+
| |
|
| 72 |
+
v v
|
| 73 |
+
Grounded Q&A Test-gen agent
|
| 74 |
+
(file:line cites) (tool-calling loop)
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
**Why it's code-aware:** chunking by AST means each chunk is a whole function or
|
| 78 |
+
class with its exact line range — so citations are precise and un-hallucinatable,
|
| 79 |
+
and retrieval matches real code units instead of arbitrary text windows. The
|
| 80 |
+
code-aware BM25 tokenizer splits on symbols, so exact searches like `jwt.encode`
|
| 81 |
+
actually match.
|
| 82 |
+
|
| 83 |
+
**The agent:** given a target function, the LLM calls `get_definition` and
|
| 84 |
+
`search_code` to read the real source, then writes pytest tests grounded in it —
|
| 85 |
+
a tool-calling loop (no framework), the model planning and acting rather than
|
| 86 |
+
answering in one shot.
|
| 87 |
+
|
| 88 |
+
## Tech stack
|
| 89 |
+
|
| 90 |
+
Python · Streamlit · tree-sitter · sentence-transformers · FAISS · rank-bm25 ·
|
| 91 |
+
cross-encoder reranker · OpenAI (`gpt-4.1-mini`, temperature 0)
|
| 92 |
+
|
| 93 |
+
## Run locally
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
python -m venv .venv && .venv\Scripts\activate # Windows
|
| 97 |
+
pip install -r requirements.txt
|
| 98 |
+
echo OPENAI_API_KEY=sk-your-key > .env
|
| 99 |
+
streamlit run app.py
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
## Evaluate
|
| 103 |
+
|
| 104 |
+
```bash
|
| 105 |
+
python evaluate.py --repo path/to/python/repo --testset data/eval/testset.json
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
## Project structure
|
| 109 |
+
|
| 110 |
+
```
|
| 111 |
+
src/
|
| 112 |
+
├── ingestion/ scanner, tree-sitter parser, chunker
|
| 113 |
+
├── rag/ embedder, FAISS, BM25, hybrid, reranker, answerer
|
| 114 |
+
├── agent/ tools (search_code, get_definition) + tool-calling workflow
|
| 115 |
+
└── evaluation/ eval harness
|
| 116 |
+
app.py Streamlit UI (Ask + Generate tests)
|
| 117 |
+
evaluate.py eval CLI
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
## Limitations & roadmap
|
| 121 |
+
|
| 122 |
+
v1 is a deliberate vertical slice. Known limits and next steps:
|
| 123 |
+
|
| 124 |
+
- **Python only** — multi-language via more tree-sitter grammars.
|
| 125 |
+
- **ZIP upload only** — GitHub URL ingestion (clone) next.
|
| 126 |
+
- **Module-level symbols** (e.g. `app = FastAPI()`) retrieve worse than named
|
| 127 |
+
functions — index top-level assignments specially.
|
| 128 |
+
- **Citation accuracy is a strict string check** — the answer must contain the
|
| 129 |
+
filename; LLM-as-judge grading would measure correctness more fairly.
|
| 130 |
+
- **General-purpose embeddings** — a code-specific embedding model
|
| 131 |
+
(`jina-embeddings-v2-base-code`) would likely improve retrieval.
|
| 132 |
+
- Future: code graph (call/import relationships), PR review mode, bug-fix tool,
|
| 133 |
+
documentation agent.
|
| 134 |
+
|
| 135 |
+
## About
|
| 136 |
+
|
| 137 |
+
A self-directed project focused on code-aware RAG, tool-calling agents, and
|
| 138 |
+
measured evaluation — not a generic "chat with your repo" demo.
|
app.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import hashlib
|
| 3 |
+
import streamlit as st
|
| 4 |
+
|
| 5 |
+
st.set_page_config(page_title="Codebase Intelligence Agent", page_icon="🧭", layout="wide")
|
| 6 |
+
|
| 7 |
+
# Bridge HF/Streamlit secrets to env (safe if neither exists).
|
| 8 |
+
try:
|
| 9 |
+
if not os.getenv("OPENAI_API_KEY") and "OPENAI_API_KEY" in st.secrets:
|
| 10 |
+
os.environ["OPENAI_API_KEY"] = st.secrets["OPENAI_API_KEY"]
|
| 11 |
+
except Exception:
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
st.title("🧭 Codebase Intelligence Agent")
|
| 15 |
+
st.write("Upload a Python repository (ZIP) and ask questions — answers come with exact file/line citations.")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# ---- models: loaded once per session ----
|
| 19 |
+
@st.cache_resource(show_spinner="Loading models (first run only)...")
|
| 20 |
+
def load_models():
|
| 21 |
+
from src.rag.embedder import Embedder
|
| 22 |
+
from src.rag.reranker import Reranker
|
| 23 |
+
from src.rag.answerer import Answerer
|
| 24 |
+
return {"embedder": Embedder(), "reranker": Reranker(), "answerer": Answerer()}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---- ingest + chunk, cached per uploaded file ----
|
| 28 |
+
@st.cache_data(show_spinner="Scanning and parsing repository...")
|
| 29 |
+
def ingest(file_bytes, file_name):
|
| 30 |
+
import tempfile
|
| 31 |
+
from src.ingestion.scanner import scan_repo
|
| 32 |
+
from src.ingestion.chunker import chunk_repo
|
| 33 |
+
|
| 34 |
+
tmp_zip = os.path.join(tempfile.mkdtemp(), file_name)
|
| 35 |
+
with open(tmp_zip, "wb") as f:
|
| 36 |
+
f.write(file_bytes)
|
| 37 |
+
files, _ = scan_repo(tmp_zip)
|
| 38 |
+
chunks = chunk_repo(files)
|
| 39 |
+
return chunks, len(files)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ---- build index, cached per file (underscore args skip hashing) ----
|
| 43 |
+
@st.cache_resource(show_spinner="Building search index...")
|
| 44 |
+
def build_index(file_hash, _chunks, _embeddings):
|
| 45 |
+
from src.rag.vector_store import VectorStore
|
| 46 |
+
from src.rag.bm25_search import BM25Retriever
|
| 47 |
+
from src.rag.hybrid_search import HybridRetriever
|
| 48 |
+
vs = VectorStore()
|
| 49 |
+
vs.build(_embeddings, _chunks)
|
| 50 |
+
return HybridRetriever(vs, BM25Retriever(_chunks))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@st.cache_data(show_spinner="Embedding code...")
|
| 54 |
+
def embed(file_hash, _texts, _embedder):
|
| 55 |
+
return _embedder.create_embeddings(_texts)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
uploaded = st.file_uploader("Upload repository ZIP", type=["zip"])
|
| 59 |
+
|
| 60 |
+
if uploaded:
|
| 61 |
+
file_bytes = uploaded.getvalue()
|
| 62 |
+
file_hash = hashlib.md5(file_bytes).hexdigest()
|
| 63 |
+
|
| 64 |
+
models = load_models()
|
| 65 |
+
chunks, n_files = ingest(file_bytes, uploaded.name)
|
| 66 |
+
texts = [c["chunk_text"] for c in chunks]
|
| 67 |
+
embeddings = embed(file_hash, texts, models["embedder"])
|
| 68 |
+
hybrid = build_index(file_hash, chunks, embeddings)
|
| 69 |
+
|
| 70 |
+
st.success(f"Indexed {len(chunks)} definitions from {n_files} files. Ask away.")
|
| 71 |
+
|
| 72 |
+
ask_tab, test_tab = st.tabs(["💬 Ask the codebase", "🧪 Generate tests"])
|
| 73 |
+
|
| 74 |
+
with ask_tab:
|
| 75 |
+
query = st.text_input("Ask about the codebase", placeholder="e.g. where are JWT tokens created?")
|
| 76 |
+
if query:
|
| 77 |
+
with st.spinner("Searching and answering..."):
|
| 78 |
+
results = hybrid.search(query, models["embedder"].create_embeddings([query])[0], k=10)
|
| 79 |
+
results = models["reranker"].rerank(query, results)
|
| 80 |
+
result = models["answerer"].answer(query, results[:5])
|
| 81 |
+
|
| 82 |
+
st.subheader("Answer")
|
| 83 |
+
st.write(result["answer"])
|
| 84 |
+
|
| 85 |
+
st.subheader("Sources")
|
| 86 |
+
for s in result["sources"]:
|
| 87 |
+
label = f"📄 {s['file']}:{s['start_line']}-{s['end_line']} · {s['type']} {s['name']}"
|
| 88 |
+
with st.expander(label):
|
| 89 |
+
st.code(s["code"], language="python")
|
| 90 |
+
|
| 91 |
+
with test_tab:
|
| 92 |
+
st.write("Enter a function or class name and the agent will read its real source and write pytest tests.")
|
| 93 |
+
target = st.text_input("Function / class name", placeholder="e.g. create_access_token")
|
| 94 |
+
if target and st.button("Generate tests"):
|
| 95 |
+
from src.agent.tools import CodeTools
|
| 96 |
+
from src.agent.workflow import TestAgent
|
| 97 |
+
with st.spinner("Agent reading the code and writing tests..."):
|
| 98 |
+
tools = CodeTools(chunks, models["embedder"], hybrid, models["reranker"])
|
| 99 |
+
tests = TestAgent(tools).generate_tests(target)
|
| 100 |
+
st.code(tests.replace("```python", "").replace("```", "").strip(), language="python")
|
| 101 |
+
|
| 102 |
+
with st.expander("Repository overview"):
|
| 103 |
+
by_type = {}
|
| 104 |
+
for c in chunks:
|
| 105 |
+
by_type[c["type"]] = by_type.get(c["type"], 0) + 1
|
| 106 |
+
st.write({"files": n_files, "definitions": len(chunks), **by_type})
|
data/eval/testset.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{"question": "Where are JWT tokens created?", "expected_file": "security.py", "expected_name": "create_access_token"},
|
| 3 |
+
{"question": "How are JWT tokens decoded or verified?", "expected_file": "security.py", "expected_name": "decode_access_token"},
|
| 4 |
+
{"question": "Where is a new user registered?", "expected_file": "auth.py", "expected_name": "register"},
|
| 5 |
+
{"question": "How does the AI planner generate tasks?", "expected_file": "tasks.py", "expected_name": "plan"},
|
| 6 |
+
{"question": "Where is the database connection or session set up?", "expected_file": "database.py", "expected_name": ""},
|
| 7 |
+
{"question": "How is the current authenticated user resolved from a request?", "expected_file": "auth.py", "expected_name": ""},
|
| 8 |
+
{"question": "Where are application settings and configuration loaded?", "expected_file": "config.py", "expected_name": ""},
|
| 9 |
+
{"question": "How is a password hashed?", "expected_file": "security.py", "expected_name": ""},
|
| 10 |
+
{"question": "How is a password verified against its hash?", "expected_file": "security.py", "expected_name": ""},
|
| 11 |
+
{"question": "Where is the focus timer or pomodoro session logic?", "expected_file": "focus.py", "expected_name": ""},
|
| 12 |
+
{"question": "How is a task marked complete?", "expected_file": "tasks.py", "expected_name": ""},
|
| 13 |
+
{"question": "Where is partner matching handled?", "expected_file": "matching.py", "expected_name": ""},
|
| 14 |
+
{"question": "How are study rooms joined?", "expected_file": "rooms.py", "expected_name": ""},
|
| 15 |
+
{"question": "Where is the productivity score computed?", "expected_file": "focus.py", "expected_name": ""},
|
| 16 |
+
{"question": "How is the user profile or personality created?", "expected_file": "profile.py", "expected_name": ""},
|
| 17 |
+
{"question": "Where is the StudyRoom database model defined?", "expected_file": "study_room.py", "expected_name": ""},
|
| 18 |
+
{"question": "How does real-time messaging or websockets work?", "expected_file": "socket.py", "expected_name": ""},
|
| 19 |
+
{"question": "Where is the FastAPI app created and configured?", "expected_file": "main.py", "expected_name": ""},
|
| 20 |
+
{"question": "How are API routes registered?", "expected_file": "main.py", "expected_name": ""},
|
| 21 |
+
{"question": "Where is the coach or AI feedback logic?", "expected_file": "coach.py", "expected_name": ""}
|
| 22 |
+
]
|
evaluate.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Run the codebase-agent evaluation over a repo + test set.
|
| 3 |
+
|
| 4 |
+
Usage (from project root, venv active, OPENAI_API_KEY set):
|
| 5 |
+
python evaluate.py --repo path/to/repo_dir --testset data/eval/testset.json
|
| 6 |
+
|
| 7 |
+
Generation is deterministic (temperature=0 in answerer.py) so results are
|
| 8 |
+
reproducible. Override retrieval depth with --retrieve / --top to compare configs.
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
from src.ingestion.scanner import scan_python_files
|
| 15 |
+
from src.ingestion.chunker import chunk_repo
|
| 16 |
+
from src.rag.embedder import Embedder
|
| 17 |
+
from src.rag.vector_store import VectorStore
|
| 18 |
+
from src.rag.bm25_search import BM25Retriever
|
| 19 |
+
from src.rag.hybrid_search import HybridRetriever
|
| 20 |
+
from src.rag.reranker import Reranker
|
| 21 |
+
from src.rag.answerer import Answerer
|
| 22 |
+
from src.evaluation.evaluator import CodeEvaluator
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def build_pipeline(repo_dir, retrieve_k, top_n):
|
| 26 |
+
chunks = chunk_repo(scan_python_files(repo_dir))
|
| 27 |
+
embedder = Embedder()
|
| 28 |
+
embeddings = embedder.create_embeddings([c["chunk_text"] for c in chunks])
|
| 29 |
+
vs = VectorStore()
|
| 30 |
+
vs.build(embeddings, chunks)
|
| 31 |
+
hybrid = HybridRetriever(vs, BM25Retriever(chunks))
|
| 32 |
+
evaluator = CodeEvaluator(embedder, hybrid, Reranker(), Answerer(), retrieve_k, top_n)
|
| 33 |
+
return evaluator, len(chunks)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
ap = argparse.ArgumentParser()
|
| 38 |
+
ap.add_argument("--repo", required=True, help="path to a Python repo directory")
|
| 39 |
+
ap.add_argument("--testset", required=True, help="JSON list of test questions")
|
| 40 |
+
ap.add_argument("--retrieve", type=int, default=10)
|
| 41 |
+
ap.add_argument("--top", type=int, default=5)
|
| 42 |
+
ap.add_argument("--out", default="data/eval/results.json")
|
| 43 |
+
args = ap.parse_args()
|
| 44 |
+
|
| 45 |
+
with open(args.testset, encoding="utf-8") as f:
|
| 46 |
+
testset = json.load(f)
|
| 47 |
+
|
| 48 |
+
print(f"Building index for {args.repo} ...")
|
| 49 |
+
evaluator, n_chunks = build_pipeline(args.repo, args.retrieve, args.top)
|
| 50 |
+
print(f"Indexed {n_chunks} chunks. Running {len(testset)} questions "
|
| 51 |
+
f"(retrieve={args.retrieve}, top={args.top})...\n")
|
| 52 |
+
|
| 53 |
+
rows, summary = evaluator.evaluate(testset)
|
| 54 |
+
|
| 55 |
+
for r in rows:
|
| 56 |
+
fh = "Y" if r["file_hit"] else "."
|
| 57 |
+
nh = ("Y" if r["name_hit"] else ".") if r["name_hit"] is not None else "-"
|
| 58 |
+
ch = "Y" if r["citation_ok"] else "."
|
| 59 |
+
print(f"[file {fh}][fn {nh}][cite {ch}] {r['seconds']:5.2f}s | {r['question'][:55]}")
|
| 60 |
+
|
| 61 |
+
print("\n" + "=" * 50)
|
| 62 |
+
print("SUMMARY")
|
| 63 |
+
print("=" * 50)
|
| 64 |
+
print(f"Questions ............ {summary['questions']}")
|
| 65 |
+
print(f"File accuracy ........ {summary['file_accuracy']}%")
|
| 66 |
+
if summary["function_accuracy"] is not None:
|
| 67 |
+
print(f"Function accuracy .... {summary['function_accuracy']}%")
|
| 68 |
+
print(f"Citation accuracy .... {summary['citation_accuracy']}%")
|
| 69 |
+
print(f"Median latency ....... {summary['median_latency']}s")
|
| 70 |
+
|
| 71 |
+
os.makedirs(os.path.dirname(args.out), exist_ok=True)
|
| 72 |
+
with open(args.out, "w", encoding="utf-8") as f:
|
| 73 |
+
json.dump({"settings": vars(args), "summary": summary, "rows": rows},
|
| 74 |
+
f, indent=2, ensure_ascii=False)
|
| 75 |
+
print(f"\nFull results saved to {args.out}")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
openai==1.51.0
|
| 3 |
+
python-dotenv==1.0.1
|
| 4 |
+
numpy==1.26.4
|
| 5 |
+
faiss-cpu==1.8.0.post1
|
| 6 |
+
rank-bm25==0.2.2
|
| 7 |
+
sentence-transformers==3.0.1
|
| 8 |
+
transformers==4.44.2
|
| 9 |
+
torch==2.4.1+cpu
|
| 10 |
+
sentencepiece==0.2.0
|
| 11 |
+
tree-sitter==0.23.2
|
| 12 |
+
tree-sitter-python==0.23.6
|
smoke_test.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Quick end-to-end check of the code-aware retrieval pipeline on a real repo.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python smoke_test.py <repo_dir> "your question"
|
| 6 |
+
|
| 7 |
+
Example:
|
| 8 |
+
python smoke_test.py C:\\Users\\aisha\\ai_projects\\studysync_backend\\studysync\\backend "where are JWT tokens created"
|
| 9 |
+
"""
|
| 10 |
+
import sys
|
| 11 |
+
from src.agent.tools import CodeTools
|
| 12 |
+
from src.agent.workflow import TestAgent
|
| 13 |
+
from src.ingestion.scanner import scan_python_files
|
| 14 |
+
from src.ingestion.chunker import chunk_repo
|
| 15 |
+
from src.rag.embedder import Embedder
|
| 16 |
+
from src.rag.bm25_search import BM25Retriever
|
| 17 |
+
from src.rag.vector_store import VectorStore
|
| 18 |
+
from src.rag.hybrid_search import HybridRetriever
|
| 19 |
+
from src.rag.reranker import Reranker
|
| 20 |
+
from src.rag.answerer import Answerer
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
if len(sys.argv) < 3:
|
| 25 |
+
print('usage: python smoke_test.py <repo_dir> "your question"')
|
| 26 |
+
sys.exit(1)
|
| 27 |
+
|
| 28 |
+
repo_dir = sys.argv[1]
|
| 29 |
+
query = sys.argv[2]
|
| 30 |
+
|
| 31 |
+
print("Scanning + chunking...")
|
| 32 |
+
chunks = chunk_repo(scan_python_files(repo_dir))
|
| 33 |
+
print(f" {len(chunks)} chunks")
|
| 34 |
+
|
| 35 |
+
print("Embedding + indexing...")
|
| 36 |
+
embedder = Embedder()
|
| 37 |
+
embeddings = embedder.create_embeddings([c["chunk_text"] for c in chunks])
|
| 38 |
+
vector_store = VectorStore()
|
| 39 |
+
vector_store.build(embeddings, chunks)
|
| 40 |
+
hybrid = HybridRetriever(vector_store, BM25Retriever(chunks))
|
| 41 |
+
|
| 42 |
+
print(f'Searching: "{query}"\n')
|
| 43 |
+
query_emb = embedder.create_embeddings([query])[0]
|
| 44 |
+
results = hybrid.search(query, query_emb, k=10)
|
| 45 |
+
results = Reranker().rerank(query, results)
|
| 46 |
+
|
| 47 |
+
print("Top 5 results:")
|
| 48 |
+
for r in results[:5]:
|
| 49 |
+
d = r["document"]
|
| 50 |
+
print(f" {d['name']:40} {d['file']}:{d['start_line']}-{d['end_line']}")
|
| 51 |
+
|
| 52 |
+
print("\n--- Answer ---")
|
| 53 |
+
result = Answerer().answer(query, results[:5])
|
| 54 |
+
print(result["answer"])
|
| 55 |
+
|
| 56 |
+
tools = CodeTools(chunks, embedder, hybrid, Reranker())
|
| 57 |
+
agent = TestAgent(tools)
|
| 58 |
+
print("\n--- Generated tests for create_access_token ---")
|
| 59 |
+
print(agent.generate_tests("create_access_token"))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
main()
|
src/__init__.py
ADDED
|
File without changes
|
src/agent/__init__.py
ADDED
|
File without changes
|
src/agent/tools.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Agent tools.
|
| 3 |
+
|
| 4 |
+
Two callable tools the LLM can invoke to gather context before writing tests:
|
| 5 |
+
- search_code(query) : semantic+keyword search over the repo
|
| 6 |
+
- get_definition(name) : fetch the full source of a function/class by name
|
| 7 |
+
|
| 8 |
+
Both are thin wrappers over the same retrieval/index the Q&A side uses. The
|
| 9 |
+
CodeTools object holds the live index so the tool functions can reach it.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
# OpenAI tool schemas (function-calling format).
|
| 13 |
+
TOOL_SCHEMAS = [
|
| 14 |
+
{
|
| 15 |
+
"type": "function",
|
| 16 |
+
"function": {
|
| 17 |
+
"name": "search_code",
|
| 18 |
+
"description": "Search the repository for code relevant to a query. "
|
| 19 |
+
"Returns matching definitions with their file and line range.",
|
| 20 |
+
"parameters": {
|
| 21 |
+
"type": "object",
|
| 22 |
+
"properties": {
|
| 23 |
+
"query": {"type": "string", "description": "what to look for"}
|
| 24 |
+
},
|
| 25 |
+
"required": ["query"],
|
| 26 |
+
},
|
| 27 |
+
},
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"type": "function",
|
| 31 |
+
"function": {
|
| 32 |
+
"name": "get_definition",
|
| 33 |
+
"description": "Return the full source code of a function or class by its name "
|
| 34 |
+
"(e.g. 'login_user' or 'UserService.create_token').",
|
| 35 |
+
"parameters": {
|
| 36 |
+
"type": "object",
|
| 37 |
+
"properties": {
|
| 38 |
+
"name": {"type": "string", "description": "function/class name"}
|
| 39 |
+
},
|
| 40 |
+
"required": ["name"],
|
| 41 |
+
},
|
| 42 |
+
},
|
| 43 |
+
},
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class CodeTools:
|
| 48 |
+
"""Holds the live index and exposes the tool implementations."""
|
| 49 |
+
|
| 50 |
+
def __init__(self, chunks, embedder, hybrid, reranker):
|
| 51 |
+
self.chunks = chunks
|
| 52 |
+
self.embedder = embedder
|
| 53 |
+
self.hybrid = hybrid
|
| 54 |
+
self.reranker = reranker
|
| 55 |
+
|
| 56 |
+
def search_code(self, query, k=5):
|
| 57 |
+
emb = self.embedder.create_embeddings([query])[0]
|
| 58 |
+
results = self.reranker.rerank(query, self.hybrid.search(query, emb, k=10))
|
| 59 |
+
out = []
|
| 60 |
+
for r in results[:k]:
|
| 61 |
+
d = r["document"]
|
| 62 |
+
out.append({
|
| 63 |
+
"name": d["name"],
|
| 64 |
+
"file": d["file"],
|
| 65 |
+
"lines": f"{d['start_line']}-{d['end_line']}",
|
| 66 |
+
"code": d["code"],
|
| 67 |
+
})
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
def get_definition(self, name):
|
| 71 |
+
name_l = name.lower()
|
| 72 |
+
# exact match first, then suffix match (so "create_token" finds "UserService.create_token")
|
| 73 |
+
matches = [c for c in self.chunks if c["name"].lower() == name_l]
|
| 74 |
+
if not matches:
|
| 75 |
+
matches = [c for c in self.chunks
|
| 76 |
+
if c["name"].lower().endswith("." + name_l) or name_l in c["name"].lower()]
|
| 77 |
+
if not matches:
|
| 78 |
+
return {"error": f"No definition found named '{name}'."}
|
| 79 |
+
d = matches[0]
|
| 80 |
+
return {
|
| 81 |
+
"name": d["name"], "file": d["file"],
|
| 82 |
+
"lines": f"{d['start_line']}-{d['end_line']}", "code": d["code"],
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
def dispatch(self, tool_name, args):
|
| 86 |
+
"""Route a tool call from the LLM to the right implementation."""
|
| 87 |
+
if tool_name == "search_code":
|
| 88 |
+
return self.search_code(**args)
|
| 89 |
+
if tool_name == "get_definition":
|
| 90 |
+
return self.get_definition(**args)
|
| 91 |
+
return {"error": f"Unknown tool '{tool_name}'."}
|
src/agent/workflow.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test-generation agent.
|
| 3 |
+
|
| 4 |
+
A minimal tool-calling loop (no LangGraph). The LLM is given two tools
|
| 5 |
+
(search_code, get_definition) and asked to generate pytest tests for a target
|
| 6 |
+
function. It decides which tools to call to gather the function's real source
|
| 7 |
+
and its dependencies, then writes the tests grounded in that actual code.
|
| 8 |
+
|
| 9 |
+
This is the "agent" capability: the model plans and acts via tools, rather than
|
| 10 |
+
answering in a single shot.
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
from dotenv import load_dotenv
|
| 16 |
+
from openai import OpenAI
|
| 17 |
+
|
| 18 |
+
from src.agent.tools import TOOL_SCHEMAS
|
| 19 |
+
|
| 20 |
+
load_dotenv()
|
| 21 |
+
|
| 22 |
+
SYSTEM_PROMPT = """You are a senior Python engineer that writes pytest unit tests.
|
| 23 |
+
|
| 24 |
+
You have tools to explore a real codebase:
|
| 25 |
+
- search_code(query): find relevant code
|
| 26 |
+
- get_definition(name): fetch the full source of a function/class
|
| 27 |
+
|
| 28 |
+
Workflow:
|
| 29 |
+
1. Use get_definition (and search_code if needed) to read the ACTUAL source of
|
| 30 |
+
the target function and anything it depends on. Never guess at the code.
|
| 31 |
+
2. Then write focused pytest tests covering the main behavior and edge cases.
|
| 32 |
+
|
| 33 |
+
Return ONLY the final pytest code in a single Python code block. Base the tests
|
| 34 |
+
strictly on the real code you retrieved.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
MAX_TOOL_ROUNDS = 5
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TestAgent:
|
| 41 |
+
|
| 42 |
+
def __init__(self, tools, model="gpt-4.1-mini"):
|
| 43 |
+
self.tools = tools # a CodeTools instance
|
| 44 |
+
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 45 |
+
self.model = model
|
| 46 |
+
|
| 47 |
+
def generate_tests(self, target):
|
| 48 |
+
"""target: a function/class name, e.g. 'create_access_token'."""
|
| 49 |
+
messages = [
|
| 50 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 51 |
+
{"role": "user", "content": f"Generate pytest tests for `{target}`."},
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
for _ in range(MAX_TOOL_ROUNDS):
|
| 55 |
+
response = self.client.chat.completions.create(
|
| 56 |
+
model=self.model,
|
| 57 |
+
messages=messages,
|
| 58 |
+
tools=TOOL_SCHEMAS,
|
| 59 |
+
temperature=0,
|
| 60 |
+
)
|
| 61 |
+
msg = response.choices[0].message
|
| 62 |
+
|
| 63 |
+
# No tool calls -> the model produced its final answer (the tests).
|
| 64 |
+
if not msg.tool_calls:
|
| 65 |
+
return msg.content
|
| 66 |
+
|
| 67 |
+
# Otherwise, run each requested tool and feed results back.
|
| 68 |
+
messages.append(msg)
|
| 69 |
+
for call in msg.tool_calls:
|
| 70 |
+
args = json.loads(call.function.arguments)
|
| 71 |
+
result = self.tools.dispatch(call.function.name, args)
|
| 72 |
+
messages.append({
|
| 73 |
+
"role": "tool",
|
| 74 |
+
"tool_call_id": call.id,
|
| 75 |
+
"content": json.dumps(result)[:6000], # keep tool payload bounded
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
# Safety net if it never stopped calling tools.
|
| 79 |
+
return "Could not finish generating tests within the tool-call limit."
|
src/evaluation/__init__.py
ADDED
|
File without changes
|
src/evaluation/evaluator.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Evaluation harness for the codebase agent.
|
| 3 |
+
|
| 4 |
+
For each test question we run the real pipeline (hybrid search -> rerank ->
|
| 5 |
+
grounded answer) and measure:
|
| 6 |
+
|
| 7 |
+
- file accuracy : did a chunk from the expected file reach the top-N?
|
| 8 |
+
- function accuracy : did the expected function/class reach the top-N?
|
| 9 |
+
(only scored on questions that name an expected function)
|
| 10 |
+
- citation accuracy : did the generated answer actually cite the expected file?
|
| 11 |
+
- latency : per-question wall time
|
| 12 |
+
|
| 13 |
+
This is the honest, code-appropriate version of StudyMate's eval. NLI-style
|
| 14 |
+
faithfulness is a poor fit for code, so citation accuracy is the faithfulness
|
| 15 |
+
proxy here (does the answer ground itself in the right file?). LLM-as-judge
|
| 16 |
+
grading is the natural upgrade (see README roadmap).
|
| 17 |
+
"""
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CodeEvaluator:
|
| 22 |
+
|
| 23 |
+
def __init__(self, embedder, hybrid, reranker, answerer, retrieve_k=10, top_n=5):
|
| 24 |
+
self.embedder = embedder
|
| 25 |
+
self.hybrid = hybrid
|
| 26 |
+
self.reranker = reranker
|
| 27 |
+
self.answerer = answerer
|
| 28 |
+
self.retrieve_k = retrieve_k
|
| 29 |
+
self.top_n = top_n
|
| 30 |
+
|
| 31 |
+
def evaluate(self, testset):
|
| 32 |
+
rows = []
|
| 33 |
+
for item in testset:
|
| 34 |
+
q = item["question"]
|
| 35 |
+
exp_file = (item.get("expected_file") or "").lower()
|
| 36 |
+
exp_name = (item.get("expected_name") or "").lower()
|
| 37 |
+
|
| 38 |
+
t0 = time.time()
|
| 39 |
+
query_emb = self.embedder.create_embeddings([q])[0]
|
| 40 |
+
results = self.reranker.rerank(q, self.hybrid.search(q, query_emb, k=self.retrieve_k))
|
| 41 |
+
top = results[:self.top_n]
|
| 42 |
+
answer = self.answerer.answer(q, top)
|
| 43 |
+
elapsed = round(time.time() - t0, 2)
|
| 44 |
+
|
| 45 |
+
files = [r["document"]["file"].lower() for r in top]
|
| 46 |
+
names = [r["document"]["name"].lower() for r in top]
|
| 47 |
+
|
| 48 |
+
file_hit = bool(exp_file) and any(exp_file in f for f in files)
|
| 49 |
+
name_hit = (any(exp_name in n for n in names)) if exp_name else None
|
| 50 |
+
citation_ok = bool(exp_file) and exp_file in answer["answer"].lower()
|
| 51 |
+
|
| 52 |
+
rows.append({
|
| 53 |
+
"question": q,
|
| 54 |
+
"expected_file": item.get("expected_file", ""),
|
| 55 |
+
"expected_name": item.get("expected_name", ""),
|
| 56 |
+
"file_hit": file_hit,
|
| 57 |
+
"name_hit": name_hit,
|
| 58 |
+
"citation_ok": citation_ok,
|
| 59 |
+
"seconds": elapsed,
|
| 60 |
+
"top_files": files,
|
| 61 |
+
})
|
| 62 |
+
|
| 63 |
+
n = len(rows)
|
| 64 |
+
named = [r for r in rows if r["name_hit"] is not None]
|
| 65 |
+
latencies = sorted(r["seconds"] for r in rows)
|
| 66 |
+
summary = {
|
| 67 |
+
"questions": n,
|
| 68 |
+
"file_accuracy": round(100 * sum(r["file_hit"] for r in rows) / n, 1) if n else 0,
|
| 69 |
+
"function_accuracy": (round(100 * sum(r["name_hit"] for r in named) / len(named), 1)
|
| 70 |
+
if named else None),
|
| 71 |
+
"citation_accuracy": round(100 * sum(r["citation_ok"] for r in rows) / n, 1) if n else 0,
|
| 72 |
+
"median_latency": latencies[len(latencies) // 2] if latencies else 0,
|
| 73 |
+
}
|
| 74 |
+
return rows, summary
|
src/generation/__init__.py
ADDED
|
File without changes
|
src/ingestion/__init__.py
ADDED
|
File without changes
|
src/ingestion/chunker.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Code chunker.
|
| 3 |
+
|
| 4 |
+
Takes the raw definitions from parser.py and produces retrieval-ready chunks.
|
| 5 |
+
The only real job here is building `chunk_text` -- the string that actually gets
|
| 6 |
+
embedded and BM25-indexed. We prepend a short header (file, kind, name) to the
|
| 7 |
+
code so search can match on *location and signature* as well as the code body.
|
| 8 |
+
A query like "where is JWT created" then matches both the symbol names and the
|
| 9 |
+
implementation.
|
| 10 |
+
|
| 11 |
+
Run standalone to preview chunks:
|
| 12 |
+
python -m src.ingestion.chunker path/to/repo_dir
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
# Definitions longer than this many characters get their body trimmed in
|
| 16 |
+
# chunk_text so one giant function can't dominate an embedding. The full code
|
| 17 |
+
# is always kept in `code` for display/citations -- only the embedded text is
|
| 18 |
+
# trimmed.
|
| 19 |
+
_MAX_BODY_CHARS = 2000
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _build_chunk_text(d):
|
| 23 |
+
header = f"File: {d['file']} | {d['type']} {d['name']} | lines {d['start_line']}-{d['end_line']}"
|
| 24 |
+
body = d["code"]
|
| 25 |
+
if len(body) > _MAX_BODY_CHARS:
|
| 26 |
+
body = body[:_MAX_BODY_CHARS] + "\n# ... (truncated)"
|
| 27 |
+
return f"{header}\n{body}"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def build_chunks(definitions):
|
| 31 |
+
"""Attach chunk_text (and a stable id) to each definition dict."""
|
| 32 |
+
chunks = []
|
| 33 |
+
for i, d in enumerate(definitions):
|
| 34 |
+
chunk = dict(d) # don't mutate the parser's output
|
| 35 |
+
chunk["id"] = f"{d['file']}::{d['name']}::{d['start_line']}"
|
| 36 |
+
chunk["chunk_text"] = _build_chunk_text(d)
|
| 37 |
+
chunks.append(chunk)
|
| 38 |
+
return chunks
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def chunk_repo(files):
|
| 42 |
+
"""Full ingestion: parse files -> chunks. `files` is scanner output."""
|
| 43 |
+
from src.ingestion.parser import parse_files
|
| 44 |
+
return build_chunks(parse_files(files))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
import sys
|
| 49 |
+
from src.ingestion.scanner import scan_python_files, scan_repo
|
| 50 |
+
|
| 51 |
+
if len(sys.argv) < 2:
|
| 52 |
+
print("usage: python -m src.ingestion.chunker <repo.zip | repo_dir>")
|
| 53 |
+
sys.exit(1)
|
| 54 |
+
|
| 55 |
+
target = sys.argv[1]
|
| 56 |
+
files = scan_repo(target)[0] if target.lower().endswith(".zip") else scan_python_files(target)
|
| 57 |
+
chunks = chunk_repo(files)
|
| 58 |
+
|
| 59 |
+
print(f"Built {len(chunks)} chunks. First 3:\n")
|
| 60 |
+
for c in chunks[:3]:
|
| 61 |
+
print("-" * 70)
|
| 62 |
+
print(f"id: {c['id']}")
|
| 63 |
+
print(c["chunk_text"][:400])
|
| 64 |
+
print("-" * 70)
|
src/ingestion/parser.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Code parser (tree-sitter).
|
| 3 |
+
|
| 4 |
+
Turns a Python source file into a list of *definitions* -- functions, classes,
|
| 5 |
+
and methods -- each with the exact source text and 1-indexed start/end lines.
|
| 6 |
+
Those line numbers are what make citations exact and un-hallucinatable later.
|
| 7 |
+
|
| 8 |
+
It handles the real-world cases that trip up naive parsing:
|
| 9 |
+
- methods inside classes (named "ClassName.method", type "method")
|
| 10 |
+
- decorators (@app.route etc. -> included in the chunk + lines)
|
| 11 |
+
- nested functions (found via full-tree recursion)
|
| 12 |
+
- module-level imports (collected into one "module" context chunk)
|
| 13 |
+
|
| 14 |
+
Run standalone to inspect a repo's definitions:
|
| 15 |
+
python -m src.ingestion.parser path/to/repo_dir
|
| 16 |
+
"""
|
| 17 |
+
import tree_sitter_python as tspython
|
| 18 |
+
from tree_sitter import Language, Parser
|
| 19 |
+
|
| 20 |
+
_PY_LANGUAGE = Language(tspython.language())
|
| 21 |
+
_parser = Parser(_PY_LANGUAGE)
|
| 22 |
+
|
| 23 |
+
# Top-level nodes we fold into a per-file "module" chunk (imports + config).
|
| 24 |
+
_MODULE_CONTEXT_TYPES = {
|
| 25 |
+
"import_statement",
|
| 26 |
+
"import_from_statement",
|
| 27 |
+
"expression_statement", # top-level assignments / constants
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _node_text(src_bytes, node):
|
| 32 |
+
return src_bytes[node.start_byte:node.end_byte].decode("utf-8", errors="ignore")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _name_of(src_bytes, def_node):
|
| 36 |
+
n = def_node.child_by_field_name("name")
|
| 37 |
+
return _node_text(src_bytes, n) if n is not None else "<anonymous>"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _unwrap(node):
|
| 41 |
+
"""
|
| 42 |
+
If node is (or wraps) a function/class definition, return
|
| 43 |
+
(def_node_for_naming, outer_node_for_range); else None.
|
| 44 |
+
|
| 45 |
+
decorated_definition wraps the real def with its decorators, so we name
|
| 46 |
+
from the inner def but take the code/line range from the outer node so the
|
| 47 |
+
decorators are part of the chunk.
|
| 48 |
+
"""
|
| 49 |
+
if node.type in ("function_definition", "class_definition"):
|
| 50 |
+
return node, node
|
| 51 |
+
if node.type == "decorated_definition":
|
| 52 |
+
for child in node.children:
|
| 53 |
+
if child.type in ("function_definition", "class_definition"):
|
| 54 |
+
return child, node
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def extract_definitions(rel_path, source):
|
| 59 |
+
"""Return a list of definition dicts for one file."""
|
| 60 |
+
src_bytes = source.encode("utf-8")
|
| 61 |
+
root = _parser.parse(src_bytes).root_node
|
| 62 |
+
defs = []
|
| 63 |
+
|
| 64 |
+
def emit(def_node, outer, parent_class):
|
| 65 |
+
is_class = def_node.type == "class_definition"
|
| 66 |
+
kind = "class" if is_class else ("method" if parent_class else "function")
|
| 67 |
+
name = _name_of(src_bytes, def_node)
|
| 68 |
+
full_name = f"{parent_class}.{name}" if parent_class else name
|
| 69 |
+
defs.append({
|
| 70 |
+
"file": rel_path,
|
| 71 |
+
"type": kind,
|
| 72 |
+
"name": full_name,
|
| 73 |
+
"start_line": outer.start_point[0] + 1,
|
| 74 |
+
"end_line": outer.end_point[0] + 1,
|
| 75 |
+
"code": _node_text(src_bytes, outer),
|
| 76 |
+
})
|
| 77 |
+
return name if is_class else None
|
| 78 |
+
|
| 79 |
+
def walk(node, parent_class):
|
| 80 |
+
for child in node.children:
|
| 81 |
+
info = _unwrap(child)
|
| 82 |
+
if info:
|
| 83 |
+
def_node, outer = info
|
| 84 |
+
new_parent = emit(def_node, outer, parent_class)
|
| 85 |
+
# descend into the body: a class's inner funcs become methods
|
| 86 |
+
walk(def_node, new_parent)
|
| 87 |
+
else:
|
| 88 |
+
# not a definition -> keep descending to find nested defs
|
| 89 |
+
walk(child, parent_class)
|
| 90 |
+
|
| 91 |
+
walk(root, parent_class=None)
|
| 92 |
+
|
| 93 |
+
# one "module" chunk per file: top-level imports + constants
|
| 94 |
+
context_nodes = [c for c in root.children if c.type in _MODULE_CONTEXT_TYPES]
|
| 95 |
+
if context_nodes:
|
| 96 |
+
defs.append({
|
| 97 |
+
"file": rel_path,
|
| 98 |
+
"type": "module",
|
| 99 |
+
"name": rel_path,
|
| 100 |
+
"start_line": context_nodes[0].start_point[0] + 1,
|
| 101 |
+
"end_line": context_nodes[-1].end_point[0] + 1,
|
| 102 |
+
"code": "\n".join(_node_text(src_bytes, n) for n in context_nodes),
|
| 103 |
+
})
|
| 104 |
+
|
| 105 |
+
return defs
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def parse_files(files):
|
| 109 |
+
"""Run extract_definitions over scanner output (list of file records)."""
|
| 110 |
+
all_defs = []
|
| 111 |
+
for f in files:
|
| 112 |
+
all_defs.extend(extract_definitions(f["rel_path"], f["source"]))
|
| 113 |
+
return all_defs
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == "__main__":
|
| 117 |
+
import sys
|
| 118 |
+
from src.ingestion.scanner import scan_python_files, scan_repo
|
| 119 |
+
|
| 120 |
+
if len(sys.argv) < 2:
|
| 121 |
+
print("usage: python -m src.ingestion.parser <repo.zip | repo_dir>")
|
| 122 |
+
sys.exit(1)
|
| 123 |
+
|
| 124 |
+
target = sys.argv[1]
|
| 125 |
+
files = scan_repo(target)[0] if target.lower().endswith(".zip") else scan_python_files(target)
|
| 126 |
+
|
| 127 |
+
defs = parse_files(files)
|
| 128 |
+
print(f"Extracted {len(defs)} definitions from {len(files)} files:\n")
|
| 129 |
+
for d in defs:
|
| 130 |
+
print(f" [{d['type']:8}] {d['file']}:{d['start_line']}-{d['end_line']} {d['name']}")
|
src/ingestion/scanner.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Repository scanner.
|
| 3 |
+
|
| 4 |
+
Takes an uploaded repo (a .zip or an already-extracted directory) and returns
|
| 5 |
+
the Python source files worth indexing -- filtering out virtualenvs, caches,
|
| 6 |
+
VCS folders, build artifacts, and oversized files so the rest of the pipeline
|
| 7 |
+
only ever sees real source code.
|
| 8 |
+
|
| 9 |
+
Run standalone to sanity-check a repo:
|
| 10 |
+
python -m src.ingestion.scanner path/to/repo.zip
|
| 11 |
+
python -m src.ingestion.scanner path/to/repo_dir
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import tempfile
|
| 15 |
+
import zipfile
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
# Directories we never want to descend into.
|
| 19 |
+
SKIP_DIRS = {
|
| 20 |
+
".git", ".hg", ".svn",
|
| 21 |
+
"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox",
|
| 22 |
+
".venv", "venv", "env", "virtualenv",
|
| 23 |
+
"node_modules", "dist", "build", ".eggs", "site-packages",
|
| 24 |
+
".idea", ".vscode", ".ipynb_checkpoints",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
# Skip files bigger than this (generated/vendored files, data dumps, etc.).
|
| 28 |
+
MAX_FILE_BYTES = 1_000_000 # ~1 MB
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def extract_zip(zip_path, dest_dir=None):
|
| 32 |
+
"""Extract a .zip and return the directory it was extracted into."""
|
| 33 |
+
dest_dir = dest_dir or tempfile.mkdtemp(prefix="repo_")
|
| 34 |
+
with zipfile.ZipFile(zip_path) as zf:
|
| 35 |
+
zf.extractall(dest_dir)
|
| 36 |
+
return dest_dir
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def scan_python_files(root_dir):
|
| 40 |
+
"""
|
| 41 |
+
Walk root_dir and return a list of file records:
|
| 42 |
+
{"path": absolute path, "rel_path": path relative to root, "source": text}
|
| 43 |
+
|
| 44 |
+
rel_path is what we'll show in citations later (e.g. "auth/service.py"),
|
| 45 |
+
so it must stay relative to the repo root, not the temp extraction folder.
|
| 46 |
+
"""
|
| 47 |
+
root = Path(root_dir)
|
| 48 |
+
files = []
|
| 49 |
+
|
| 50 |
+
for dirpath, dirnames, filenames in os.walk(root):
|
| 51 |
+
# Prune skip dirs in place so os.walk won't descend into them.
|
| 52 |
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
| 53 |
+
|
| 54 |
+
for name in filenames:
|
| 55 |
+
if not name.endswith(".py"):
|
| 56 |
+
continue
|
| 57 |
+
full = Path(dirpath) / name
|
| 58 |
+
try:
|
| 59 |
+
if full.stat().st_size > MAX_FILE_BYTES:
|
| 60 |
+
continue
|
| 61 |
+
source = full.read_text(encoding="utf-8", errors="ignore")
|
| 62 |
+
except (OSError, UnicodeDecodeError):
|
| 63 |
+
continue # unreadable / weird encoding -> skip quietly
|
| 64 |
+
files.append({
|
| 65 |
+
"path": str(full),
|
| 66 |
+
"rel_path": str(full.relative_to(root)),
|
| 67 |
+
"source": source,
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
# Stable order makes runs reproducible (matters for eval later).
|
| 71 |
+
files.sort(key=lambda f: f["rel_path"])
|
| 72 |
+
return files
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def scan_repo(zip_path):
|
| 76 |
+
"""Extract a zip and scan it in one call. Returns (files, extraction_root)."""
|
| 77 |
+
root = extract_zip(zip_path)
|
| 78 |
+
return scan_python_files(root), root
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
import sys
|
| 83 |
+
|
| 84 |
+
if len(sys.argv) < 2:
|
| 85 |
+
print("usage: python -m src.ingestion.scanner <repo.zip | repo_dir>")
|
| 86 |
+
sys.exit(1)
|
| 87 |
+
|
| 88 |
+
target = sys.argv[1]
|
| 89 |
+
if target.lower().endswith(".zip"):
|
| 90 |
+
found, root = scan_repo(target)
|
| 91 |
+
print(f"Extracted to: {root}")
|
| 92 |
+
else:
|
| 93 |
+
found = scan_python_files(target)
|
| 94 |
+
|
| 95 |
+
print(f"Found {len(found)} Python files:")
|
| 96 |
+
for f in found:
|
| 97 |
+
line_count = f["source"].count("\n") + 1
|
| 98 |
+
print(f" {f['rel_path']} ({line_count} lines)")
|
src/rag/__init__.py
ADDED
|
File without changes
|
src/rag/answerer.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Grounded answerer.
|
| 3 |
+
|
| 4 |
+
Takes the reranked code chunks and asks the LLM to answer the developer's
|
| 5 |
+
question using ONLY those snippets, citing file:line for every claim. The model
|
| 6 |
+
phrases the answer; the retrieved chunks ground it. Generation runs at
|
| 7 |
+
temperature=0 so answers are faithful and reproducible.
|
| 8 |
+
|
| 9 |
+
Returns:
|
| 10 |
+
{
|
| 11 |
+
"answer": "<text with file:line citations>",
|
| 12 |
+
"sources": [ {file, name, type, start_line, end_line, code}, ... ]
|
| 13 |
+
}
|
| 14 |
+
"""
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
from dotenv import load_dotenv
|
| 18 |
+
from openai import OpenAI
|
| 19 |
+
|
| 20 |
+
load_dotenv()
|
| 21 |
+
|
| 22 |
+
SYSTEM_PROMPT = """You are a precise code-analysis assistant for a codebase Q&A tool.
|
| 23 |
+
|
| 24 |
+
Answer the developer's question using ONLY the code snippets provided.
|
| 25 |
+
|
| 26 |
+
Rules:
|
| 27 |
+
1. Cite the file and line range for every claim, e.g. `app/core/security.py:38-44`.
|
| 28 |
+
2. Use ONLY the provided snippets. Never invent files, functions, or behavior.
|
| 29 |
+
3. If the snippets do not contain the answer, reply exactly:
|
| 30 |
+
"I couldn't find that in the retrieved code."
|
| 31 |
+
4. Be concise. Explain what the relevant code does and where it lives.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Answerer:
|
| 36 |
+
|
| 37 |
+
def __init__(self, model="gpt-4.1-mini"):
|
| 38 |
+
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 39 |
+
self.model = model
|
| 40 |
+
|
| 41 |
+
def _format_context(self, documents):
|
| 42 |
+
blocks = []
|
| 43 |
+
for i, d in enumerate(documents, 1):
|
| 44 |
+
header = (f"[{i}] {d['file']}:{d['start_line']}-{d['end_line']} "
|
| 45 |
+
f"({d['type']} {d['name']})")
|
| 46 |
+
blocks.append(f"{header}\n{d['code']}")
|
| 47 |
+
return "\n\n".join(blocks)
|
| 48 |
+
|
| 49 |
+
def answer(self, query, results):
|
| 50 |
+
# accept reranked results ({"document": chunk}) OR raw chunk dicts
|
| 51 |
+
documents = [r["document"] if isinstance(r, dict) and "document" in r else r
|
| 52 |
+
for r in results]
|
| 53 |
+
|
| 54 |
+
if not documents:
|
| 55 |
+
return {"answer": "I couldn't find that in the retrieved code.",
|
| 56 |
+
"sources": []}
|
| 57 |
+
|
| 58 |
+
context = self._format_context(documents)
|
| 59 |
+
user_prompt = (f"Code snippets:\n\n{context}\n\n"
|
| 60 |
+
f"Question: {query}\n\nAnswer:")
|
| 61 |
+
|
| 62 |
+
response = self.client.chat.completions.create(
|
| 63 |
+
model=self.model,
|
| 64 |
+
messages=[
|
| 65 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 66 |
+
{"role": "user", "content": user_prompt},
|
| 67 |
+
],
|
| 68 |
+
temperature=0,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
sources = [{
|
| 72 |
+
"file": d["file"],
|
| 73 |
+
"name": d["name"],
|
| 74 |
+
"type": d["type"],
|
| 75 |
+
"start_line": d["start_line"],
|
| 76 |
+
"end_line": d["end_line"],
|
| 77 |
+
"code": d["code"],
|
| 78 |
+
} for d in documents]
|
| 79 |
+
|
| 80 |
+
return {"answer": response.choices[0].message.content, "sources": sources}
|
src/rag/bm25_search.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BM25 keyword retriever, tuned for code.
|
| 3 |
+
|
| 4 |
+
Same interface as the StudyMate version, but with a code-aware tokenizer:
|
| 5 |
+
prose `.split()` turns "jwt.encode(token)" into the single junk token
|
| 6 |
+
"jwt.encode(token)", so a search for "jwt.encode" never matches. Splitting on
|
| 7 |
+
non-identifier characters instead yields ["jwt", "encode", "token"], so exact
|
| 8 |
+
symbol searches -- BM25's whole strength on code -- actually work.
|
| 9 |
+
"""
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
from rank_bm25 import BM25Okapi
|
| 13 |
+
|
| 14 |
+
# Split on anything that isn't a letter, digit, or underscore.
|
| 15 |
+
_TOKEN_RE = re.compile(r"[A-Za-z0-9_]+")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def tokenize_code(text):
|
| 19 |
+
return _TOKEN_RE.findall(text.lower())
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class BM25Retriever:
|
| 23 |
+
|
| 24 |
+
def __init__(self, chunks):
|
| 25 |
+
self.chunks = chunks
|
| 26 |
+
documents = [tokenize_code(c["chunk_text"]) for c in chunks]
|
| 27 |
+
self.bm25 = BM25Okapi(documents)
|
| 28 |
+
|
| 29 |
+
def search(self, query, k=5):
|
| 30 |
+
tokens = tokenize_code(query)
|
| 31 |
+
scores = self.bm25.get_scores(tokens)
|
| 32 |
+
|
| 33 |
+
results = []
|
| 34 |
+
top_indexes = scores.argsort()[-k:][::-1]
|
| 35 |
+
for idx in top_indexes:
|
| 36 |
+
results.append({
|
| 37 |
+
"score": float(scores[idx]),
|
| 38 |
+
"document": self.chunks[idx],
|
| 39 |
+
})
|
| 40 |
+
return results
|
src/rag/embedder.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Embedder.
|
| 3 |
+
|
| 4 |
+
Same role as the StudyMate version. Returns a NumPy array (not a list) so the
|
| 5 |
+
FAISS VectorStore can read `embeddings.shape[1]`. Embeddings are L2-normalized
|
| 6 |
+
so inner-product search (IndexFlatIP) == cosine similarity.
|
| 7 |
+
|
| 8 |
+
Default model is the small general-purpose MiniLM (fast, already cached from
|
| 9 |
+
StudyMate). For a code project, a code-aware model retrieves better -- swap in
|
| 10 |
+
"jinaai/jina-embeddings-v2-base-code" (pass trust_remote_code=True) once the
|
| 11 |
+
pipeline works end-to-end.
|
| 12 |
+
"""
|
| 13 |
+
import numpy as np
|
| 14 |
+
from sentence_transformers import SentenceTransformer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Embedder:
|
| 18 |
+
|
| 19 |
+
def __init__(self, model_name="sentence-transformers/all-MiniLM-L6-v2", **kwargs):
|
| 20 |
+
self.model = SentenceTransformer(model_name, **kwargs)
|
| 21 |
+
|
| 22 |
+
def create_embeddings(self, texts):
|
| 23 |
+
embeddings = self.model.encode(list(texts), normalize_embeddings=True)
|
| 24 |
+
return np.array(embeddings)
|
src/rag/hybrid_search.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class HybridRetriever:
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def __init__(
|
| 5 |
+
self,
|
| 6 |
+
vector_store,
|
| 7 |
+
bm25
|
| 8 |
+
):
|
| 9 |
+
|
| 10 |
+
self.vector_store = vector_store
|
| 11 |
+
self.bm25 = bm25
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def search(
|
| 16 |
+
self,
|
| 17 |
+
query,
|
| 18 |
+
query_embedding,
|
| 19 |
+
k=5
|
| 20 |
+
):
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
semantic_results = (
|
| 24 |
+
self.vector_store.search(
|
| 25 |
+
query_embedding,
|
| 26 |
+
k
|
| 27 |
+
)
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
keyword_results = (
|
| 32 |
+
self.bm25.search(
|
| 33 |
+
query,
|
| 34 |
+
k
|
| 35 |
+
)
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
combined=[]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
for item in semantic_results:
|
| 43 |
+
|
| 44 |
+
combined.append(
|
| 45 |
+
{
|
| 46 |
+
"document":
|
| 47 |
+
item["document"],
|
| 48 |
+
|
| 49 |
+
"score":
|
| 50 |
+
item["score"] * 0.7
|
| 51 |
+
}
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
for item in keyword_results:
|
| 56 |
+
|
| 57 |
+
combined.append(
|
| 58 |
+
{
|
| 59 |
+
"document":
|
| 60 |
+
item["document"],
|
| 61 |
+
|
| 62 |
+
"score":
|
| 63 |
+
item["score"] * 0.3
|
| 64 |
+
}
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
combined.sort(
|
| 69 |
+
key=lambda x:x["score"],
|
| 70 |
+
reverse=True
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
return combined[:k]
|
src/rag/reranker.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import CrossEncoder
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Reranker:
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def __init__(self):
|
| 9 |
+
|
| 10 |
+
self.model = CrossEncoder(
|
| 11 |
+
"cross-encoder/ms-marco-MiniLM-L-6-v2"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def rerank(
|
| 17 |
+
self,
|
| 18 |
+
query,
|
| 19 |
+
results
|
| 20 |
+
):
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
pairs=[]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
for r in results:
|
| 27 |
+
|
| 28 |
+
pairs.append(
|
| 29 |
+
[
|
| 30 |
+
query,
|
| 31 |
+
r["document"]["chunk_text"]
|
| 32 |
+
]
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
scores = self.model.predict(
|
| 37 |
+
pairs
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
for r,score in zip(
|
| 42 |
+
results,
|
| 43 |
+
scores
|
| 44 |
+
):
|
| 45 |
+
|
| 46 |
+
r["rerank_score"]=float(score)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
results.sort(
|
| 51 |
+
key=lambda x:x["rerank_score"],
|
| 52 |
+
reverse=True
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
return results
|
src/rag/vector_store.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import faiss
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class VectorStore:
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def __init__(self):
|
| 10 |
+
|
| 11 |
+
self.index = None
|
| 12 |
+
self.documents = []
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def build(self, embeddings, documents):
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
dimension = embeddings.shape[1]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
self.index = faiss.IndexFlatIP(
|
| 23 |
+
dimension
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
self.index.add(
|
| 28 |
+
np.array(embeddings)
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
self.documents = documents
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def search(self, query_embedding, k=3):
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
scores, indexes = self.index.search(
|
| 40 |
+
np.array([query_embedding]),
|
| 41 |
+
k
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
results=[]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
for score, idx in zip(
|
| 49 |
+
scores[0],
|
| 50 |
+
indexes[0]
|
| 51 |
+
):
|
| 52 |
+
|
| 53 |
+
results.append(
|
| 54 |
+
{
|
| 55 |
+
"score":float(score),
|
| 56 |
+
|
| 57 |
+
"document":
|
| 58 |
+
self.documents[idx]
|
| 59 |
+
}
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
return results
|