A sophisticated Retrieval Augmented Generation (RAG) system built with LangGraph, LangChain, and OpenAI, featuring an intelligent agent-based architecture for semantic document search and question-answering.
DocRAG is a production-ready RAG system that combines document retrieval with agentic intelligence to answer complex questions about loaded documents. It leverages modern AI frameworks to provide accurate, context-aware responses with source attribution.
Key Innovation: Integrates ReAct (Reasoning + Acting) agent pattern within a LangGraph workflow for enhanced reasoning capabilities over retrieved documents.
- π Semantic Search: FAISS-powered vector similarity search for intelligent document retrieval
- π§ Agentic Architecture: Built-in ReAct agent for multi-step reasoning and action planning
- π Multi-format Support: Process documents from various sources (URLs, PDFs, text)
- β‘ Streaming Support: Real-time response generation with streaming capabilities
- π Response Tracking: Built-in history tracking and performance metrics
- π¨ Interactive UI: Streamlit-based web interface for easy interaction
- π Source Attribution: Retrieve and display relevant source documents for verification
- βοΈ Configurable: Easy customization of chunk sizes, overlap, and LLM parameters
The system follows a sophisticated multi-layer architecture:
User Input
β
Streamlit UI (streamlit_app.py)
β
Graph Builder (LangGraph StateGraph)
βββ Retriever Node (Vector Search)
β βββ FAISS Vector Store
β
βββ Responder Node (ReAct Agent)
βββ OpenAI GPT-4o LLM
βββ Wikipedia Tool
βββ Wikidata Tool
β
Formatted Response + Source Docs
| Component | Purpose |
|---|---|
| document_processor.py | Ingests and chunks documents from URLs |
| vectorstore.py | FAISS-based vector database management |
| graph_builder.py | Orchestrates RAG workflow with LangGraph |
| reactnode.py | Implements ReAct agent with retrieval tools |
| rag_state.py | Defines application state schema |
| streamlit_app.py | Interactive web UI for end users |
- LangGraph - Workflow orchestration and state management
- LangChain - LLM integration and chain building
- OpenAI GPT-4o - Large Language Model
- FAISS - Fast approximate nearest neighbor search
- Pydantic - Data validation and settings management
- Streamlit - Interactive web interface
- BeautifulSoup4 - Web scraping for document extraction
- Requests - HTTP client for URL content fetching
- Wikipedia API - External knowledge retrieval
- Wikidata - Structured knowledge integration
- Python 3.9+
- OpenAI API Key
- Clone the repository
git clone https://github.com/yourusername/docRAG.git
cd docRAG- Create virtual environment
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # macOS/Linux- Install dependencies
pip install -r requirements.txt- Configure environment
# Create .env file
echo OPENAI_API_KEY=your_api_key_here > .env- Verify installation
python -c "from src.config.config import Config; print('β Installation successful')"streamlit run streamlit_app.pyThe app will:
- Initialize the RAG system with default documents
- Load 2 articles on LLM agents and diffusion models
- Create a vector database with document chunks
- Present an interactive search interface
Features in UI:
- Real-time question input
- Source document visualization
- Response time tracking
- Search history (last 3 queries)
from src.config.config import Config
from src.document_ingestion.document_processor import DocumentProcessor
from src.vectorstore.vectorstore import VectorStore
from src.graph_builder.graph_builder import GraphBuilder
# Initialize components
llm = Config.get_llm()
doc_processor = DocumentProcessor()
vector_store = VectorStore()
# Process documents
urls = ["https://example.com/article1", "https://example.com/article2"]
documents = doc_processor.process_urls(urls)
vector_store.create_vectorstore(documents)
# Build and run RAG workflow
graph = GraphBuilder(
retriever=vector_store.as_retriever(),
llm=llm
)
graph.build()
# Query
result = graph.run("Your question here")
print(result["answer"])Edit src/config/config.py:
class Config:
CHUNK_SIZE = 500 # Document chunk size
CHUNK_OVERLAP = 50 # Overlap between chunks
LLM_MODEL = "openai:gpt-4o" # Model selection
Default_URLS = [...] # Default documentsdocRAG/
βββ src/
β βββ config/ # Configuration management
β βββ document_ingestion/ # Document processing pipeline
β βββ vectorstore/ # Vector database operations
β βββ graph_builder/ # LangGraph workflow builder
β βββ nodes/ # Graph nodes (retrieval, generation)
β βββ state/ # State definitions
βββ data/
β βββ url.txt # Sample URLs for processing
βββ streamlit_app.py # Web interface
βββ main.py # CLI entry point
βββ requirements.txt # Python dependencies
βββ pyproject.toml # Project metadata
βββ README.md # This file
- Maintains conversation history
- Tracks retrieved documents
- Stores intermediate results
- Manages agent state
- Document Ingestion: Fetch and parse documents from URLs
- Chunking: Split documents into overlapping chunks
- Embedding: Convert chunks to vector embeddings
- Indexing: Store in FAISS for fast retrieval
- Query Embedding: Convert user question to embedding
- Retrieval: Find top-K similar documents (default K=3-5)
- ReAct Agent: Multi-step reasoning with access to:
- Retrieved context
- Wikipedia for external knowledge
- Wikidata for structured facts
- Response Generation: Synthesize final answer from reasoning steps
- Documentation Search: Intelligent QA over technical documentation
- Research Assistant: Quick answers from academic papers
- Knowledge Base: Internal company documentation search
- Educational Tool: Learning platform for complex topics
- Content Analysis: Extract insights from document collections
The system tracks:
- Response Time: Total latency from query to answer
- Retrieval Quality: Relevance of retrieved documents
- Token Usage: Input/output tokens for cost tracking
- Error Rates: System reliability metrics
1. User submits question
β
2. Query embedding generation
β
3. Vector similarity search (FAISS)
β
4. Top documents retrieved
β
5. ReAct Agent initialization
β
6. Multi-step reasoning:
- Analyze question
- Search retrieved docs
- Query external tools (Wikipedia/Wikidata)
- Synthesize information
β
7. Generate structured response
β
8. Return answer + source attribution + metrics
The system includes robust error handling for:
- Missing API keys
- Invalid URLs
- Document parsing failures
- Vector store initialization errors
- LLM API rate limits
All errors are caught and user-friendly messages are displayed in the Streamlit UI.
- API keys stored in
.envfile (not committed) - Input validation on user queries
- Rate limiting for API calls
- Secure document storage
This project demonstrates:
- LangGraph state graph orchestration
- ReAct Pattern implementation (Reasoning + Acting)
- Vector Database usage (FAISS)
- LLM Integration with LangChain
- Agentic AI architecture
- Streamlit application development
- Full-stack RAG system design