Production-grade agentic RAG system for AI-powered medical literature analysis with real-time streaming, PubMed integration, automated evaluation, and evidence-based citations.
π Live Demo: www.romedrag.me Β· π‘ API Docs: Swagger UI Β· π₯ Register β Upload PDF β Ask Questions
RO MEDRAG is an AI-powered research assistant that lets medical researchers upload PDF papers, ask natural language questions, and receive evidence-based answers with source citations, all streamed in real-time.
Unlike basic RAG demos, this system features an autonomous LangGraph agent that:
- Routes queries intelligently: decides whether to retrieve, summarize, compare, extract data, or ask for clarification
- Self-corrects: validates its own answers against source material and regenerates if grounding fails
- Re-queries automatically: reformulates search queries when initial retrieval is insufficient
- Searches live literature: falls back to PubMed's 36M+ article database when local docs aren't enough
- Measures its own quality: built-in RAGAS-style evaluation pipeline with automated metrics
Every answer is grounded in documents. Hallucination is structurally prevented.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β React Frontend β
β Dashboard Β· Chat (SSE Streaming) Β· Documents Β· PubMed Β· Eval β
β Three.js 3D DNA Β· Framer Motion Β· Audiowide/Urbanist Typography β
ββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββ
β REST + SSE
ββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββ
β FastAPI Backend β
β β
β ββββββββββββββββββββ LangGraph Agent βββββββββββββββββββββββββββ β
β β β β
β β ββββββββββββ β β
β β β Router β β Classify intent (retrieve/summarize/ β β
β β β Node β compare/extract/clarify) β β
β β ββββββ¬ββββββ β β
β β β β β
β β ββββββΌββββββ βββββββββββββββ ββββββββββββββββ β β
β β β Retrieve βββββ Reformulate βββββ Evaluate β β β
β β β (FAISS) ββββΊβ Query ββββΊβ Sufficiency β β β
β β ββββββ¬ββββββ βββββββββββββββ ββββββββββββββββ β β
β β β β β
β β ββββββΌββββββ βββββββββββββββ β β
β β β Generate ββββΊβ Validate ββββΊ Self-correction loop β β
β β β (Claude) βββββ Grounding β β β
β β ββββββ¬ββββββ βββββββββββββββ β β
β β β β β
β β ββββββΌββββββ β β
β β β Finalize β β Citations + Metrics + Confidence β β
β β ββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β Services: EmbeddingService Β· FAISSVectorStore Β· PubMedService β
β EvalService Β· ConversationMemory Β· PDFParser β
ββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
β PostgreSQL + FAISS β
β Users Β· Documents Β· β
β Chunks Β· Sessions Β· β
β Messages Β· Citations β
βββββββββββββββββββββββββββ
| Layer | Technology | Why |
|---|---|---|
| AI Agent | LangGraph (custom) | Autonomous routing, retrieval loops, self-correction |
| LLM | Claude Sonnet 4 | Best instruction-following, lowest hallucination |
| Streaming | SSE (Server-Sent Events) | Real-time token-by-token output |
| Embeddings | OpenAI text-embedding-3-small | Best price/quality ratio (1536-dim) |
| Vector DB | FAISS (IndexFlatIP) | Zero cost, cosine similarity on normalized vectors |
| Literature | PubMed E-utilities API | 36M+ medical articles, free, no API key needed |
| Evaluation | Custom RAGAS-style metrics | Faithfulness, relevancy, precision, citation accuracy |
| Backend | FastAPI + asyncpg | Async, fast, typed, production-ready |
| Database | PostgreSQL 16 | Relational integrity for citations and audit trail |
| pypdf + pdfminer fallback | Handles messy/scanned PDFs with dual-parser strategy | |
| Frontend | React 18 + Three.js | 3D DNA helix, Framer Motion animations |
| Typography | Audiowide + Urbanist | Cyber-medical display + clean readable body |
| Auth | JWT (access + refresh) + bcrypt | Stateless, secure, with token rotation |
| Deploy | Docker + GCP Cloud Run | Serverless, auto-scale, zero-downtime |
Not a simple retrieve-and-generate pipeline. The agent autonomously:
- Routes queries to the optimal action (retrieve / summarize / compare / extract / clarify)
- Re-queries with reformulated terms when initial retrieval scores are low
- Validates answers against source chunks and regenerates if grounding fails
- Maintains conversation memory across turns for multi-turn research sessions
Responses stream token-by-token via Server-Sent Events, with live status updates:
Analyzing query... β Searching documents... β Found 4 passages β Generating response...
No more staring at a loading spinner for 20 seconds.
When uploaded documents don't have enough information, search PubMed's database of 36M+ biomedical articles. Results include titles, authors, journals, abstracts, and direct links to PubMed.
Automated quality metrics inspired by RAGAS:
- Faithfulness: Is the answer grounded in retrieved context?
- Answer Relevancy: Does it address the question?
- Context Precision: Are retrieved chunks relevant?
- Citation Accuracy: Do [N] references map to real chunks?
Run the full suite or test individual queries. Track pass rates over time.
Click any citation β the original PDF opens in a modal, scrolled to the exact page. PubMed citations link directly to the article.
Toggle between dark glassmorphism and clean light mode. Persists across sessions.
Collapsible sidebar with hamburger menu, stacked layouts, touch-friendly sizing.
Non-negotiable safety constraints built into the system:
| Constraint | Implementation |
|---|---|
| Zero hallucination | LLM sees only retrieved chunks, never generates from memory |
| Mandatory citations | Every claim must include [1], [2] references |
| Insufficient evidence path | Agent returns "INSUFFICIENT_EVIDENCE" when context is absent |
| Self-validation | Agent cross-checks its own answer against sources |
| Medical disclaimer | Every response ends with " |
| Deterministic output | temperature=0 for reproducible results |
git clone https://github.com/rohithkandula19/Ro-MedRag.git
cd Ro-MedRag
cp backend/.env.example backend/.env
# Edit backend/.env with your API keysdocker-compose up --buildhttp://localhost:3000
Register β Upload a PDF β Start asking questions.
cd backend
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
mkdir -p data/uploads data/faiss_index
# Start PostgreSQL
docker run -d --name postgres -e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=healthcare_rag -p 5432:5432 postgres:16-alpine
# Start backend
uvicorn app.main:app --reload --port 8000cd frontend
npm install
npm run dev| Method | Endpoint | Description |
|---|---|---|
| POST | /api/auth/register |
Create account |
| POST | /api/auth/login |
Get JWT tokens |
| GET | /api/auth/me |
Current user |
| POST | /api/documents/upload |
Upload PDF (async processing) |
| GET | /api/documents/ |
List documents |
| DELETE | /api/documents/{id} |
Delete + remove from vector store |
| POST | /api/chat/sessions |
Create chat session |
| POST | /api/chat/sessions/{id}/query |
RAG query (standard) |
| POST | /api/chat/sessions/{id}/stream |
RAG query (SSE streaming) |
| GET | /api/chat/sessions/{id}/messages |
Chat history with citations |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/pubmed/search?q=... |
Search PubMed articles |
| POST | /api/eval/run |
Run full evaluation suite |
| POST | /api/eval/single |
Evaluate single query |
| GET | /api/viewer/{id}/pdf |
Serve PDF for citation viewer |
| GET | /api/health/ |
Health check |
Interactive docs: http://localhost:8000/api/docs
ro-medrag/
βββ backend/
β βββ app/
β β βββ main.py - FastAPI app, middleware, all route registration
β β βββ core/
β β β βββ config.py - Settings (pydantic-settings, env vars)
β β β βββ security.py - JWT auth, bcrypt, dependencies
β β β βββ logging.py - Structured JSON logging
β β βββ db/
β β β βββ database.py - Async SQLAlchemy engine + sessions
β β βββ models/
β β β βββ user.py - User, Document, ChatSession ORM models
β β β βββ chat.py - Message, Citation models
β β β βββ document.py - Document, DocumentChunk models
β β βββ api/routes/
β β β βββ auth.py - Register, login, me
β β β βββ documents.py - Upload, list, delete
β β β βββ chat.py - Sessions, messages, query
β β β βββ streaming.py - SSE streaming endpoint
β β β βββ pubmed.py - PubMed search API
β β β βββ eval.py - RAG evaluation endpoints
β β β βββ viewer.py - PDF serving for citation viewer
β β β βββ admin.py - Admin statistics
β β β βββ health.py - Health checks
β β βββ services/
β β βββ rag_pipeline.py - Core RAG: parse β chunk β embed β retrieve β generate
β β βββ agent/ - β
LangGraph Agent System
β β β βββ state.py - AgentState dataclass (shared graph state)
β β β βββ tools.py - 6 agent tools (retrieval, reformulation, comparison,
β β β β extraction, sufficiency evaluation, answer validation)
β β β βββ nodes.py - 8 graph nodes (route, retrieve, evaluate, reformulate,
β β β β compare, generate, validate, finalize)
β β β βββ graph.py - MedRAGAgent orchestrator with conditional loops
β β βββ pubmed_service.py - PubMed E-utilities integration
β β βββ eval_service.py - RAGAS-style evaluation metrics
β β βββ chat_service.py - Session & query orchestration
β β βββ document_service.py - Upload & async ingestion
β β βββ user_service.py - Auth CRUD
β βββ requirements.txt
β βββ Dockerfile
β βββ .env.example
βββ frontend/
β βββ src/
β β βββ App.jsx - Route definitions (6 pages)
β β βββ components/
β β β βββ ui/Layout.jsx - Collapsible icon sidebar, theme toggle
β β β βββ auth/LoginPage.jsx - Login/register with 3D background
β β β βββ dashboard/Dashboard.jsx - Stats, quick actions, 3D hero
β β β βββ chat/ChatPage.jsx - β
Streaming chat with SSE, citation cards, PDF viewer
β β β βββ documents/DocumentsPage.jsx - Drag-drop upload, status tracking
β β β βββ evaluation/EvaluationPage.jsx - β
RAG metrics dashboard
β β β βββ pubmed/PubMedPage.jsx - β
PubMed article search
β β β βββ 3d/Scene3D.jsx - Three.js DNA helix + particles
β β βββ store/
β β β βββ authStore.js - Zustand auth state
β β β βββ themeStore.js - Dark/light theme persistence
β β βββ services/api.js - Axios client with JWT interceptors
β β βββ styles/globals.css - Design system (Audiowide + Urbanist)
β βββ index.html
β βββ vite.config.js
β βββ package.json
βββ scripts/
β βββ deploy_gcp.sh - Full GCP deployment (Cloud Run + Cloud SQL)
βββ docker-compose.yml
βββ README.md
The LangGraph agent uses a graph-based workflow with conditional edges:
Query β Router β [Action Decision]
β
βββββββββββΌβββββββββββ¬βββββββββββ
βΌ βΌ βΌ βΌ
Retrieve Compare Extract Clarify
β β β β
βΌ β β βΌ
ββEvaluateββ β β Finalize
βSufficient?β β β
ββββ¬ββββ¬ββββ β β
Yes β β No β β
β βΌ β β
β Reformulate β
β β β β
β ββΊRetrieve β
βΌ βΌ
Generate ββββββββββββββββββ
β
βΌ
Validate βββ
β β Failed
β ββΊRegenerate
βΌ
Finalize β Response + Citations + Metrics
Key behaviors:
- Retrieval loop: Up to 3 attempts with automatic query reformulation
- Validation loop: Up to 2 regeneration attempts if grounding check fails
- Conversation memory: Agent remembers previous turns for multi-turn research
- Confidence scoring: Average relevance score across retrieved chunks
| Metric | What It Measures | How |
|---|---|---|
| Faithfulness | Is every claim supported by context? | LLM-as-judge grounding check |
| Answer Relevancy | Does the answer address the question? | LLM-as-judge relevance rating |
| Context Precision | Are retrieved chunks relevant? | Keyword overlap + expected term matching |
| Citation Accuracy | Do [N] references exist in retrieved chunks? | Regex extraction + set comparison |
Run via API: POST /api/eval/run or from the Evaluation page in the UI.
chmod +x scripts/deploy_gcp.sh
./scripts/deploy_gcp.sh YOUR_PROJECT_ID us-central1The script handles: Cloud SQL setup, GCS bucket with versioning, Secret Manager for API keys, Artifact Registry for Docker images, Cloud Run deployment with auto-scaling.
Estimated cost: ~$22/month for light usage.
β’ Architected LangGraph agentic RAG system with autonomous query routing,
iterative retrieval with reformulation, and self-correcting answer validation
β’ Implemented real-time SSE streaming for token-by-token LLM responses
with multi-phase status updates across the agent pipeline
β’ Integrated PubMed E-utilities API as a live literature search tool,
enabling the agent to augment local documents with 36M+ medical articles
β’ Built automated RAG evaluation pipeline measuring faithfulness, answer
relevancy, context precision, and citation accuracy (RAGAS-inspired)
β’ Designed citation-linked PDF viewer with page-level deep linking
for source verification in a medical research context
β’ Engineered full-stack React + FastAPI application with JWT auth,
async PostgreSQL, FAISS vector search, and Docker deployment
β’ Created responsive UI with dark/light theme, collapsible icon sidebar,
3D Three.js visualization, and Audiowide/Urbanist typography system
This software is not FDA approved and must not be used for clinical decision-making.
For research and educational purposes only. Always consult qualified healthcare professionals for medical decisions.
MIT. For research and educational purposes.