Spaces:
Sleeping

Divb30 commited on
Commit
740b461
·
1 Parent(s): a6ffba1

feat: IntelliCode RAG — HF Spaces deploy

Browse files
Files changed (4) hide show
  1. README.md +21 -92
  2. agent.py +22 -22
  3. app.py +12 -11
  4. requirements.txt +4 -10
README.md CHANGED
@@ -1,92 +1,21 @@
1
- # IntelliCode RAG Assistant
2
-
3
- A production-ready AI-powered code analysis and document intelligence system built with local LLMs. This assistant provides comprehensive code quality analysis, security scanning, automated test generation, and intelligent document search capabilities without requiring external API keys or internet connectivity.
4
-
5
- ## Overview
6
-
7
- IntelliCode RAG Assistant is an enterprise-grade tool that combines Retrieval-Augmented Generation (RAG) with advanced code analysis to help developers maintain high-quality, secure codebases while providing instant answers from technical documentation. The system runs entirely on local hardware, ensuring complete privacy and eliminating API costs.
8
-
9
- ## Features
10
-
11
- ### Code Analysis Tools
12
-
13
- **Static Code Analyzer**
14
- - AST-based Python code inspection
15
- - Detects mutable default arguments, bare except clauses, and unused variables
16
- - Identifies deep nesting and overly complex functions
17
- - Calculates code metrics including comment coverage and cyclomatic complexity
18
- - Provides severity-based issue classification (HIGH, MEDIUM, LOW)
19
-
20
- **Security Scanner**
21
- - Detects hardcoded credentials and API keys
22
- - Identifies SQL injection vulnerabilities
23
- - Flags weak cryptographic algorithms (MD5, SHA1)
24
- - Warns about dangerous function usage (eval, exec, os.system)
25
- - Checks for insecure deserialization patterns
26
- - Assigns risk levels from LOW to CRITICAL
27
-
28
- **Automated Test Generator**
29
- - Generates pytest-compatible test suites automatically
30
- - Creates normal, edge, and parametrized test cases
31
- - Infers parameter types from function signatures
32
- - Supports multiple test scenarios per function
33
- - Outputs ready-to-run test files
34
-
35
- **Code Executor**
36
- - Safe execution in isolated subprocess environment
37
- - Configurable timeout protection
38
- - Captures stdout and stderr separately
39
- - Provides execution time metrics
40
- - Prevents resource leaks with automatic cleanup
41
-
42
- **Code Fixer**
43
- - Analyzes code issues and suggests specific fixes
44
- - Provides before/after code examples
45
- - Explains why each fix is necessary
46
- - Covers common Python antipatterns
47
- - Generates actionable improvement recommendations
48
-
49
- ### Document Intelligence Tools
50
-
51
- **RAG-Powered Document Search**
52
- - Semantic search across uploaded documents
53
- - Supports TXT, PDF, CSV, and Markdown formats
54
- - Uses FAISS for efficient vector similarity search
55
- - Provides context-aware answers to queries
56
- - Processes documents with configurable chunk sizes
57
-
58
- **Document Summarizer**
59
- - Extracts key highlights from large documents
60
- - Generates concise summaries
61
- - Supports multiple document formats
62
- - Maintains context across document sections
63
-
64
- ## Technical Architecture
65
-
66
- ### Core Components
67
-
68
- **Language Model**
69
- - Model: Qwen 2.5 3B Instruct (quantized Q4_K_M)
70
- - Context window: 4096 tokens
71
- - Runs on CPU with optimized threading
72
- - No GPU required for operation
73
-
74
- **Vector Database**
75
- - FAISS (Facebook AI Similarity Search)
76
- - IndexFlatL2 for exact similarity search
77
- - Optimized for CPU-based retrieval
78
- - Supports dynamic index updates
79
-
80
- **Embedding Model**
81
- - Model: all-MiniLM-L6-v2
82
- - Dimension: 384
83
- - Fast inference on CPU
84
- - Balanced accuracy and speed
85
-
86
- **Web Interface**
87
- - Built with Streamlit
88
- - Responsive design for desktop use
89
- - Real-time chat interface
90
- - Professional UI with custom CSS styling
91
- - Expandable detail panels for analysis results
92
-
 
