This PathRAG Demo App is a comprehensive knowledge graph-based Retrieval-Augmented Generation (RAG) system that combines document processing, chat functionality, and knowledge graph visualization in a single application.
PathRAG (Path-based Retrieval Augmented Generation) is an advanced approach to knowledge retrieval and generation that combines the power of knowledge graphs with large language models (LLMs).
PathRAG builds and maintains a knowledge graph from your documents, where:
Unlike traditional RAG systems that rely solely on vector similarity:
PathRAG combines multiple search strategies:
Document Processing:
Query Processing:
Response Generation:
/api
/auth - Authentication module
- jwt_handler.py - JWT token handling
- routes.py - Authentication endpoints
- schemas.py - Authentication data models
/features - Feature modules
/users - User management
/chats - Chat functionality
/documents - Document management
/knowledge_graph - Knowledge graph functionality
/models - Database models
- database.py - SQLite database setup and models
main.py - Main application entry point
/pathrag-ui
/public - Static files
/src
/components - Reusable components
/auth - Authentication components
/chat - Chat components
/documents - Document components
/knowledge-graph - Knowledge graph components
/context - React context providers
/pages - Application pages
/services - API services
/utils - Utility functions
App.js - Main application component
index.js - Application entry point
Python Version: Python 3.10.18
cd PathRAG
pip install -e .
v1_test.py file.api_key="sk-...". in the v1_test.py and llm.py file.v1_test.py file to initialize PathRAG and perform queries.import os
from PathRAG import PathRAG, QueryParam
from PathRAG.llm import gpt_4o_mini_complete
WORKING_DIR = "./your_working_dir"
api_key="your_api_key"
os.environ["OPENAI_API_KEY"] = api_key
base_url="https://api.openai.com/v1"
os.environ["OPENAI_API_BASE"]=base_url
if not os.path.exists(WORKING_DIR):
os.mkdir(WORKING_DIR)
rag = PathRAG(
working_dir=WORKING_DIR,
llm_model_func=gpt_4o_mini_complete,
)
data_file="./text.txt"
question="your_question"
with open(data_file) as f:
rag.insert(f.read())
print(rag.query(question, param=QueryParam(mode="hybrid")))
rag_test.py file.rag_test.py file to use models from different sources.examples.txt.import os
import asyncio
import torch
from PathRAG.RAGRunner import RAGRunner
if __name__ == "__main__":
backend = "your_model_source" # hf / vllm / ollama / ms / local
working_dir = f"your_working_dir"
llm_model_name = "Qwen/Qwen3-0.6B" # model name or path of model
embedding_model_name = "iic/nlp_corom_sentence-embedding_english-base" # embedding model name or path ofembedding model
# ollama additional parameters
llm_model_kwargs = {
"host": "http://localhost:11434",
"options": {"num_ctx": 8192},
"timeout": 300,
} if backend == "ollama" else {}
runner = RAGRunner(
backend=backend,
working_dir=working_dir,
llm_model_name=llm_model_name,
embedding_model_name=embedding_model_name,
llm_model_max_token_size=8192,
llm_model_kwargs=llm_model_kwargs,
embedding_dim=768,
embedding_max_token_size=5000,
)
data_file = "your_data_file"
question = "your_question"
with open(data_file, "r", encoding="utf-8") as f:
runner.insert_text(f.read())
answer = runner.query(question, mode="hybrid")
print("question:", question)
print("answer:", answer)
You can adjust the relevant parameters in the base.py and operate.py files.
top_k in base.py, where top_k represents the number of nodes retrievedalpha and threshold in operate.py, where alpha represents the decay rate of information propagation along the edges, and threshold is the pruning threshold.import os
folder_path = "your_folder_path"
txt_files = [f for f in os.listdir(folder_path) if f.endswith(".txt")]
for file_name in txt_files:
file_path = os.path.join(folder_path, file_name)
with open(file_path, "r", encoding="utf-8") as file:
rag.insert(file.read())
The dataset used in PathRAG can be downloaded from TommyChien/UltraDomain.
You will evaluate two answers to the same question based on five criteria: **Comprehensiveness**, **Diversity**, **logicality**, **Coherence**, **Relevance**.
- **Comprehensiveness**: How much detail does the answer provide to cover all aspects and details of the question?
- **Diversity**: How varied and rich is the answer in providing different perspectives and insights on the question?
- **logicality**: How logically does the answer respond to all parts of the question?
- **Coherence**: How well does the answer maintain internal logical connections between its parts, ensuring a smooth and consistent structure?
- **Relevance**: How relevant is the answer to the question, staying focused and addressing the intended topic or issue?
For each criterion, choose the better answer (either Answer 1 or Answer 2) and explain why.
Here is the question:
{query}
Here are the two answers:
**Answer 1:**
{answer1}
**Answer 2:**
{answer2}
Evaluate both answers using the five criteria listed above and provide detailed explanations for each criterion.
Output your evaluation in the following JSON format:
{{
"Comprehensiveness": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"Diversity": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"logicality": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"Coherence": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"Relevance": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}}
}}
Use our start script to set up and run the API:
For Unix/Linux/macOS:
# Make the script executable (first time only)
chmod +x start-api.sh
# Run the API
./start-api.sh
For Windows:
# Run the API
start-api.bat
These scripts will:
.venv if it doesn't existThe API will be available at:
Navigate to the UI directory and start the React application:
# Navigate to the UI directory
cd ui
# Install dependencies (first time only)
npm install
# Start the UI
npm start
The UI will be available at:
If you prefer to set up and run the components separately, follow these instructions:
Create and activate a virtual environment:
# Create virtual environment
python -m venv .venv
# Activate on Windows
.venv\Scripts\activate
# Activate on macOS/Linux
source .venv/bin/activate
Install Python dependencies:
pip install -r requirements.txt
Configure environment variables: Copy the sample environment file and modify it with your settings:
cp sample.env .env
# Edit .env with your preferred text editor
Key environment variables include:
# JWT Authentication
SECRET_KEY=your_secret_key_here # Generate with: openssl rand -hex 32
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Application Directories
WORKING_DIR=./data
UPLOAD_DIR=./uploads
# Database Configuration
DATABASE_URL=sqlite:///./pathrag.db
# Server Configuration
HOST=0.0.0.0
PORT=8000
DEBUG=False
LOG_LEVEL=info
CORS_ORIGINS=http://localhost:3000
# AI Model Settings (choose one option)
# Option 1: Azure OpenAI
AZURE_OPENAI_API_KEY=your_azure_key
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_DEPLOYMENT=gpt-4o
AZURE_OPENAI_API_VERSION=2023-05-15
AZURE_EMBEDDING_DEPLOYMENT=text-embedding-3-large
# Option 2: OpenAI direct
OPENAI_API_KEY=your_openai_key
OPENAI_API_BASE=https://api.openai.com/v1
# PathRAG Configuration
CHUNK_SIZE=1200
CHUNK_OVERLAP=100
MAX_TOKENS=32768
TEMPERATURE=0.7
TOP_K=40
See INSTALLATION.md for detailed environment variable configuration and sample.env for a complete example.
Start the backend server:
python main.py
The API will be available at http://localhost:8000
For more advanced options, see INSTALLATION.md.
API Documentation:
Navigate to the frontend directory:
cd ui
Install dependencies:
npm install
Start the development server:
npm start
The application will be available at http://localhost:3000
id: Integer (Primary Key)username: String (Unique)email: String (Unique)hashed_password: Stringcreated_at: DateTimetheme: String (Default: "blue")id: Integer (Primary Key)uuid: String (Unique)user_id: Integer (Foreign Key to User)title: Stringcreated_at: DateTimeupdated_at: DateTimeis_deleted: Boolean (Default: False)id: Integer (Primary Key)user_id: Integer (Foreign Key to User)thread_id: Integer (Foreign Key to Thread)role: String ('user' or 'system')message: Textcreated_at: DateTimeid: Integer (Primary Key)user_id: Integer (Foreign Key to User)filename: Stringcontent_type: Stringfile_path: Stringfile_size: Integeruploaded_at: DateTimestatus: Stringprocessed_at: DateTime (Nullable)error_message: Text (Nullable)POST /token: Login and get access tokenPOST /register: Register a new userGET /users/me: Get current user informationGET /users/: Get all usersPOST /users/theme: Update user themeGET /chats/threads: Get all chat threadsPOST /chats/threads: Create a new chat threadGET /chats/threads/{thread_uuid}: Get a specific thread with all its chatsPUT /chats/threads/{thread_uuid}: Update a thread's titleDELETE /chats/threads/{thread_uuid}: Mark a thread as deletedGET /chats/: Get all chatsGET /chats/recent: Get the 5 most recent chat threadsPOST /chats/chat/{thread_uuid}: Create a new chat message in a threadGET /documents/: Get all documentsPOST /documents/upload: Upload a documentGET /documents/{document_id}: Get a specific documentGET /documents/{document_id}/status: Get document processing statusPOST /documents/reload: Reload the PathRAG instance to recognize new documentsGET /knowledge-graph/: Get the knowledge graphPOST /knowledge-graph/query: Query the knowledge graphNote: These storage options are suitable for demonstration and development purposes only. They are not recommended for production use with large datasets or high traffic.
For production environments, consider using these alternatives:
This project is licensed under the MIT License - see the LICENSE file for details.
PathRAG is particularly effective for:
Boyu Chen¹, Zirui Guo², Zidan Yang¹, Yuluo Chen¹, Junze Chen¹, Zhenghao Liu³, Chuan Shi¹, Cheng Yang¹
Contact: [email protected], [email protected]
132 followers · starred Feb 2025
5 followers · starred Oct 2025
88 followers · starred Dec 2025
60 followers · starred Feb 2025
This PathRAG Demo App is a comprehensive knowledge graph-based Retrieval-Augmented Generation (RAG) system that combines document processing, chat functionality, and knowledge graph visualization in a single application.
PathRAG (Path-based Retrieval Augmented Generation) is an advanced approach to knowledge retrieval and generation that combines the power of knowledge graphs with large language models (LLMs).
PathRAG builds and maintains a knowledge graph from your documents, where:
Unlike traditional RAG systems that rely solely on vector similarity:
PathRAG combines multiple search strategies:
Document Processing:
Query Processing:
Response Generation:
/api
/auth - Authentication module
- jwt_handler.py - JWT token handling
- routes.py - Authentication endpoints
- schemas.py - Authentication data models
/features - Feature modules
/users - User management
/chats - Chat functionality
/documents - Document management
/knowledge_graph - Knowledge graph functionality
/models - Database models
- database.py - SQLite database setup and models
main.py - Main application entry point
/pathrag-ui
/public - Static files
/src
/components - Reusable components
/auth - Authentication components
/chat - Chat components
/documents - Document components
/knowledge-graph - Knowledge graph components
/context - React context providers
/pages - Application pages
/services - API services
/utils - Utility functions
App.js - Main application component
index.js - Application entry point
Python Version: Python 3.10.18
cd PathRAG
pip install -e .
v1_test.py file.api_key="sk-...". in the v1_test.py and llm.py file.v1_test.py file to initialize PathRAG and perform queries.import os
from PathRAG import PathRAG, QueryParam
from PathRAG.llm import gpt_4o_mini_complete
WORKING_DIR = "./your_working_dir"
api_key="your_api_key"
os.environ["OPENAI_API_KEY"] = api_key
base_url="https://api.openai.com/v1"
os.environ["OPENAI_API_BASE"]=base_url
if not os.path.exists(WORKING_DIR):
os.mkdir(WORKING_DIR)
rag = PathRAG(
working_dir=WORKING_DIR,
llm_model_func=gpt_4o_mini_complete,
)
data_file="./text.txt"
question="your_question"
with open(data_file) as f:
rag.insert(f.read())
print(rag.query(question, param=QueryParam(mode="hybrid")))
rag_test.py file.rag_test.py file to use models from different sources.examples.txt.import os
import asyncio
import torch
from PathRAG.RAGRunner import RAGRunner
if __name__ == "__main__":
backend = "your_model_source" # hf / vllm / ollama / ms / local
working_dir = f"your_working_dir"
llm_model_name = "Qwen/Qwen3-0.6B" # model name or path of model
embedding_model_name = "iic/nlp_corom_sentence-embedding_english-base" # embedding model name or path ofembedding model
# ollama additional parameters
llm_model_kwargs = {
"host": "http://localhost:11434",
"options": {"num_ctx": 8192},
"timeout": 300,
} if backend == "ollama" else {}
runner = RAGRunner(
backend=backend,
working_dir=working_dir,
llm_model_name=llm_model_name,
embedding_model_name=embedding_model_name,
llm_model_max_token_size=8192,
llm_model_kwargs=llm_model_kwargs,
embedding_dim=768,
embedding_max_token_size=5000,
)
data_file = "your_data_file"
question = "your_question"
with open(data_file, "r", encoding="utf-8") as f:
runner.insert_text(f.read())
answer = runner.query(question, mode="hybrid")
print("question:", question)
print("answer:", answer)
You can adjust the relevant parameters in the base.py and operate.py files.
top_k in base.py, where top_k represents the number of nodes retrievedalpha and threshold in operate.py, where alpha represents the decay rate of information propagation along the edges, and threshold is the pruning threshold.import os
folder_path = "your_folder_path"
txt_files = [f for f in os.listdir(folder_path) if f.endswith(".txt")]
for file_name in txt_files:
file_path = os.path.join(folder_path, file_name)
with open(file_path, "r", encoding="utf-8") as file:
rag.insert(file.read())
The dataset used in PathRAG can be downloaded from TommyChien/UltraDomain.
You will evaluate two answers to the same question based on five criteria: **Comprehensiveness**, **Diversity**, **logicality**, **Coherence**, **Relevance**.
- **Comprehensiveness**: How much detail does the answer provide to cover all aspects and details of the question?
- **Diversity**: How varied and rich is the answer in providing different perspectives and insights on the question?
- **logicality**: How logically does the answer respond to all parts of the question?
- **Coherence**: How well does the answer maintain internal logical connections between its parts, ensuring a smooth and consistent structure?
- **Relevance**: How relevant is the answer to the question, staying focused and addressing the intended topic or issue?
For each criterion, choose the better answer (either Answer 1 or Answer 2) and explain why.
Here is the question:
{query}
Here are the two answers:
**Answer 1:**
{answer1}
**Answer 2:**
{answer2}
Evaluate both answers using the five criteria listed above and provide detailed explanations for each criterion.
Output your evaluation in the following JSON format:
{{
"Comprehensiveness": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"Diversity": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"logicality": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"Coherence": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}},
"Relevance": {{
"Winner": "[Answer 1 or Answer 2]",
"Explanation": "[Provide explanation here]"
}}
}}
Use our start script to set up and run the API:
For Unix/Linux/macOS:
# Make the script executable (first time only)
chmod +x start-api.sh
# Run the API
./start-api.sh
For Windows:
# Run the API
start-api.bat
These scripts will:
.venv if it doesn't existThe API will be available at:
Navigate to the UI directory and start the React application:
# Navigate to the UI directory
cd ui
# Install dependencies (first time only)
npm install
# Start the UI
npm start
The UI will be available at:
If you prefer to set up and run the components separately, follow these instructions:
Create and activate a virtual environment:
# Create virtual environment
python -m venv .venv
# Activate on Windows
.venv\Scripts\activate
# Activate on macOS/Linux
source .venv/bin/activate
Install Python dependencies:
pip install -r requirements.txt
Configure environment variables: Copy the sample environment file and modify it with your settings:
cp sample.env .env
# Edit .env with your preferred text editor
Key environment variables include:
# JWT Authentication
SECRET_KEY=your_secret_key_here # Generate with: openssl rand -hex 32
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Application Directories
WORKING_DIR=./data
UPLOAD_DIR=./uploads
# Database Configuration
DATABASE_URL=sqlite:///./pathrag.db
# Server Configuration
HOST=0.0.0.0
PORT=8000
DEBUG=False
LOG_LEVEL=info
CORS_ORIGINS=http://localhost:3000
# AI Model Settings (choose one option)
# Option 1: Azure OpenAI
AZURE_OPENAI_API_KEY=your_azure_key
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_DEPLOYMENT=gpt-4o
AZURE_OPENAI_API_VERSION=2023-05-15
AZURE_EMBEDDING_DEPLOYMENT=text-embedding-3-large
# Option 2: OpenAI direct
OPENAI_API_KEY=your_openai_key
OPENAI_API_BASE=https://api.openai.com/v1
# PathRAG Configuration
CHUNK_SIZE=1200
CHUNK_OVERLAP=100
MAX_TOKENS=32768
TEMPERATURE=0.7
TOP_K=40
See INSTALLATION.md for detailed environment variable configuration and sample.env for a complete example.
Start the backend server:
python main.py
The API will be available at http://localhost:8000
For more advanced options, see INSTALLATION.md.
API Documentation:
Navigate to the frontend directory:
cd ui
Install dependencies:
npm install
Start the development server:
npm start
The application will be available at http://localhost:3000
id: Integer (Primary Key)username: String (Unique)email: String (Unique)hashed_password: Stringcreated_at: DateTimetheme: String (Default: "blue")id: Integer (Primary Key)uuid: String (Unique)user_id: Integer (Foreign Key to User)title: Stringcreated_at: DateTimeupdated_at: DateTimeis_deleted: Boolean (Default: False)id: Integer (Primary Key)user_id: Integer (Foreign Key to User)thread_id: Integer (Foreign Key to Thread)role: String ('user' or 'system')message: Textcreated_at: DateTimeid: Integer (Primary Key)user_id: Integer (Foreign Key to User)filename: Stringcontent_type: Stringfile_path: Stringfile_size: Integeruploaded_at: DateTimestatus: Stringprocessed_at: DateTime (Nullable)error_message: Text (Nullable)POST /token: Login and get access tokenPOST /register: Register a new userGET /users/me: Get current user informationGET /users/: Get all usersPOST /users/theme: Update user themeGET /chats/threads: Get all chat threadsPOST /chats/threads: Create a new chat threadGET /chats/threads/{thread_uuid}: Get a specific thread with all its chatsPUT /chats/threads/{thread_uuid}: Update a thread's titleDELETE /chats/threads/{thread_uuid}: Mark a thread as deletedGET /chats/: Get all chatsGET /chats/recent: Get the 5 most recent chat threadsPOST /chats/chat/{thread_uuid}: Create a new chat message in a threadGET /documents/: Get all documentsPOST /documents/upload: Upload a documentGET /documents/{document_id}: Get a specific documentGET /documents/{document_id}/status: Get document processing statusPOST /documents/reload: Reload the PathRAG instance to recognize new documentsGET /knowledge-graph/: Get the knowledge graphPOST /knowledge-graph/query: Query the knowledge graphNote: These storage options are suitable for demonstration and development purposes only. They are not recommended for production use with large datasets or high traffic.
For production environments, consider using these alternatives:
This project is licensed under the MIT License - see the LICENSE file for details.
PathRAG is particularly effective for:
Boyu Chen¹, Zirui Guo², Zidan Yang¹, Yuluo Chen¹, Junze Chen¹, Zhenghao Liu³, Chuan Shi¹, Cheng Yang¹
Contact: [email protected], [email protected]
132 followers · starred Feb 2025
5 followers · starred Oct 2025
88 followers · starred Dec 2025
60 followers · starred Feb 2025