Skip to content

About

A multi-agent RAG system that uses iterative reasoning and hybrid retrieval to answer complex financial queries

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

10 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DeepThinking-AgenticRAG

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.

Python 3.10+ FastAPI LangChain React


πŸ“‹ Table of Contents


🎯 Overview

This project implements a Deep Thinking RAG system that significantly outperforms traditional RAG approaches by:

  1. Breaking down complex queries into manageable sub-questions
  2. Dynamically selecting retrieval strategies (vector, keyword, or hybrid search)
  3. Reranking and compressing retrieved information
  4. Reflecting on findings and deciding whether to continue research or finalize
  5. 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.

Example Query

"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."


✨ Features

Core Capabilities

  • πŸ€– 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

Technical Highlights

  • 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

πŸ—οΈ Architecture

alt text

Demo

Deep Thinking RAG Demo

Click here to view the full quality video.

Agent Responsibilities

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

πŸš€ Installation

Prerequisites

  • Python 3.10+
  • Node.js 18+
  • API Keys:
    • DeepSeek API Key
    • Google Gemini API Key
    • Tavily API Key

Backend Setup

# 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 8000

Frontend Setup

cd ../frontend

# Install dependencies
npm install

# Start development server
npm start

The application will be available at:


πŸ’» Usage

1. Web Interface

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

2. API Usage

Baseline RAG (Simple)

curl -X POST http://localhost:8000/query/baseline \
  -H "Content-Type: application/json" \
  -d '{"query": "What are NVIDIA'\''s key risks?"}'

Deep Thinking RAG (Streaming)

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

3. Python Client

import 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"])

πŸ“‘ API Documentation

Endpoints

GET /

Health check endpoint.

Response: {"message": "Deep Thinking RAG API is running."}


POST /query/baseline

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..."]
}

POST /stream_query/deep_thinking

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..."]}

πŸ“Š Evaluation Results

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.

Results (n=5)

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%

Key Findings

  • βœ… 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.

Test Queries

  1. Competition Risk Analysis - Extract NVIDIA's 10-K competition risks and analyze AMD's 2024 AI GPU strategy impact
  2. Supply Chain Assessment - Evaluate supply/manufacturing disclosures and score AMD's supply posture risk (0-5)
  3. Ecosystem Lock-in Analysis - Compare NVIDIA's CUDA ecosystem with AMD's ROCm developments
  4. Customer Concentration - Analyze customer risks and build impact scenarios for workload shifts
  5. Product Cadence - Assess whether AMD's 2024-2025 roadmap targets NVIDIA's stated vulnerability windows

Running Evaluation

# Ensure server is running
uvicorn server:app --reload

# In another terminal
python evaluate.py

Results are saved to evaluation_results.csv and evaluation_summary.txt.

Running Evaluation

# Ensure server is running
uvicorn server:app --reload

# In another terminal
python evaluate.py

Results are saved to evaluation_results.csv.


πŸ“ Project Structure

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

βš™οΈ Configuration

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
}

🐳 Docker Deployment (Optional)

# 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-rag

πŸ”§ Troubleshooting

Common Issues

Issue: ModuleNotFoundError: No module named 'langchain_deepseek'

pip install langchain-deepseek

Issue: Vector stores not found

# Rebuild vector stores
python build_vector_store.py

Issue: 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=["*"],
)

πŸ“š References


πŸ‘¨β€πŸ’» Author

Siddhant Diwaker


πŸ™ Acknowledgments

  • 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

About

A multi-agent RAG system that uses iterative reasoning and hybrid retrieval to answer complex financial queries

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages