--- title: IntelliCode RAG Assistant emoji: ๐Ÿง  colorFrom: blue colorTo: purple sdk: gradio sdk_version: 4.44.0 app_file: app.py pinned: false hardware: zero-gpu --- # IntelliCode โ€” Hybrid RAG + AST Code Intelligence A retrieval-augmented assistant that pairs a **hybrid dense + sparse retriever with cross-encoder reranking** for document Q&A, and an **AST-powered static analyzer** for Python code review. Every retrieval and analysis decision in this repo is backed by a reproducible benchmark that runs in CI โ€” no GPU or API keys required. [![CI](https://github.com/Divyanshb30/IntelliDoc-RAG-Assistant/actions/workflows/ci.yml/badge.svg)](https://github.com/Divyanshb30/IntelliDoc-RAG-Assistant/actions/workflows/ci.yml) ![Python](https://img.shields.io/badge/python-3.10%2B-blue) [![Live Demo](https://img.shields.io/badge/๐Ÿค—%20demo-HuggingFace%20Spaces-orange)](https://huggingface.co/spaces/Divb30/intellicode-rag) **[โ–ถ Try the live demo](https://huggingface.co/spaces/Divb30/intellicode-rag)** ยท Qwen2.5-3B ยท FAISS ยท BM25 ยท Cross-Encoder ยท Python AST --- ## Benchmarks Retrieval and analysis are measured by the same harness on a labeled eval set, and both are **regression-gated on every push** via [`eval/baselines.json`](eval/baselines.json) โ€” a change that drops MRR@5, Recall@3, or analyzer F1 below the floor fails CI. Relevance is scored by answer-span containment ([`evaluation.py`](src/intellicode/evaluation.py)), which stays valid when chunk boundaries change. Retrieval ablations (dense vs hybrid vs reranked, chunk size, chunking method) are in [Ablations](#ablations); reproduce everything with `python eval/run_benchmarks.py`. **AST analyzer accuracy** โ€” against an annotated ground-truth fixture with a clean-code false-positive control: | Precision | Recall | F1 | False positives on clean code | |:---:|:---:|:---:|:---:| | 1.00 | 1.00 | 1.00 | 0 | --- ## Architecture ```mermaid flowchart LR subgraph Ingest[Indexing] DOC[Documents] --> CH[Sentence-aware
chunking ~256 tok] CH --> EMB[MiniLM embeddings] EMB --> FA[(FAISS
IndexFlatIP)] CH --> BM[(BM25
corpus)] end subgraph Query[Retrieval and generation] Q[Query] --> D[Dense search] Q --> S[Sparse search] FA --> D BM --> S D --> RRF[RRF fusion] S --> RRF RRF --> RE[Cross-encoder
rerank] RE --> LLM[Qwen2.5-3B] LLM --> ANS[Grounded answer] end subgraph Code[Code intelligence] PY[Python file] --> AST[AST analyzer] AST --> ISS[Anti-patterns +
security findings] end ``` The RAG path and the AST path are independent engines: document Q&A runs the full retrieval + LLM pipeline, while code analysis is pure-Python AST work with no model call โ€” deterministic and instant. **Deeper design notes, data-flow, and tradeoffs:** [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md). --- ## Key design decisions - **Hybrid retrieval over dense-only.** Dense embeddings miss exact-keyword queries (product names, error codes, acronyms); BM25 catches them. The two rankings are merged with **Reciprocal Rank Fusion** (`score = ฮฃ 1/(k+rank)`, k=60), which needs no score normalization and is robust to the very different score scales of cosine similarity and BM25. Measured: +0.024 MRR@5 and Recall@3 0.96 โ†’ 1.00. - **Cross-encoder reranking as a second stage.** A bi-encoder scores query and passage separately; a cross-encoder (`ms-marco-MiniLM-L-6-v2`, 22M params) scores them jointly and is far more accurate. Running it only on the top-20 candidates keeps it CPU-cheap (<100 ms) while lifting MRR@5 to 1.000. - **Cosine similarity, not L2.** Embeddings are L2-normalized and indexed with `IndexFlatIP`, so inner product equals cosine similarity โ€” the metric sentence-transformers is trained for, and directly comparable across queries (which the negative-rejection check relies on). - **Sentence-aware chunking.** Recursive paragraph โ†’ sentence โ†’ word splitting keeps chunks on semantic boundaries. At matched ~256-token size it beats the naive word-window splitter (MRR@5 0.893 โ†’ 0.907) while never cutting mid-sentence. Every claim above is a row in the [benchmark tables](#ablations) and is gated in CI. --- ## AST analyzer Detects 12 classes of anti-pattern by walking the AST โ€” **including `async def`**, which the original naive version silently skipped. Function-level checks cover both `FunctionDef` and `AsyncFunctionDef`. | Severity | Anti-patterns detected | |---|---| | HIGH | Mutable default arguments (literals **and** `list()`/`dict()`/`set()` constructors) | | MEDIUM | Bare `except:`, deep nesting, high cyclomatic complexity, star imports, deeply nested functions | | LOW | Broad `except Exception`, unused variables, long functions, missing return type hints, `global` statements, `assert` in production code | A companion **security scanner** flags hardcoded secrets, SQL injection, weak crypto (MD5/SHA1), `eval`/`exec`/`os.system`, insecure deserialization, `shell=True`, and unsafe `yaml.load`. --- ## Ablations
Chunk size (hybrid, no rerank) | Chunk size | MRR@5 | Recall@1 | Recall@3 | NDCG@5 | |---|:---:|:---:|:---:|:---:| | 128 tokens | 0.863 | 0.760 | 0.960 | 0.898 | | **256 tokens** | 0.907 | 0.840 | **1.000** | 0.930 | | 512 tokens | 0.930 | 0.880 | 0.960 | 0.948 | 256 tokens is the default: it achieves perfect Recall@3 while passing more focused (less noisy) context to the LLM. 512 edges MRR@5 slightly but retrieves more extraneous text per chunk and drops a Recall@3 point.
Chunking method at matched size | Method | MRR@5 | Recall@1 | Recall@3 | NDCG@5 | |---|:---:|:---:|:---:|:---:| | Word-split (~256 tok) | 0.893 | 0.800 | 1.000 | 0.921 | | **Sentence-aware** (256 tok) | 0.907 | 0.840 | 1.000 | 0.930 |
--- ## Project structure ``` src/intellicode/ โ”œโ”€โ”€ config.py # Pydantic settings (env-overridable) โ”œโ”€โ”€ rag/ โ”‚ โ”œโ”€โ”€ chunking.py # sentence-aware + legacy word-split chunkers โ”‚ โ”œโ”€โ”€ retriever.py # FAISS dense + BM25 sparse + RRF fusion โ”‚ โ”œโ”€โ”€ reranker.py # cross-encoder second stage โ”‚ โ””โ”€โ”€ pipeline.py # ingest โ†’ index โ†’ query orchestrator โ”œโ”€โ”€ analysis/ โ”‚ โ”œโ”€โ”€ code_analyzer.py # AST anti-pattern detection (async-aware) โ”‚ โ”œโ”€โ”€ security_scanner.py โ”‚ โ”œโ”€โ”€ test_generator.py โ”‚ โ”œโ”€โ”€ code_executor.py # sandboxed subprocess execution โ”‚ โ””โ”€โ”€ code_fixer.py โ”œโ”€โ”€ agent.py # intent routing + answer rendering โ”œโ”€โ”€ tools.py # tool registry โ”œโ”€โ”€ llm.py # Qwen2.5-3B backend (optional) โ””โ”€โ”€ evaluation.py # metrics + eval harness tests/ # 121 tests: unit, integration, eval gates eval/ # benchmark runner + pinned baselines ``` --- ## Tech stack | Layer | Technology | |---|---| | Embeddings | sentence-transformers (`all-MiniLM-L6-v2`, 384-d) | | Dense index | FAISS `IndexFlatIP` (cosine) | | Sparse index | `rank-bm25` (BM25Okapi) | | Reranker | `cross-encoder/ms-marco-MiniLM-L-6-v2` | | Generation | Qwen2.5-3B-Instruct (HuggingFace ZeroGPU) | | Code analysis | Python `ast` | | Config | Pydantic Settings | | UI / hosting | Gradio ยท HuggingFace Spaces | | CI | GitHub Actions (eval-gated) |