Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

RAG Assistant

A LangChain-based RAG assistant with both online and offline capabilities, built using LangGraph for intelligent document retrieval and answer generation. TL;DR: The most important sections in the README are: Architecture Overview, Data Freshness Strategy, Setup Instructions(if you intend to run it), Known Limitations & Future Improvement ideas and Resources.

Architecture Overview

Graph Design & State Management

The assistant uses a LangGraph StateGraph with conditional routing based on operating mode and document quality:

State Structure:

  • question: User's query
  • documents: Retrieved documents from vector DB or web search
  • generation: Final LLM-generated answer
  • documents_good_enough: Quality flag (Yes/No) from grading step
  • offline_mode: Boolean flag to switch between modes
  • query_rewritten: Boolean flag to track query transformation

Node Structure:

The workflow diagrams below show the complete node structure and routing logic:

Online Mode Workflow

Uses external APIs (Google Gemini, Tavily) for enhanced search and generation:

Online Mode Workflow

Flow:

  1. retrieve → Fetches documents from local ChromaDB vector database
  2. grade_documents → LLM-based relevance checking using Gemini
  3. Conditional routing:
    • If documents are good → generate answer with Gemini
    • If documents are poor → transform_query (LLM rewrites query) → web_search_node (Tavily API) → generate

Offline Mode Workflow

Completely self-contained, no internet or API calls required:

Offline Mode Workflow

Flow:

  1. retrieve → Fetches documents from local ChromaDB vector database
  2. grade_documents → Similarity-based scoring (cosine similarity > 0.5 threshold)
  3. generate → Local Qwen3-4B-Instruct model (4 billion parameters)

Operating Modes

Offline Mode

What it uses:

  • Local Vector Database: ChromaDB with 1660+ documents (LangChain/LangGraph documentation)
  • Local Embeddings: BAAI/bge-small-en-v1.5 (384-dimensional embeddings)
  • Local LLM: Qwen3-4B-Instruct (8GB model, ~4 billion parameters)
  • Similarity Grading: Cosine similarity scoring (no LLM needed)

How it works:

  1. User question → Embedded using local model
  2. Vector search retrieves top 4 relevant documents
  3. Each document scored using cosine similarity (threshold: 0.5)
  4. Relevant documents → Qwen3-4B generates answer locally
  5. Answer includes data freshness timestamp

Advantages:

  • ✅ No internet required
  • ✅ No API costs
  • ✅ Complete privacy (no data leaves your machine)
  • ✅ Fast retrieval (local vector DB)

Limitations:

  • ⚠️ Data freshness limited to last update.py run
  • ⚠️ 4B model may struggle with complex queries (see "Known Limitations" below)

Online Mode

What it uses:

  • Local Vector Database: Same ChromaDB (primary source)
  • Google Gemini 2.5-flash: For LLM grading and answer generation
  • Tavily Search API: Web search when local docs insufficient
  • Query Rewriter: Gemini optimizes queries for web search

How it works:

  1. User question → Local vector search (same as offline)
  2. Documents graded by Gemini LLM (more sophisticated than similarity)
  3. If documents good: Gemini generates answer from local docs
  4. If documents poor:
    • Gemini rewrites query for better web search
    • Tavily searches the web
    • Web results + local docs → Gemini generates answer

Advantages:

  • ✅ Access to latest information (via web search)
  • ✅ More sophisticated LLM (Gemini vs. local 4B model)
  • ✅ Better query understanding and rewriting

Limitations:

  • ⚠️ Requires API keys (costs money)
  • ⚠️ Still depends heavily on local data (see "Known Limitations" below)
  • ⚠️ Internet connection required

Switching Between Modes

Command Line:

# Online mode (default)
python main.py "Your question here"

# Offline mode (add --offline flag)
python main.py "Your question here" --offline

Programmatic:

# In code, set offline_mode in the initial state
inputs = {
    "question": "What is LangGraph?",
    "offline_mode": True  # or False for online
}

The graph automatically routes based on the offline_mode flag:

  • route_after_transform() → web search (online) vs. re-retrieve (offline)
  • grade_documents() → LLM grading (online) vs. similarity scoring (offline)
  • generate() → Gemini (online) vs. Qwen3-4B (offline)

