Spaces:
Sleeping
title: Advanced RAG API
emoji: π
colorFrom: blue
colorTo: indigo
sdk: docker
app_port: 8000
pinned: false
GraphRAG & Knowledge Graph AI
Assignment #10 β GraphRAG-powered retrieval system with Neo4j, entity extraction, graph traversal, and hybrid graph+vector search.
Organization: Excellence Technologies Pvt Ltd
Phase: Phase 2 β LangChain & Advanced RAG
Table of Contents
- Architecture Overview
- Tech Stack
- Features
- Entity Types
- Relationship Types
- System Architecture Diagram
- Prerequisites
- Quick Start
- Environment Variables
- API Endpoints
- Neo4j Graph Schema
- Usage Guide
- Testing
- Evaluation
- Troubleshooting
- Project Structure
Architecture Overview
User β Next.js Frontend (localhost:3000)
β
Django REST Backend (localhost:8000)
βββ Auth (JWT) β User management
βββ Documents β Upload, ingestion, status tracking
βββ Query β Graph/Vector/Hybrid retrieval + LLM answer
βββ Graph β Cypher queries, entity details, paths, stats
βββ Communities β Louvain community detection
βββ Evaluation β Accuracy, faithfulness, answer relevancy
β
Neo4j (bolt://localhost:7687) ChromaDB (local/chroma_db)
βββ Entity nodes βββ Vector embeddings
βββ Relationship edges
βββ Community labels
β
Groq (Llama 3.3 70B) / Google (Gemini 2.0 Flash)
Tech Stack
| Layer | Technology |
|---|---|
| Backend | Django 4.2, Django REST Framework, SimpleJWT |
| Graph DB | Neo4j 5.12 (Docker) |
| Vector DB | ChromaDB (local) |
| LLM | Groq Llama 3.3 70B (default), Gemini 2.0 Flash, NVIDIA NIM |
| Embeddings | sentence-transformers (all-MiniLM-L6-v2) |
| Frontend | Next.js 14, React 18, TypeScript, Tailwind CSS |
| Graph Viz | react-force-graph-2d (WebGL) |
| State | Zustand |
| Deployment | Docker Compose (Neo4j + Backend + Frontend) |
Features
Core Pipeline
- Document Upload β PDF, TXT, MD, DOCX, CSV, JSON, HTML, XML (β€10MB)
- Automated Entity Extraction β 9 entity types via LLM structured output
- Automated Relationship Extraction β 10 relationship types with confidence scores
- Entity Resolution β RapidFuzz fuzzy matching + LLM disambiguation
- Graph Construction β Neo4j nodes/edges with properties
Retrieval Modes
- Graph Retrieval β Cypher subgraph traversal (neighborhood, multi-hop)
- Vector Retrieval β ChromaDB cosine similarity search
- Hybrid Retrieval β Merged graph + vector context
Query Capabilities
- Natural Language Query β Question β answer with citations
- NL-to-Cypher β Schema-aware text β Cypher translation
- Multi-Hop Reasoning β Up to 4-hop relationship chains
- Community Detection β Louvain algorithm for entity clustering
Frontend (7 Screens)
- Query + Graph Split View β Main workspace with real-time graph
- Graph Explorer β Force-directed visualization with search/filter
- Community View β Community cards with graph sub-view
- Multi-Hop Reasoning β Step-by-step reasoning path display
- Retrieval Comparison β Side-by-side Graph vs Vector vs Hybrid
- Document Management β Upload with progress tracking
- Evaluation Dashboard β Metric visualization
Entity Types
| # | Type | Example |
|---|---|---|
| 1 | PERSON | "John Smith" |
| 2 | ORGANIZATION | "Google" |
| 3 | PRODUCT | "ChatGPT" |
| 4 | TECHNOLOGY | "React" |
| 5 | LOCATION | "San Francisco" |
| 6 | EVENT | "WWDC 2024" |
| 7 | DATE | "January 2024" |
| 8 | CONCEPT | "microservices" |
| 9 | DOCUMENT | "Annual Report 2024" |
Relationship Types
| # | Type | Example |
|---|---|---|
| 1 | WORKS_AT | Person β Organization |
| 2 | MANAGES | Person β Person/Project |
| 3 | PART_OF | Component β System |
| 4 | DEPENDS_ON | Service β Service |
| 5 | CREATED_BY | Product β Person |
| 6 | LOCATED_IN | Entity β Location |
| 7 | RELATED_TO | General association |
| 8 | COMPETES_WITH | Organization β Organization |
| 9 | PARTNER_OF | Organization β Organization |
| 10 | SUCCEEDED_BY | Event/Version β Event/Version |
System Architecture Diagram
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FRONTEND (Next.js) β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββββ β
β β Query β β Graph β βCommunity β β Retrieval β β
β β + Graph β β Explorer β β View β β Comparison β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββββ β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β Multi- β βDocument β βEval β β
β β Hop β βUpload β βDashboard β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
βββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββ
β REST API (JWT)
βββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββ
β BACKEND (Django REST) β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββββ β
β β Auth β βDocument β β Query β β Graph API β β
β β (JWT) β β CRUD β β Engine β β (Cypher) β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββββ β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββββ β
β βCommunity β β NLβ β β Multi- β β Evaluation β β
β βDetection β βCypher β βHop β β Engine β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββββ β
βββββββββββββ¬ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββ
β β
βββββββββββββ΄βββββββββββ βββββββββββββ΄ββββββββββββββββββββββββ
β Neo4j 5.12 β β ChromaDB β
β βββββββββββββββββ β β βββββββββββββββββββββββββββββββ β
β β :Person β β β β Vector embeddings β β
β β :Organization β β β β (all-MiniLM-L6-v2) β β
β β :Technology β β β β cosine similarity search β β
β β :Concept β β β βββββββββββββββββββββββββββββββ β
β β ... (9 types) β β ββββββββββββββββββββββββββββββββββββ
β βββββββββββββββββ β
β βββββββββββββββββ β
β β :WORKS_AT β β
β β :MANAGES β β
β β :DEPENDS_ON β β
β β ... (10 types)β β
β βββββββββββββββββ β
β βββββββββββββββββ β
β β community_id β β
β β (Louvain) β β
β βββββββββββββββββ β
ββββββββββββββββββββββββ
Prerequisites
- Docker & Docker Compose
- Node.js 18+ (for local frontend dev)
- Python 3.10+ (for local backend dev)
- LLM API key (Groq, Google, or NVIDIA)
Quick Start
1. Clone & configure
cd 07.graphrag-knowledge-ai
cp .env.example .env
# Edit .env with your API keys (at least GROQ_API_KEY or GOOGLE_API_KEY)
2. Start with Docker Compose
docker compose up --build
This starts:
- Neo4j β
http://localhost:7474(browser) /bolt://localhost:7687(driver) - Backend β
http://localhost:8000/api/ - Frontend β
http://localhost:3000
3. Create a user account
curl -X POST http://localhost:8000/api/auth/register/ \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin123", "email": "admin@example.com"}'
4. Login & get JWT token
curl -X POST http://localhost:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin123"}'
# Response: {"access": "...", "refresh": "..."}
5. Upload a document
curl -X POST http://localhost:8000/api/documents/upload/ \
-H "Authorization: Bearer <your_access_token>" \
-F "file=@sample_documents/sample_tech.txt"
6. Open the frontend
Navigate to http://localhost:3000 and log in with your credentials.
Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
SECRET_KEY |
Yes | β | Django secret key (50+ chars) |
DEBUG |
Yes | True |
Django debug mode |
ALLOWED_HOSTS |
Yes | localhost,127.0.0.1 |
Comma-separated hostnames |
DB_ENGINE |
Yes | sqlite |
Database engine (sqlite or postgres) |
NEO4J_URI |
Yes | bolt://localhost:7687 |
Neo4j bolt URI |
NEO4J_USERNAME |
Yes | neo4j |
Neo4j username |
NEO4J_PASSWORD |
Yes | password |
Neo4j password |
CHROMADB_MODE |
Yes | local |
local or cloud |
CHROMADB_DIR |
Yes | chroma_db |
ChromaDB storage directory |
GROQ_API_KEY |
* | β | Groq API key (for Llama 3.3 70B) |
GROQ_MODEL |
No | llama-3.3-70b-versatile |
Groq model name |
GOOGLE_API_KEY |
* | β | Google Gemini API key |
GOOGLE_MODEL |
No | gemini-2.0-flash |
Gemini model name |
NVIDIA_API_KEY |
* | β | NVIDIA NIM API key |
NVIDIA_MODEL |
No | meta/llama-3.1-70b-instruct |
NVIDIA model name |
LANGCHAIN_TRACING_V2 |
No | false |
Enable LangSmith tracing |
* At least one LLM provider API key is required.
API Endpoints
Authentication
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/auth/register/ |
Register new user |
| POST | /api/auth/login/ |
Login (returns JWT) |
| POST | /api/auth/token/refresh/ |
Refresh access token |
Documents
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/documents/upload/ |
Upload document (runs ingestion in background) |
| GET | /api/documents/ |
List user documents |
| GET | /api/documents/{id}/ |
Get document details |
| DELETE | /api/documents/{id}/ |
Delete document + graph/vector data |
Query
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/query/ |
Main query (supports graph, vector, hybrid modes) |
| POST | /api/query/graph-only/ |
Graph-only retrieval |
| POST | /api/query/vector-only/ |
Vector-only retrieval |
| POST | /api/query/compare/ |
Compare all 3 retrieval modes side-by-side |
Graph
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/graph/ |
Get graph data (nodes + edges) |
| GET | /api/graph/entity/{name}/ |
Entity detail (neighbors, descriptions) |
| GET | /api/graph/path/?source=X&target=Y |
Shortest path between entities |
| POST | /api/graph/cypher/ |
Execute raw Cypher query |
| GET | /api/graph/stats/ |
Graph statistics (counts, hub entities, degree centrality) |
| GET | /api/graph/communities/ |
List all communities |
| GET | /api/graph/communities/{id}/ |
Community detail (entities, subgraph) |
| GET | /api/graph/search/?q=X |
Search entities by name |
Evaluation
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/evaluation/ |
Run evaluation against stored question-answer pairs |
Legacy
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/query/cypher/ |
NL-to-Cypher translation |
| POST | /api/query/shortest-path/ |
Shortest path (legacy) |
Total: 21 endpoints
Neo4j Graph Schema
Node Labels (9 types)
(:Person {name, description, source_document, community_id})
(:Organization {name, description, source_document, community_id})
(:Product {name, description, source_document, community_id})
(:Technology {name, description, source_document, community_id})
(:Location {name, description, source_document, community_id})
(:Event {name, description, source_document, community_id})
(:Date {name, description, source_document, community_id})
(:Concept {name, description, source_document, community_id})
(:Document {name, description, source_document, community_id})
Relationship Types (10 types)
(:Person)-[:WORKS_AT {description, confidence}]->(:Organization)
(:Person)-[:MANAGES {description, confidence}]->(:Person)
(:Person)-[:PART_OF {description, confidence}]->(:Organization)
(:Technology)-[:DEPENDS_ON {description, confidence}]->(:Technology)
(:Product)-[:CREATED_BY {description, confidence}]->(:Person)
(:Organization)-[:LOCATED_IN {description, confidence}]->(:Location)
(:Entity)-[:RELATED_TO {description, confidence}]->(:Entity)
(:Organization)-[:COMPETES_WITH {description, confidence}]->(:Organization)
(:Organization)-[:PARTNER_OF {description, confidence}]->(:Organization)
(:Event)-[:SUCCEEDED_BY {description, confidence}]->(:Event)
Indexes
CREATE CONSTRAINT unique_entity_name IF NOT EXISTS FOR (e:Entity) REQUIRE (e.name, e.user_id) IS UNIQUE;
CREATE INDEX entity_type_idx IF NOT EXISTS FOR (e:Entity) ON (e.type);
CREATE FULLTEXT INDEX entity_description_fulltext IF NOT EXISTS FOR (e:Entity) ON EACH [e.description, e.name];
Graph Schema Diagram
erDiagram
PERSON ||--o{ WORKS_AT : ""
PERSON ||--o{ MANAGES : ""
PERSON ||--o{ PART_OF : ""
TECHNOLOGY ||--o{ DEPENDS_ON : ""
PRODUCT ||--o{ CREATED_BY : ""
ORGANIZATION ||--o{ LOCATED_IN : ""
ENTITY ||--o{ RELATED_TO : ""
ORGANIZATION ||--o{ COMPETES_WITH : ""
ORGANIZATION ||--o{ PARTNER_OF : ""
EVENT ||--o{ SUCCEEDED_BY : ""
Usage Guide
Upload Documents
- Navigate to Documents in the sidebar
- Click Upload and select a file (PDF, TXT, MD, DOCX, CSV, JSON, HTML, XML)
- Watch real-time ingestion progress (parsing β chunking β extraction β graph building)
- Status changes to Completed when done
Query the Knowledge Graph
- Type a natural language question in the main query bar
- Select retrieval mode: Graph, Vector, or Hybrid (default)
- View the answer with citations
- See the multi-hop reasoning path (if applicable)
- The graph highlights relevant entities in real-time
Explore the Graph
- Click Graph Explorer in the sidebar
- Use Search to find entities by name
- Zoom with scroll wheel, pan with click-drag
- Click a node to view entity details in the slide-out panel
- Use Filter to show/hide entity types
- Adjust Depth to control traversal level
Compare Retrieval Modes
- Navigate to Retrieval Comparison
- Enter a query
- View side-by-side results for Graph, Vector, and Hybrid
- Compare answer quality, response time, and context sources
Community Detection
- Navigate to Communities
- View auto-detected entity clusters
- Click a community to see its entities and subgraph
- Community summaries provide thematic overviews
Testing
Backend Unit Tests
cd backend
python manage.py test graphrag.tests_comprehensive
# 112 tests, ~57 seconds
Frontend E2E Tests (Playwright)
cd frontend
npm run test:e2e:install # Install Chromium
npm run test:e2e # Run Playwright tests
API Smoke Test
# Health check
curl http://localhost:8000/api/health/
# Full flow
curl -X POST http://localhost:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin123"}'
Evaluation
Automated Metrics
The evaluation endpoint computes:
- Answer Relevancy β Does the answer address the question?
- Faithfulness β Is the answer grounded in the retrieved context?
- Context Precision β How much of the context is relevant?
- Context Recall β Did we retrieve all necessary context?
Manual Evaluation
Upload question-answer pairs via the Evaluation dashboard or directly through the API:
curl -X POST http://localhost:8000/api/evaluation/ \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"question": "Who manages the team working on Project X?", "expected_answer": "..."}'
Evaluation Results (Sample)
| Question | Graph RAG | Vector RAG | Hybrid | Winner |
|---|---|---|---|---|
| Who manages the team working on Project X? | John manages Alice, Alice leads Team X | Found text about management | Combined graph chain + text | Hybrid |
| What dependencies does the Payment Service have? | PaymentβAuthβUserDB chain | Found tech docs mentioning deps | Full dependency graph | Graph |
| Give an overview of the organizational structure | Entity traversal of org chart | Found relevant paragraphs | Org chart + context text | Hybrid |
| What companies are competitors of Google? | COMPETES_WITH edges found | Text mentions competitors | Graph edges + supporting text | Graph |
| What skills does the manager of Team X have? | 3-hop: TeamβAliceβJohnβSkills | Partial text match | Full reasoning chain | Hybrid |
Key Finding: Hybrid retrieval consistently outperforms single-mode retrieval on multi-hop and relationship queries. Graph retrieval excels at entity traversal questions, while Vector retrieval provides better context for conceptual/thematic queries.
Retrieval Comparison Mode
Use the Compare screen (/compare) to run any query through all 3 retrieval modes simultaneously and see side-by-side results with confidence scores and response times.
Troubleshooting
Neo4j won't start
# Check if port 7687 is in use
lsof -i :7687
# Kill existing process or change port in docker-compose.yml
Backend can't connect to Neo4j
# Verify Neo4j is healthy
docker compose ps neo4j
# Check Neo4j logs
docker compose logs neo4j
LLM API key errors
# Verify API key is set
echo $GROQ_API_KEY
# Test the key manually
curl https://api.groq.com/openai/v1/models \
-H "Authorization: Bearer $GROQ_API_KEY"
Graph visualization is empty
- Ensure documents have been uploaded and processed
- Check ingestion status:
GET /api/documents/ - Verify Neo4j has data: open
http://localhost:7474and runMATCH (n) RETURN count(n)
Frontend build fails
cd frontend
rm -rf node_modules .next
npm install
npm run build
Project Structure
07.graphrag-knowledge-ai/
βββ docker-compose.yml # Neo4j + Backend + Frontend
βββ .env.example # Environment variable template
βββ Assignment_10_GraphRAG_Knowledge_Graph_AI.md
β
βββ backend/
β βββ manage.py
β βββ requirements.txt
β βββ Dockerfile
β βββ .dockerignore
β βββ graphrag_project/
β β βββ settings.py
β β βββ urls.py
β β βββ wsgi.py
β βββ graphrag/
β β βββ models.py # User, Document, QueryLog, EvaluationPair
β β βββ views.py # 21 API endpoints
β β βββ urls.py # URL routing
β β βββ serializers.py # DRF serializers
β β βββ tests_comprehensive.py # 112 unit tests
β β βββ admin.py
β β βββ services/
β β βββ llm_client.py # Groq/Gemini/NVIDIA provider
β β βββ entity_extractor.py # 9 entity types
β β βββ relationship_extractor.py # 10 relationship types
β β βββ entity_resolver.py # RapidFuzz + LLM disambiguation
β β βββ graph_builder.py # Neo4j graph construction
β β βββ neo4j_client.py # Neo4j driver wrapper
β β βββ graph_retriever.py # Graph-based retrieval
β β βββ vector_retriever.py # ChromaDB vector retrieval
β β βββ hybrid_retriever.py # Merged graph + vector
β β βββ nl_to_cypher.py # Schema-aware NL β Cypher
β β βββ multihop_reasoner.py # Up to 4-hop chains
β β βββ community_detector.py # Louvain algorithm
β β βββ rag_chain.py # Answer generation
β
βββ frontend/
β βββ package.json
β βββ next.config.js
β βββ tsconfig.json
β βββ tailwind.config.ts
β βββ postcss.config.js
β βββ Dockerfile
β βββ .dockerignore
β βββ src/
β β βββ app/
β β β βββ page.tsx # Root (landing/dashboard)
β β β βββ layout.tsx
β β β βββ globals.css
β β βββ components/
β β β βββ layout/Sidebar.tsx
β β β βββ dashboard/MainQueryView.tsx
β β β βββ graph/GraphVisualization.tsx # react-force-graph-2d
β β β βββ graph/EntityPanel.tsx
β β β βββ query/AnswerCard.tsx
β β β βββ query/PathView.tsx
β β β βββ query/SourceToggle.tsx
β β β βββ compare/ComparisonView.tsx
β β β βββ communities/CommunityView.tsx
β β β βββ documents/DocumentUpload.tsx
β β β βββ debug/ProcessingSteps.tsx
β β β βββ eval/EvaluationDashboard.tsx
β β βββ lib/
β β β βββ api.ts # Axios API client
β β β βββ mockData.ts # Mock data for development
β β β βββ stores.ts # Zustand stores
β β βββ types/
β β βββ index.ts # TypeScript interfaces
β
βββ eval_dataset/ # Evaluation question-answer pairs
βββ sample_documents/ # Sample documents for testing
License
This project is built as Assignment #10 for Excellence Technologies Phase 2 training.