A sophisticated multi-agent Retrieval-Augmented Generation (RAG) system that uses iterative reasoning, dynamic planning, and hybrid retrieval strategies to answer complex queries from financial documents and web sources.
- Overview
- Features
- Architecture
- Installation
- Usage
- API Documentation
- Evaluation Results
- Project Structure
- Configuration
- Contributing
- License
This project implements a Deep Thinking RAG system that significantly outperforms traditional RAG approaches by:
- Breaking down complex queries into manageable sub-questions
- Dynamically selecting retrieval strategies (vector, keyword, or hybrid search)
- Reranking and compressing retrieved information
- Reflecting on findings and deciding whether to continue research or finalize
- Streaming responses in real-time to the frontend
The system is designed to answer multi-hop questions requiring information from both structured documents (SEC 10-K filings) and real-time web sources.
"Based on NVIDIA's 2025 10-K filing, identify their key risks related to competition. Then, find recent news from 2024 about AMD's AI chip strategy and explain how this new strategy directly addresses or exacerbates one of NVIDIA's stated risks."
- π€ Multi-Agent Architecture: 6 specialized agents (Planner, Query Rewriter, Retrieval Supervisor, Distiller, Reflection, Policy)
- π Hybrid Retrieval: Combines vector search (semantic) + BM25 (keyword) + metadata filtering
- π― Intelligent Reranking: Cross-encoder reranking for precision
- π Web Integration: Tavily search for up-to-date information
- π Streaming UI: Real-time step-by-step visualization
- π Evaluation Framework: RAGAs metrics for performance tracking
- β‘ Fast Startup: Pre-built vector stores for instant deployment
- LangGraph for stateful, iterative workflows
- DeepSeek Reasoner for complex planning and reasoning
- Google Gemini Embeddings for semantic search
- Chroma DB for persistent vector storage
- FastAPI with SSE (Server-Sent Events) streaming
- React + Tailwind CSS frontend
Click here to view the full quality video.
| Agent | Purpose |
|---|---|
| Planner | Decomposes complex query into sequential sub-questions |
| Query Rewriter | Optimizes sub-questions for retrieval |
| Retrieval Supervisor | Selects best strategy (vector/keyword/hybrid) |
| Distiller | Compresses retrieved context into concise summaries |
| Reflection | Generates key findings for each step |
| Policy | Decides whether to continue research or finalize |
- Python 3.10+
- Node.js 18+
- API Keys:
- DeepSeek API Key
- Google Gemini API Key
- Tavily API Key
# Clone the repository
git clone https://github.com/proxi666/DeepThinking-AgenticRAG.git
cd DeepThinking-AgenticRAG/backend
# Create virtual environment
python -m venv rag
source rag/bin/activate # On Windows: rag\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Create .env file
cat > .env << EOF
DEEPSEEK_API_KEY=your_deepseek_key_here
GOOGLE_API_KEY=your_gemini_key_here
TAVILY_API_KEY=your_tavily_key_here
EOF
# Build vector stores (one-time setup)
python build_vector_store.py
# Start the server
uvicorn server:app --reload --host 0.0.0.0 --port 8000cd ../frontend
# Install dependencies
npm install
# Start development server
npm startThe application will be available at:
- Frontend: http://localhost:3000
- Backend API: http://localhost:8000
- API Docs: http://localhost:8000/docs
Navigate to http://localhost:3000 and enter your query. The interface shows:
- Planning Phase: Multi-step research plan
- Research Steps: Real-time retrieval and findings
- Final Answer: Comprehensive response with citations
curl -X POST http://localhost:8000/query/baseline \
-H "Content-Type: application/json" \
-d '{"query": "What are NVIDIA'\''s key risks?"}'curl -X POST http://localhost:8000/stream_query/deep_thinking \
-H "Content-Type: application/json" \
-d '{"query": "Analyze NVIDIA'\''s competitive risks and AMD'\''s response"}' \
--no-bufferimport requests
import json
query = "Your complex query here"
# Streaming response
with requests.post(
"http://localhost:8000/stream_query/deep_thinking",
json={"query": query},
stream=True
) as response:
for line in response.iter_lines():
if line:
data = json.loads(line.decode('utf-8')[5:]) # Remove 'data:' prefix
if data["type"] == "plan":
print("π Research Plan:", data["data"])
elif data["type"] == "step_result":
print(f"β
Step {data['data']['step']}: {data['data']['summary']}")
elif data["type"] == "final_answer":
print("π― Final Answer:", data["data"])Health check endpoint.
Response: {"message": "Deep Thinking RAG API is running."}
Execute simple baseline RAG query.
Request Body:
{
"query": "What are the main risks in the 10-K?"
}Response:
{
"baseline_output": "The main risks include...",
"contexts": ["Context chunk 1...", "Context chunk 2..."]
}Execute Deep Thinking RAG with streaming.
Request Body:
{
"query": "Complex multi-hop question"
}Response (Server-Sent Events):
data: {"type": "plan", "data": [...]}
data: {"type": "step_result", "data": {"step": 1, "sub_question": "...", "summary": "..."}}
data: {"type": "final_answer", "data": "Comprehensive answer..."}
data: {"type": "contexts", "data": ["Context 1...", "Context 2..."]}
Evaluated on 5 complex financial queries requiring multi-hop reasoning across SEC 10-K filings and real-time web sources using RAGAs framework with Google Gemini 2.5 Flash.
| Metric | Baseline RAG | Deep Thinking RAG | Improvement |
|---|---|---|---|
| Faithfulness | 34.5% | 53.4% | +54.9% |
| Context Recall | 11.7% | 15.0% | +28.3% |
| Context Precision | β | 29.9% | β |
| Answer Correctness | 49.1% | 50.0% | +1.8% |
- β 54.9% improvement in faithfulness - Deep Thinking RAG significantly reduces hallucinations and stays grounded in retrieved context
- β 28.3% improvement in context recall - Multi-step retrieval captures more relevant information from ground truth
- β 29.9% context precision - Reranking and metadata filtering effectively select relevant documents (baseline failed to calculate this metric)
- β Consistent improvements across all measurable metrics demonstrate the effectiveness of the multi-agent approach
Evaluated using RAGAs framework with Google Gemini 2.5 Flash. See evaluation_results.csv for detailed per-query breakdown.
- Competition Risk Analysis - Extract NVIDIA's 10-K competition risks and analyze AMD's 2024 AI GPU strategy impact
- Supply Chain Assessment - Evaluate supply/manufacturing disclosures and score AMD's supply posture risk (0-5)
- Ecosystem Lock-in Analysis - Compare NVIDIA's CUDA ecosystem with AMD's ROCm developments
- Customer Concentration - Analyze customer risks and build impact scenarios for workload shifts
- Product Cadence - Assess whether AMD's 2024-2025 roadmap targets NVIDIA's stated vulnerability windows
# Ensure server is running
uvicorn server:app --reload
# In another terminal
python evaluate.pyResults are saved to evaluation_results.csv and evaluation_summary.txt.
# Ensure server is running
uvicorn server:app --reload
# In another terminal
python evaluate.pyResults are saved to evaluation_results.csv.
DeepThinking-AgenticRAG/
βββ backend/
β βββ agents.py # Agent definitions (Planner, Rewriter, etc.)
β βββ build_vector_store.py # Offline vector store builder
β βββ config.py # Configuration settings
β βββ data_processing.py # Document parsing and chunking
β βββ evaluate.py # RAGAs evaluation script
β βββ graph_builder.py # LangGraph construction
β βββ graph_nodes.py # Node functions for the graph
β βββ main.py # CLI execution script
β βββ models.py # Pydantic models
β βββ rag_core.py # Core RAG logic
β βββ retrieval.py # Retrieval strategies
β βββ server.py # FastAPI server
β βββ utils.py # Helper utilities
β βββ vector_store.py # Vector store management
β βββ requirements.txt # Python dependencies
β βββ .env # Environment variables
β βββ chroma_db/ # Persistent vector stores
β β βββ baseline/
β β βββ advanced/
β β βββ bm25_index.pkl
β βββ data/ # Downloaded documents
β βββ nvda_q2_2025_clean.txt
β βββ nvda_q2_2025_raw.html
β
βββ frontend/
β βββ src/
β β βββ App.js # Main React component
β β βββ App.css # Styles
β β βββ index.js # Entry point
β β βββ reportWebVitals.js # Performance monitoring
β βββ public/
β β βββ index.html
β βββ package.json
β βββ tailwind.config.js
β
βββ README.md
Edit backend/config.py to customize:
config = {
"data_dir": "./data",
"vector_store_dir": "./vector_store",
"persistent_db_dir": "./chroma_db",
"reasoning_llm": "deepseek-reasoner", # LLM for planning
"fast_llm": "deepseek-chat", # LLM for quick tasks
"embedding_model": "models/gemini-embedding-001",
"reranker_model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"max_reasoning_iterations": 7, # Max research steps
"top_k_retrieval": 10, # Docs to retrieve
"top_n_rerank": 3, # Docs after reranking
}# Dockerfile (create this)
FROM python:3.10-slim
WORKDIR /app
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY backend/ .
EXPOSE 8000
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"]# Build and run
docker build -t deep-thinking-rag .
docker run -p 8000:8000 --env-file backend/.env deep-thinking-ragIssue: ModuleNotFoundError: No module named 'langchain_deepseek'
pip install langchain-deepseekIssue: Vector stores not found
# Rebuild vector stores
python build_vector_store.pyIssue: Timeout errors during evaluation
# In evaluate.py, increase timeout
eval_llm = ChatDeepSeek(model="deepseek-chat", timeout=300)Issue: CORS errors in frontend
// In server.py, ensure CORS middleware is configured
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)Siddhant Diwaker
- GitHub: @proxi666
- Docker: @proxi666
- Email: [email protected]
- NVIDIA for providing publicly available 10-K filings
- The LangChain and LangGraph teams for excellent frameworks
- The open-source community for various tools and libraries
- Fareed Khan for the original DeepRAG architecture and inspiration
Built with β€οΈ using LangChain, LangGraph, and FastAPI