Data Freshness Strategy

Offline Mode: Pre-Built Vector Database

How data was prepared:

  1. setup.py downloads documentation from:

    • https://langchain-ai.github.io/langgraph/llms.txt (index of documentation URLs)
    • https://python.langchain.com/llms.txt (LangChain documentation index)
    • https://langchain-ai.github.io/langgraph/llms-full.txt (complete docs in single file)
  2. URLs are crawled, text extracted, and split into chunks (1000 chars, 200 overlap)

  3. Embedded using BAAI/bge-small-en-v1.5 and stored in ChromaDB

  4. Timestamp saved to vector_db/.last_update

How users update the data:

# Run update.py when online
python update.py

What update.py does:

  • Backs up current vector_db/ to vector_db_backup/
  • Re-downloads all documentation (same sources as setup.py)
  • Rebuilds vector database in-place
  • Updates timestamp file
  • If update fails, backup can be restored

Data freshness notification:

When you run the application, you'll see:

Loaded vector database with 1660 documents.
Database last updated: October 31, 2025 at 01:29 PM

This timestamp is displayed at startup, showing when the vector database was last refreshed.

Online Mode: Hybrid Approach

Primary source: Local vector database (same as offline)

Fallback: When local documents are insufficient:

  1. Gemini rewrites the query for better web search
  2. Tavily Search API fetches 3 top web results
  3. Web content + local docs → Gemini generates comprehensive answer

Why this approach:

  • Local docs are high-quality, curated LangChain/LangGraph documentation
  • Web search adds real-time information when needed
  • Combines speed (local) with freshness (web)

Setup Instructions

Prerequisites

System Requirements:

  • Disk Space: ~10 GB free space (models + vector database + dependencies)
  • RAM:
    • Offline mode (CPU): 24-32 GB RAM recommended (4B parameter model in FP32 + inference overhead)
    • Offline mode (GPU): 8 GB RAM + GPU with 12-16 GB VRAM (model in FP16 on GPU)
    • Online mode: 8 GB RAM minimum (uses cloud APIs, lighter local requirements)

Software:

Step 1: Clone Repository

git clone https://github.com/AviSimkin/LangChain-assistant.git
cd LangChain-assistant

Step 2: Create .env File

⚠️ REQUIRED BEFORE RUNNING

Create a .env file in the project root:

# Copy the example file
cp .env.example .env

Edit .env with your API keys:

# Required for online mode (optional for offline-only usage)
GOOGLE_API_KEY=your_actual_google_api_key_here
TAVILY_API_KEY=your_actual_tavily_api_key_here

Note: If you only plan to use offline mode, you can leave the API keys as placeholders.

Step 3: Choose Setup Method

Option A: Docker (Recommended - Cross-Platform)

# Build the image (Python 3.13, all dependencies)
docker-compose build

# Run setup inside container (downloads models, builds vector DB)
docker-compose run --rm rag-assistant python setup.py

# Ask a question!
docker-compose run --rm rag-assistant python main.py "What is LangGraph?"

Option B: Local Installation (Python 3.13+)

# Install dependencies (pinned versions for reproducibility)
pip install -r requirements.txt

# Download models and build vector database (~10 min)
python setup.py

# Ask a question!
python main.py "What is LangGraph?"

Option C: VS Code DevContainer (Development)

  1. Install Docker + VS Code + DevContainers extension
  2. Open folder in VS Code
  3. Click "Reopen in Container" when prompted
  4. Run python setup.py in integrated terminal

Example Runs

Offline Mode (no internet, no API costs):

$ python main.py "How do I add persistence to a LangGraph agent?" --offline

======================================================================
Question: How do I add persistence to a LangGraph agent?
Mode: OFFLINE
======================================================================

→ retrieve
→ grade_documents
→ generate

======================================================================
ANSWER:
======================================================================
To add persistence to a LangGraph agent, you need to use a checkpointer...
[Answer continues with local model generation]
======================================================================

Online Mode (with web search fallback):

$ python main.py "What are the latest features in LangGraph?"

======================================================================
Question: What are the latest features in LangGraph?
Mode: ONLINE
======================================================================

→ retrieve
→ grade_documents
→ transform_query
→ web_search_node
→ generate