1
+ ---
2
+ title: IntelliCode RAG Assistant
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ sdk_version: 1.40.0
8
+ app_file: app.py
9
+ pinned: false
10
+ hardware: t4-small
11
+ ---
12
+
13
+ # 🧠 IntelliCode RAG Assistant
14
+
15
+ > Fully offline-capable AI assistant for code analysis & document Q&A.
16
+ > Powered by **Qwen2.5-3B-Instruct** running on GPU — zero OpenAI dependency.
17
+
18
+ [![Demo](https://img.shields.io/badge/🤗-Live_Demo-blue)](https://huggingface.co/spaces/YOUR_USERNAME/intellicode-rag)
19
+
20
+ ## Stack
21
+ `Qwen2.5-3B-Instruct` · `FAISS IndexFlatL2` · `sentence-transformers` · `Python AST` · `Streamlit`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
agent.py CHANGED
@@ -1,13 +1,31 @@
1
- from llama_cpp import Llama
2
  from typing import Dict, Any, List
3
  import json
4
 
5
  class RAGAgent:
6
  """AI Agent with intent detection and tool routing"""
7
 
8
- def __init__(self, llm: Llama, tools: Dict):
9
  self.llm = llm
10
  self.tools = tools
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  def detect_intent(self, query: str, file_context: Dict = None) -> str:
13
  """Detect which tool to use based on query and context"""
@@ -221,16 +239,7 @@ INFORMATION:
221
  ANSWER (write 2-3 complete sentences stating facts only):"""
222
 
223
  try:
224
- response = self.llm(
225
- prompt,
226
- max_tokens=120,
227
- temperature=0.2, # Very low for factual
228
- top_p=0.8,
229
- stop=["\n\nQUESTION:", "\nQUESTION:", "INFORMATION:", "\n\n\n", "1.", "2.", "3.", "###", "Question:", "question:"],
230
- repeat_penalty=1.5 # High penalty to prevent repetition
231
- )
232
-
233
- answer = response['choices'][0]['text'].strip()
234
 
235
  # Clean answer
236
  for prefix in ["ANSWER:", "Answer:", "Direct Answer:", "Response:", "Based on", "According to"]:
@@ -279,16 +288,7 @@ Summary:"""
279
 
280
  # Generate LLM response
281
  try:
282
- response = self.llm(
283
- prompt,
284
- max_tokens=200,
285
- temperature=0.5,
286
- top_p=0.9,
287
- stop=["Question:", "\n\n\n", "Human:", "Assistant:", "Context:", "Text:", "Summary:", "Assessment:", "Answer:"],
288
- repeat_penalty=1.2
289
- )
290
-
291
- answer = response['choices'][0]['text'].strip()
292
 
293
  # Clean prefixes
294
  for prefix in ["Assistant:", "Human:", "AI:", "Response:", "Answer:", "Summary:", "Assessment:"]:
 
1
+ import torch
2
  from typing import Dict, Any, List
3
  import json
4
 
5
  class RAGAgent:
6
  """AI Agent with intent detection and tool routing"""
7
 
8
+ def __init__(self, llm: Dict, tools: Dict):
9
  self.llm = llm
10
  self.tools = tools
11
+
12
+ def _call_llm(self, prompt: str, max_new_tokens: int = 150) -> str:
13
+ tokenizer = self.llm["tokenizer"]
14
+ model = self.llm["model"]
15
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
16
+ with torch.no_grad():
17
+ outputs = model.generate(
18
+ **inputs,
19
+ max_new_tokens=max_new_tokens,
20
+ temperature=0.3,
21
+ do_sample=True,
22
+ pad_token_id=tokenizer.eos_token_id
23
+ )
24
+ decoded = tokenizer.decode(
25
+ outputs[0][inputs["input_ids"].shape[1]:],
26
+ skip_special_tokens=True
27
+ ).strip()
28
+ return decoded
29
 
30
  def detect_intent(self, query: str, file_context: Dict = None) -> str:
31
  """Detect which tool to use based on query and context"""
 
239
  ANSWER (write 2-3 complete sentences stating facts only):"""
240
 
241
  try:
242
+ answer = self._call_llm(prompt, max_new_tokens=150)
 
 
 
 
 
 
 
 
 
243
 
244
  # Clean answer
245
  for prefix in ["ANSWER:", "Answer:", "Direct Answer:", "Response:", "Based on", "According to"]:
 
288
 
289
  # Generate LLM response
290
  try:
291
+ answer = self._call_llm(prompt, max_new_tokens=150)
 
 
 
 
 
 
 
 
 
292
 
293
  # Clean prefixes
294
  for prefix in ["Assistant:", "Human:", "AI:", "Response:", "Answer:", "Summary:", "Assessment:"]:
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import streamlit as st
2
- from llama_cpp import Llama
 
3
  from rag import RAGPipeline
4
  from tools import get_tools
5
  from agent import RAGAgent
@@ -168,22 +169,22 @@ st.markdown('<p class="sub-header">AI-powered code analysis and documentation</p
168
 
169
  # Initialize agent
170
  if st.session_state.agent is None:
171
- with st.spinner("Loading AI model..."):
172
  try:
173
- llm = Llama(
174
- model_path="models/qwen2.5-3b-instruct-q4_k_m.gguf",
175
- n_ctx=4096,
176
- n_threads=8,
177
- verbose=False
 
 
178
  )
179
-
180
  if st.session_state.rag is None:
181
  st.session_state.rag = RAGPipeline()
182
-
183
  tools = get_tools(st.session_state.rag)
184
  st.session_state.agent = RAGAgent(llm, tools)
185
- st.success("Model loaded")
186
-
187
  except Exception as e:
188
  st.error(f"Failed to load model: {e}")
189
  st.stop()
 
1
  import streamlit as st
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
  from rag import RAGPipeline
5
  from tools import get_tools
6
  from agent import RAGAgent
 
169
 
170
  # Initialize agent
171
  if st.session_state.agent is None:
172
+ with st.spinner("Loading Qwen2.5-3B model from HuggingFace Hub..."):
173
  try:
174
+ MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
175
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
176
+ model = AutoModelForCausalLM.from_pretrained(
177
+ MODEL_ID,
178
+ torch_dtype=torch.float16,
179
+ device_map="auto",
180
+ trust_remote_code=True
181
  )
182
+ llm = {"model": model, "tokenizer": tokenizer}
183
  if st.session_state.rag is None:
184
  st.session_state.rag = RAGPipeline()
 
185
  tools = get_tools(st.session_state.rag)
186
  st.session_state.agent = RAGAgent(llm, tools)
187
+ st.success("Qwen2.5-3B loaded")
 
188
  except Exception as e:
189
  st.error(f"Failed to load model: {e}")
190
  st.stop()
requirements.txt CHANGED
@@ -1,17 +1,11 @@
1
- llama-cpp-python==0.2.90
2
  streamlit==1.40.0
 
 
 
3
  faiss-cpu==1.9.0.post1
4
  pypdf==5.1.0
5
  pandas==2.2.3
6
  numpy==1.26.4
 
7
  python-dotenv==1.0.1
8
  tqdm==4.67.1
9
- requests==2.32.3
10
- python-dateutil==2.9.0
11
-
12
- # PyTorch and ML libraries - TESTED COMPATIBLE VERSIONS
13
- torch==2.2.0
14
- torchvision==0.17.0
15
- torchaudio==2.2.0
16
- transformers==4.38.2
17
- sentence-transformers==2.5.1
 
 
1
  streamlit==1.40.0
2
+ transformers==4.38.2
3
+ accelerate==0.27.2
4
+ torch==2.2.0
5
  faiss-cpu==1.9.0.post1
6
  pypdf==5.1.0
7
  pandas==2.2.3
8
  numpy==1.26.4
9
+ sentence-transformers==2.5.1
10
  python-dotenv==1.0.1
11
  tqdm==4.67.1