Create README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746# π€ AI Codebase Assistant β Complete Documentation> An AI-powered developer tool that ingests any local code repository, answers questions about it using RAG (Retrieval-Augmented Generation), detects bugs, measures complexity, generates docs, proposes new files, and integrates with the GitHub MCP API β all from an interactive CLI.---## Table of Contents1. [Project Overview](#1-project-overview)2. [Repository Structure](#2-repository-structure)3. [Architecture & Flow](#3-architecture--flow)4. [Component Deep-Dive](#4-component-deep-dive)5. [Setup & Installation](#5-setup--installation)6. [Configuration (.env)](#6-configuration-env)7. [Running the CLI](#7-running-the-cli)8. [CLI Features β All 9 Options](#8-cli-features--all-9-options)9. [REST API](#9-rest-api)10. [Key Design Decisions & Bug Fixes](#10-key-design-decisions--bug-fixes)11. [Extending the Project](#11-extending-the-project)---## 1. Project OverviewThe **AI Codebase Assistant** is a local developer tool that:- π **Ingests** any code repository (Python, JS, TS, Java, Go, Markdown)- π **Answers questions** about the code using RAG + LLM- π **Detects bugs** via LLM-powered code review- π **Measures cyclomatic complexity** using Radon- π **Explains functions** in plain English- π **Generates module docs and READMEs** automatically- π οΈ **Proposes & creates new files** using AI, saved to your chosen directory- π **Lists 44 GitHub MCP tools** via the GitHub Copilot MCP API**LLM Providers supported:**| Provider | Model | Notes ||---|---|---|| Groq | `llama-3.3-70b-versatile` | Free tier, recommended || Gemini | Configurable | Paid, stricter quota |**Embedding:** Google Gemini Embedding API (`models/gemini-embedding-001`)**Vector Store:** ChromaDB (local persistent)---## 2. Repository Structure```Codebase Assistant/ββββ cli.py # β Main entry point (interactive CLI)βββ app.py # β FastAPI REST server (optional)βββ config.py # β All settings via pydantic-settings + .envβββ llm.py # β LLM abstraction (Gemini / Groq) + prompt templatesβββ mcp_client.py # β GitHub MCP async context-manager clientβββ requirements.txt # β All Python dependenciesβββ .env # β API keys and configuration (not committed)ββββ rag/ # ββ RAG Pipeline βββββββββββββββββββββββββββββββ βββ repository_loader.py # Walk directory, read files β CodeDocumentβ βββ splitter.py # Split CodeDocuments into chunks with metadataβ βββ embedding.py # Embed chunks/queries via Gemini Embeddingsβ βββ retriever.py # ChromaDB vector store: build / load / queryβ βββ rag_chain.py # Orchestrate retrieve β build context β LLMββββ services/ # ββ Feature Services βββββββββββββββββββββββββββ βββ code_analysis.py # Bug detection, complexity, function explainerβ βββ documentation.py # Module docs, README generatorβ βββ file_creator.py # AI file proposal + local disk writeββββ api/ # ββ REST API (FastAPI) βββββββββββββββββββββββββ βββ routes.py # All HTTP endpoints (mirrors CLI features)ββββ vector_db/ # ββ ChromaDB Storage (auto-created) ββββββββββββββ chroma.sqlite3 # Persisted vector embeddings```---## 3. Architecture & Flow### 3.1 Full System Architecture```mermaidgraph TBsubgraph USER["User Interface"]CLI["cli.py\n(Interactive CLI)"]API["app.py\n(FastAPI REST API)"]endsubgraph RAG["RAG Pipeline"]RL["repository_loader.py\nWalk & read files"]SP["splitter.py\nChunk by language"]EM["embedding.py\nGemini Embeddings"]RT["retriever.py\nChromaDB"]RC["rag_chain.py\nOrchestrator"]endsubgraph SERVICES["Feature Services"]CA["code_analysis.py\nBugs Β· Complexity Β· Explain"]DOC["documentation.py\nModule Docs Β· README"]FC["file_creator.py\nAI File Creator"]endsubgraph EXTERNAL["External APIs"]GROQ["Groq API\nllama-3.3-70b"]GEM["Gemini API\nEmbeddings"]MCP["GitHub MCP\n44 tools"]endLLM["llm.py\nLLM Abstraction Layer"]CFG["config.py\n.env Settings"]DB[("vector_db/\nChromaDB")]CLI --> RAGCLI --> SERVICESAPI --> RAGAPI --> SERVICESRL --> SP --> EM --> RTRT --> DBRC --> RTRC --> LLMCA --> LLMDOC --> LLMFC --> LLMLLM --> GROQLLM --> GEMEM --> GEMCLI --> MCPCFG -.->|settings| RAGCFG -.->|settings| LLMCFG -.->|settings| SERVICES```### 3.2 Ingest Flow (Step-by-step)```mermaidflowchart LRA["User provides\nrepo path"] --> B["repository_loader.py\nwalk directories\nskip: .git venv __pycache__"]B --> C["Filter by\nallowed extensions\n.py .js .ts .java .go .md"]C --> D["Read each file\nβ CodeDocument\n(content, path, language, size)"]D --> E["splitter.py\nLanguage-aware chunking\nRecursiveCharacterTextSplitter"]E --> F["Each chunk gets\nmetadata: file_path\nlanguage Β· start_line Β· end_line"]F --> G["embedding.py\nGemini embed_documents\nβ float vectors"]G --> H["retriever.py\nDelete old collection\nCreate fresh ChromaDB\ncollection.add(...)"]H --> I["β Vector store ready"]```### 3.3 RAG Query Flow```mermaidflowchart LRQ["User question"] --> E["embed_query\n(Gemini)"]E --> S["ChromaDB\ncollection.query\ntop-k chunks"]S --> C["build_context\nformat chunks\nwith file/line headers"]C --> P["build_prompt\nqa template\ncontext + question"]P --> L["LLM\n(Groq / Gemini)"]L --> A["Answer + Sources\n(file_path, line range)"]```### 3.4 CLI Menu Flow```mermaidflowchart TDSTART([Start cli.py]) --> REPO["βΆ Enter repo path"]REPO --> INGEST["Ingest Repository\nload β split β embed β store"]INGEST --> MENU["Show Menu\nOptions 1β9"]MENU --> O1["1 Ask a question\nβ RAG Query"]MENU --> O2["2 Detect bugs\nβ LLM code review"]MENU --> O3["3 Cyclomatic complexity\nβ Radon"]MENU --> O4["4 Explain function\nβ AST + LLM"]MENU --> O5["5 Module docs\nβ LLM"]MENU --> O6["6 Generate README\nβ LLM"]MENU --> O7["7 Propose & create file\nβ LLM + local write"]MENU --> O8["8 List GitHub MCP tools\nβ GitHub Copilot MCP"]MENU --> O9["9 Re-ingest repo\nβ new repo path"]MENU --> O0["0 Exit"]O1 & O2 & O3 & O4 & O5 & O6 & O7 & O8 & O9 --> MENUO0 --> END([Goodbye!])```---## 4. Component Deep-Dive### 4.1 `config.py` β SettingsAll configuration lives in one `pydantic-settings` class loaded from `.env`:| Setting | Default | Description ||---|---|---|| `llm_provider` | `"groq"` | `"groq"` or `"gemini"` || `groq_api_key` | `""` | From `.env` || `groq_model` | `"llama-3.3-70b-versatile"` | Free Groq model || `gemini_api_key` | `""` | From `.env` || `embedding_model` | `"models/gemini-embedding-001"` | Always Gemini for embeddings || `vector_db_path` | `"./vector_db"` | ChromaDB storage directory || `chunk_size` | `1200` | Characters per chunk || `chunk_overlap` | `100` | Overlap between chunks || `allowed_extensions` | `[.py .js .ts .go .java .md]` | File types to load || `max_file_size_kb` | `1042` | Skip files larger than this || `github_mcp_url` | GitHub Copilot MCP endpoint | For option 8 || `github_mcp_token` | `""` | GitHub PAT from `.env` |### 4.2 `rag/repository_loader.py` β File Ingestion```load_repository(root_path)βββ os.walk(root_path)βββ Skip: .git, node_modules, __pycache__, venv, .venv, dist, buildβββ should_include(fpath) β checks extension + file sizeβββ read_file_with_metadata(fpath) β CodeDocument(content, file_path, language, size_bytes)```**Supported languages detected by extension:**| Extension | Language ||---|---|| `.py` | python || `.js` | javascript || `.ts` | typescript || `.java` | java || `.go` | go || `.md` | markdown |### 4.3 `rag/splitter.py` β ChunkingUses **LangChain's `RecursiveCharacterTextSplitter`** with language-aware splitting:- For Python/JS/TS/Java/Go β uses syntax-aware boundaries (functions, classes)- For Markdown/unknown β falls back to generic character splitting- Each chunk carries: `content`, `file_path`, `language`, `chunk_index`, `start_line`, `end_line`### 4.4 `rag/embedding.py` β Embeddings- Uses `GoogleGenerativeAIEmbeddings` (`models/gemini-embedding-001`)- `embed_document(chunks)` β batch embeds all chunks, mutates dicts in-place- `embed_query(query)` β single query vector for similarity search### 4.5 `rag/retriever.py` β Vector Store> **Critical fix applied:** collection is deleted and recreated on every ingest to prevent stale data from previous repos bleeding through.```pythonbuild_vector_store(chunks) # delete β create β add (fresh each ingest)load_vector_store() # get_or_create for readingretrieve_relevant_chunks(q, k) # embed query β cosine similarity β top-k```### 4.6 `rag/rag_chain.py` β Orchestration```pythonrun_rag_query(query, k=5)1. retrieve_relevant_chunks(query, k)2. build_context(chunks) # format with file/line headers3. build_prompt(query, context) # fill qa template4. llm.generate(prompt)5. return { answer, sources }```### 4.7 `llm.py` β LLM AbstractionAbstract `BaseLLM` with two concrete providers:| Class | Provider | API ||---|---|---|| `GeminiLLM` | Google Gemini | `google-genai` SDK || `GroqLLM` | Groq | `groq` SDK, chat completions |**Prompt templates (`build_prompt`):**| `task_type` | Used by ||---|---|| `"qa"` | RAG query, function explain, module docs, README || `"bug_finding"` | Bug detection (returns JSON) || `"docstring"` | Docstring generation || `"file_creation"` | AI file proposal |### 4.8 `mcp_client.py` β GitHub MCP ClientAsync context-manager pattern using `AsyncExitStack` to keep all `anyio` cancel scopes in the **same task**:```pythonasync with get_github_mcp_client() as client:tools = await client.list_tools()result = await client.call_tool("create_branch", {...})```Available GitHub MCP tools (44 total) include: `search_code`, `list_issues`, `create_pull_request`, `get_file_contents`, `push_files`, `create_branch`, `fork_repository`, `search_repositories`, and many more.### 4.9 `services/code_analysis.py`| Function | How it works ||---|---|| `explain_function(file, name)` | Python `ast` extracts the function source β RAG context β LLM || `detect_bugs(file)` | Read file β `bug_finding` prompt β LLM returns JSON list || `analyze_complexity(file)` | `radon.cc_visit` β cyclomatic complexity + rank AβF |### 4.10 `services/file_creator.py````propose_new_file(description, context_query)βββ RAG retrieve relevant contextβββ build_prompt(description, context, "file_creation")βββ LLM generates complete file contentβββ infer_file_path(description) β LLM suggests relative pathapply_approved_file(proposal, confirmed, base_dir)βββ Strip leading / or \ from LLM pathβββ os.path.join(base_dir, relative_path)βββ os.makedirs(parent_dirs, exist_ok=True)βββ open(abs_path, "w").write(content)```---## 5. Setup & Installation### Prerequisites| Requirement | Version ||---|---|| Python | 3.11+ || pip | Latest || Internet | For API calls |### Step 1 β Clone / Download the project```bashgit clone <your-repo-url>cd "Codebase Assistant"```### Step 2 β Create a virtual environment```bash# Windows (PowerShell)python -m venv .venv.venv\Scripts\Activate.ps1# macOS / Linuxpython3 -m venv .venvsource .venv/bin/activate```### Step 3 β Install dependencies```bashpip install -r requirements.txt```> [!TIP]> If you hit permission issues on Windows, use:> `pip install -r requirements.txt --user`### Step 4 β Create your `.env` fileCreate a file named `.env` in the project root:```env# Choose your LLM provider: "groq" (free) or "gemini"LLM_PROVIDER=groq# Groq β free at https://console.groq.comGROQ_API_KEY=gsk_your_key_here# Gemini β get at https://aistudio.google.comGEMINI_API_KEY=your_gemini_key_here# GitHub PAT for MCP tools β create at https://github.com/settings/tokens# Required scopes: repo, read:orgGITHUB_MCP_TOKEN=github_pat_your_token_here```> [!IMPORTANT]> `GEMINI_API_KEY` is **always required** regardless of LLM provider, because embeddings always use Gemini.### Step 5 β Run the CLI```bash.venv\Scripts\python.exe cli.py # Windowspython cli.py # macOS / Linux```---## 6. Configuration (.env)```env# βββ LLM Provider ββββββββββββββββββββββββββββββββββββββββLLM_PROVIDER=groq # "groq" | "gemini"# βββ Groq (recommended β free tier) βββββββββββββββββββββGROQ_API_KEY=gsk_...GROQ_MODEL=llama-3.3-70b-versatile# βββ Gemini ββββββββββββββββββββββββββββββββββββββββββββββGEMINI_API_KEY=...LLM_MODEL=gemini-1.5-flash # only used if LLM_PROVIDER=geminiEMBEDDING_MODEL=models/gemini-embedding-001# βββ RAG / Vector DB βββββββββββββββββββββββββββββββββββββVECTOR_DB_PATH=./vector_dbCHUNK_SIZE=1200CHUNK_OVERLAP=100# βββ File loader βββββββββββββββββββββββββββββββββββββββββ# comma-separated extensionsALLOWED_EXTENSIONS=[".py",".js",".ts",".go",".java",".md"]MAX_FILE_SIZE_KB=1042# βββ GitHub MCP ββββββββββββββββββββββββββββββββββββββββββGITHUB_MCP_URL=https://api.githubcopilot.com/mcp/GITHUB_MCP_TOKEN=github_pat_...```---## 7. Running the CLI```βββββββββββββββββββββββββββββββββββββββββββββ AI Codebase Assistant CLI ββββββββββββββββββββββββββββββββββββββββββββββΆ Enter the path to the repository you want to analyse: D:\MyProjectββ Ingesting Repository ββββββββββββββββββββββLoading files from: D:\MyProjectβ Loaded 12 filesβ Split into 47 chunksEmbedding chunks (this may take a moment)...β Embedded 47 chunksβ Vector store ready (ChromaDB)ββ What would you like to do? ββββββββββββββββ1 Ask a question about the codebase2 Detect bugs in a file3 Cyclomatic complexity analysis4 Explain a function5 Generate module documentation6 Generate README for a repository7 Propose & create a new file (AI)8 List GitHub MCP tools9 Re-ingest a repository0 ExitβΆ Choose an option [0β9]:```---## 8. CLI Features β All 9 Options### Option 1 β Ask a Question (RAG Query)```βΆ Your question: How does the authentication work?βΆ Number of source chunks to retrieve? [default: 5] 3ββ Answer ββββββββββββββββββββββββββββββββββββThe authentication uses JWT tokens ...ββ Sources ββββββββββββββββββββββββββββββββββββ’ src/auth/middleware.py lines 12β45β’ src/auth/tokens.py lines 1β30```**Pipeline:** Embed question β ChromaDB similarity search β Build context β LLM β Answer + cited sources---### Option 2 β Detect Bugs```βΆ File path to analyse: src/payment.pyββ Found 2 issue(s) ββββββββββββββββββββββββββ[HIGH] Line 34: SQL query uses string concatenationβ Use parameterized queries to prevent SQL injection[MEDIUM] Line 67: Exception swallowed silentlyβ Log or re-raise the exception```**Pipeline:** Read file β `bug_finding` prompt β LLM returns JSON β parsed and displayed---### Option 3 β Cyclomatic Complexity```βΆ File path to analyse: src/processor.pyββ 4 function(s) βββββββββββββββββββββββββββββ[A] process_order complexity=2 ββ[B] validate_cart complexity=5 βββββ[C] apply_discounts complexity=8 ββββββββ[F] handle_edge_cases complexity=18 ββββββββββββββββββ```**Rank scale:** A (1β5, simple) β F (26+, untestable)---### Option 4 β Explain a Function```βΆ File path: src/utils.pyβΆ Function name: parse_date_rangeββ Explanation βββββββββββββββββββββββββββββββparse_date_range takes a string like "2024-01-01:2024-12-31"and returns a tuple of (start_date, end_date) as datetime objects ...```**Pipeline:** Python `ast` module extracts exact function source β RAG retrieves usages β LLM explains---### Option 5 β Generate Module Documentation```βΆ File path: src/database.pyββ Documentation βββββββββββββββββββββββββββββ## database.py### OverviewThis module provides the database connection layer ...### Functions- `connect(url)` β Establishes a connection ...- `execute(query, params)` β Runs a parameterized query ...```---### Option 6 β Generate README```βΆ Repository root path: D:\MyProjectββ README Preview ββββββββββββββββββββββββββββ# MyProject## OverviewA FastAPI application that ...βΆ Save to README.md in that directory? [y/N] yβ Saved to D:\MyProject\README.md```---### Option 7 β Propose & Create a New File```βΆ Describe the file you want to create: Rectangle area calculator in JavaScriptβΆ Optional context query (or press Enter to skip):ββ Proposed File βββββββββββββββββββββββββββββPath: /src/geometry/rectangle.jsclass Rectangle { ...full generated code... }βΆ Write this file to disk? [y/N] yβΆ Save under which directory? [default: D:\MyProject]β File written: D:\MyProject\src\geometry\rectangle.js```**Pipeline:** RAG context (optional) β `file_creation` prompt β LLM generates code β user confirms β write to `base_dir/relative_path`---### Option 8 β List GitHub MCP Tools```ββ List GitHub MCP Tools βββββββββββββββββββββ44 tools available:β’ create_branch Create a new branch in a GitHub repositoryβ’ create_pull_request Create a new pull request ...β’ search_code Fast and precise code search ...β’ list_issues List issues in a GitHub repository ......```**Connection:** Uses `streamable_http_client` β `ClientSession` β GitHub Copilot MCP endpoint---### Option 9 β Re-ingest a Repository```βΆ New repository path to ingest: D:\AnotherProjectββ Ingesting Repository βββββββββββββββββββββββ Loaded 8 files ...```Wipes the ChromaDB collection and ingests the new repo fresh. All subsequent queries answer from the new repo only.---## 9. REST APIStart the FastAPI server:```bash.venv\Scripts\python.exe -m uvicorn app:app --reload --port 8000```Open docs at: `http://localhost:8000/docs`### Endpoints| Method | Path | Description ||---|---|---|| `GET` | `/health` | Health check || `POST` | `/api/query` | RAG question answering || `POST` | `/api/analyze/bugs?file_path=...` | Bug detection || `POST` | `/api/analyze/complexity?file_path=...` | Cyclomatic complexity || `POST` | `/api/analyze/explain` | Explain a function || `POST` | `/api/docs/module?file_path=...` | Module documentation || `POST` | `/api/docs/readme?root_path=...` | README generation || `POST` | `/api/files/propose` | Propose a new file || `POST` | `/api/files/approve` | Write approved file to disk |### Example β Query```bashcurl -X POST http://localhost:8000/api/query \-H "Content-Type: application/json" \-d '{"query": "How does authentication work?", "k": 5}'``````json{"answer": "Authentication is handled by ...","sources": [{"file_path": "src/auth.py", "start_line": 10, "end_line": 45}]}```---## 10. Key Design Decisions & Bug Fixes### Bug Fix 1 β Collection Isolation (retriever.py)**Problem:** ChromaDB used `upsert` on a shared `"codebase"` collection β stale chunks from previously ingested repos leaked into new queries.**Fix:** On every ingest, `delete_collection` + `create_collection` ensures a clean slate:```python# Before (bug)collection = client.get_or_create_collection("codebase")collection.upsert(...)# After (fix)client.delete_collection("codebase") # wipe old repocollection = client.create_collection("codebase")collection.add(...)```---### Bug Fix 2 β GitHub MCP Cancel Scope (mcp_client.py)**Problem:** Manually calling `__aenter__`/`__aexit__` on `anyio`-backed context managers across tasks causes `RuntimeError: Attempted to exit cancel scope in a different task`.**Fix:** Use `AsyncExitStack` to nest all context managers inside a single `async with`:```pythonasync with get_github_mcp_client() as client:tools = await client.list_tools()```---### Bug Fix 3 β Wrong Unpack Count (mcp_client.py)**Problem:** `streamable_http_client` yields 2 values, not 3. Unpacking 3 caused `ValueError: not enough values to unpack`.```python# Before (bug)read, write, _ = await ctx.__aenter__()# After (fix)read, write = await stack.enter_async_context(streamable_http_client(...))```---### Bug Fix 4 β File Save Path (file_creator.py)**Problem:** Generated files saved to the current working directory regardless of user input.**Fix:**- Strip leading `/\` from LLM path to make it always relative- Accept `base_dir` defaulting to `_current_repo` (the ingested repo path)- Create all parent directories automatically---## 11. Extending the Project### Add a new LLM provider1. Add a new class in `llm.py` extending `BaseLLM`2. Add the provider name to `get_llm_client()` factory3. Add matching settings in `config.py`### Add support for new file types1. Add extension β language in `LANGUAGE_BY_EXT` in `repository_loader.py`2. Add extension to `allowed_extensions` in `config.py`3. If LangChain has a `Language` enum for it, add to `LANGUAGE_MAP` in `splitter.py`### Use a GitHub MCP tool in a feature```pythonasync with get_github_mcp_client() as client:result = await client.call_tool("create_branch", {"owner": "myuser","repo": "myrepo","branch": "feature/new-branch","from_branch": "main"})```### Add a new CLI option1. Write a `feature_xxx()` function in `cli.py`2. Add `("Label", feature_xxx)` to the `MENU` list3. Add a matching FastAPI endpoint in `api/routes.py`---
README.md+746