Spaces:
Sleeping

intellicode-rag / README.md
Divb30's picture
trim the readme
65c53b7
|
Raw History Blame Contribute Delete
7.45 kB

A newer version of the Gradio SDK is available: 6.33.0

Upgrade
metadata
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 Python Live Demo

β–Ά Try the live demo Β· 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 β€” 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), which stays valid when chunk boundaries change. Retrieval ablations (dense vs hybrid vs reranked, chunk size, chunking method) are in 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

flowchart LR
    subgraph Ingest[Indexing]
        DOC[Documents] --> CH[Sentence-aware<br/>chunking ~256 tok]
        CH --> EMB[MiniLM embeddings]
        EMB --> FA[(FAISS<br/>IndexFlatIP)]
        CH --> BM[(BM25<br/>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<br/>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 +<br/>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.


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 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)