======================================================================
ANSWER:
======================================================================
Based on recent updates, LangGraph has introduced several new features...
[Answer combines local docs + web search results]
======================================================================

Version Specifications

Component Version Notes
Python 3.13+ Required (tested on 3.13.9)
LangChain 1.0.2 Core framework
LangGraph 1.0.1 State machine
PyTorch 2.9.0 Local LLM inference
Transformers 4.57.1 HuggingFace models
ChromaDB 1.3.0 Vector database
Qwen3-4B-Instruct 2507 Local LLM (8GB download)
BAAI/bge-small-en-v1.5 latest Embedding model (384-dim)

All dependencies are pinned in requirements.txt for reproducibility.

Known Limitations & Future Improvement ideas

Current Drawbacks

  1. Online mode data dependency:

    • Online mode still depends heavily on local vector database that may be outdated
    • Next-step solution: Intelligently download only relevant web pages using descriptions in llms.txt, rather than pre-downloading everything
    • Not implemented as it felt too sophisticated for a home assignment
  2. Offline model quality:

    • Offline mode uses a 4B parameter model that may not be good enough for complex queries
    • Next-step solution: Fine-tune the model on LangChain/LangGraph-specific Q&A pairs
    • Not implemented as fine-tuning is time-consuming and too fancy for a home assignment
  3. Web content availability:

    • Some URLs in llms.txt returned 404 errors or were unavailable during crawling
    • Next-step solution: Implement more robust crawling (retry logic, alternative sources) or supplement with targeted web searches
    • Not handled at this stage; naive crawling was sufficient for demonstration purposes
  4. Vector database optimization:

    • The vector database implementation is fairly naive with default parameters
    • No research was conducted on optimal chunk size, overlap, or embedding parameters
    • Retrieval speed and accuracy were not optimized
    • Next-step solution: Experiment with different chunking strategies, embedding models, and retrieval parameters (e.g., similarity thresholds, number of results, reranking) and probably a different vector db system (and not the default chromaDB)
    • Not implemented as parameter tuning would require extensive benchmarking beyond the scope of a home assignment

Project Structure

.
├── main.py                 # Main RAG application with LangGraph workflow
├── setup.py               # Initial setup (downloads models, builds vector DB)
├── update.py              # Update vector database with latest docs
├── vector_db_utils.py     # Vector database creation/loading utilities
├── requirements.txt       # Pinned Python dependencies (see versions above)
├── test_portability.py    # Comprehensive system validation script
├── Dockerfile             # Docker image (Python 3.13-slim-bookworm)
├── docker-compose.yml     # Docker Compose configuration
├── .env.example           # Template for environment variables
└── images/                # Workflow diagrams
    ├── online_langgraph_chart.png
    └── offline_langgraph_chart.png

Troubleshooting

Missing .env File

Error: WARNING: GOOGLE_API_KEY not set in .env file Solution: Create .env file with your API keys (see Step 2 above)

Docker Issues

  • "No space left on device": Clean Docker: docker system prune -a
  • Permission errors: On Linux/Mac, you may need sudo
  • Slow builds: First build downloads ~10GB of models (one-time)

Python Version Issues

Error: Module compatibility issues Solution: Use Python 3.13+ (check with python --version)

Testing Your Setup

Run the portability test to validate everything:

python test_portability.py

This checks all dependencies, models, vector DB, and runs functional tests.

Resources

Primary Tutorial

This project was built based on the LangGraph CRAG (Corrective RAG) tutorial:

  • Source: https://langchain-ai.github.io/langgraph/tutorials/rag/langgraph_crag/
  • Modifications made:
    • Updated to work with newer LangChain modules (1.0.2+)
    • Added complete offline mode with local Qwen3-4B model, including conditional nodes to skip web-based search and too many llm calls
    • Implemented similarity-based document grading for offline mode
    • Built vector database from LangChain/LangGraph documentation (llms.txt + llms-full.txt)
    • Added timestamp tracking for data freshness
    • Fixed compatibility issues and deprecation warnings

Development Tools

  • Perplexity Chat: Used for debugging and troubleshooting specific issues in the logic implementation stage
  • GitHub Copilot (Agent Mode): Used for writing tests, Docker configuration, README editing, and code refactoring

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages