Update README.md
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376381 unmodified line640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746# π€ 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 \1 unmodified line-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`---1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363371 unmodified line339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462# AI Codebase AssistantAn AI-powered developer tool that lets you interact with an entire code repository using **RAG (Retrieval-Augmented Generation)** and LLMs.It can answer questions about your codebase, detect potential bugs, analyze code complexity, explain functions, generate documentation, create new files, and interact with GitHub through the GitHub MCP API.---## Features### Codebase Question AnsweringAsk natural-language questions about your repository.**Example:**```textHow does authentication work?```The assistant searches the relevant parts of the codebase and generates an answer with source references.---### Bug DetectionAnalyze a source file and identify potential issues using an LLM-powered code review.Example:```text[HIGH] Line 34SQL query uses string concatenationRecommendation:Use parameterized queries to prevent SQL injection.```The system returns the issue severity, location, and recommendation.---### Cyclomatic Complexity AnalysisAnalyze the complexity of Python functions using **Radon**.Example:```text[A] process_order complexity = 2[B] validate_cart complexity = 5[C] apply_discounts complexity = 8[F] handle_edge_cases complexity = 18```This helps identify functions that may be difficult to maintain or test.---### Function ExplanationSelect a function and get a plain-English explanation of what it does.For Python code, the project uses the `ast` module to extract the function and provides relevant repository context to the LLM.---### Documentation GenerationGenerate documentation automatically for your codebase.The assistant can generate:- Module documentation- Function explanations- Docstrings- Repository README files---### AI File GenerationDescribe the file you want to create and let the AI generate it.Example:```textCreate a Rectangle class in JavaScriptthat calculates area and perimeter.```The generated file is shown before it is written to the repository, allowing the user to approve it first.---### GitHub MCP IntegrationThe project integrates with the **GitHub Copilot MCP API**.It currently supports access to **44 GitHub MCP tools**, including:- `search_code`- `search_repositories`- `get_file_contents`- `list_issues`- `create_branch`- `create_pull_request`- `push_files`- `fork_repository`---## RAG-Based Code SearchThe project uses **Retrieval-Augmented Generation (RAG)** to work with repository-level code.Repository files are:1. Loaded and filtered2. Split into smaller chunks3. Converted into embeddings4. Stored in ChromaDB5. Retrieved based on semantic similarity when a question is askedThe retrieved code is then provided to the LLM as context.Source metadata such as file path and line range is preserved during this process.---## Supported LanguagesThe repository ingestion system currently supports:| Extension | Language ||---|---|| `.py` | Python || `.js` | JavaScript || `.ts` | TypeScript || `.java` | Java || `.go` | Go || `.md` | Markdown |---## Tech Stack### AI / LLM- Groq- Llama 3.3 70B- Google Gemini### RAG- LangChain- Google Gemini Embeddings- ChromaDB### Backend- Python- FastAPI- Pydantic Settings### Code Analysis- Python AST- Radon- LLM-based code analysis### Integration- GitHub MCP- GitHub Copilot MCP API---## LLM Providers| Provider | Model | Usage ||---|---|---|| Groq | `llama-3.3-70b-versatile` | LLM generation || Gemini | Configurable | LLM generation || Gemini Embeddings | `models/gemini-embedding-001` | Code embeddings |The project supports switching between Groq and Gemini for LLM generation.Gemini Embeddings are used for semantic retrieval.---# Installation## 1. Clone the Repository```bashgit clone <your-repository-url>cd "Codebase Assistant"```## 2. Create a Virtual Environment### Windows```bashpython -m venv .venv.venv\Scripts\Activate.ps1```### Linux / macOS```bashpython3 -m venv .venvsource .venv/bin/activate```## 3. Install Dependencies```bashpip install -r requirements.txt```---## ποΈ ArchitectureThe system combines a RAG pipeline, LLM providers, code analysis services,FastAPI, and GitHub MCP integration to provide repository-level AI assistance.# ConfigurationCreate a `.env` file in the project root.```envLLM_PROVIDER=groqGROQ_API_KEY=your_groq_api_keyGROQ_MODEL=llama-3.3-70b-versatileGEMINI_API_KEY=your_gemini_api_keyEMBEDDING_MODEL=models/gemini-embedding-001VECTOR_DB_PATH=./vector_dbGITHUB_MCP_TOKEN=your_github_token```### Required API Keys**Groq**Used for LLM generation when:```envLLM_PROVIDER=groq```**Gemini**Required for embeddings because the project uses Gemini Embeddings for repository indexing.**GitHub Token**Required for GitHub MCP functionality.---# Running the CLIStart the interactive CLI:```bashpython cli.py```The application will ask for the repository you want to analyze.```textβΆ Enter the path to the repository you want to analyse:```After the repository is indexed, you can choose from:```text1 Ask a question about the codebase2 Detect bugs in a file3 Cyclomatic complexity analysis4 Explain a function5 Generate module documentation6 Generate README7 Propose & create a new file8 List GitHub MCP tools9 Re-ingest repository0 Exit```---# REST APIThe project also provides a FastAPI REST API.Start the server:```bashpython -m uvicorn app:app --reload --port 8000```Open the interactive API documentation:```texthttp://localhost:8000/docs```## API Endpoints| Method | Endpoint | Description ||---|---|---|| `GET` | `/health` | Health check || `POST` | `/api/query` | Ask questions about the codebase || `POST` | `/api/analyze/bugs` | Detect potential bugs || `POST` | `/api/analyze/complexity` | Analyze cyclomatic complexity || `POST` | `/api/analyze/explain` | Explain a function || `POST` | `/api/docs/module` | Generate module documentation || `POST` | `/api/docs/readme` | Generate README || `POST` | `/api/files/propose` | Generate a file proposal || `POST` | `/api/files/approve` | Write an approved file |---## Example API Request```bashcurl -X POST http://localhost:8000/api/query \1 unmodified line-d '{"query": "How does authentication work?", "k": 5}'```Example response:```json{"answer": "Authentication is handled by ...","sources": [{"file_path": "src/auth.py","start_line": 10,"end_line": 45}]}```---# π Project Structure```textCodebase Assistant/ββββ cli.pyβββ app.pyβββ config.pyβββ llm.pyβββ mcp_client.pyβββ requirements.txtββββ rag/β βββ repository_loader.pyβ βββ splitter.pyβ βββ embedding.pyβ βββ retriever.pyβ βββ rag_chain.pyββββ services/β βββ code_analysis.pyβ βββ documentation.pyβ βββ file_creator.pyββββ api/β βββ routes.pyββββ vector_db/βββ chroma.sqlite3```---# Configuration Options| Setting | Default | Description ||---|---|---|| `LLM_PROVIDER` | `groq` | LLM provider || `GROQ_MODEL` | `llama-3.3-70b-versatile` | Groq model || `EMBEDDING_MODEL` | `models/gemini-embedding-001` | Embedding model || `VECTOR_DB_PATH` | `./vector_db` | ChromaDB storage || `CHUNK_SIZE` | `1200` | Chunk size || `CHUNK_OVERLAP` | `100` | Chunk overlap || `MAX_FILE_SIZE_KB` | `1042` | Maximum file size || `ALLOWED_EXTENSIONS` | `.py,.js,.ts,.go,.java,.md` | Supported files |---# Limitations- Repository ingestion currently runs locally.- External API keys are required for LLM and embedding services.- Gemini embedding quotas may limit large repositories.- Only the currently supported file types are indexed.- LLM-generated code and bug reports should be reviewed before use.- The vector database currently focuses on the actively ingested repository.---# Future ImprovementsPlanned or possible improvements include:- More programming language support- Incremental repository indexing- GitHub repository ingestion- AST-based code chunking- Hybrid keyword + vector search- Retrieval reranking- Dependency graph analysis- Automated test generation- Automated pull request review- Multi-repository search- Web-based developer interface---# Project GoalThe goal of this project is to build an AI developer assistant that can understand and interact with an entire codebase rather than only individual code snippets.It combines:**RAG + LLMs + Vector Search + Code Analysis + FastAPI + MCP**into a single developer-focused tool.---# Author**Armaan Alam**AI Engineer & Software DeveloperInterested in:- Generative AI- RAG Systems- Backend Engineering- LLM Applications- AI Developer Tools- Machine Learning
README.md+277-561