Add your description here
Project description
๐ง RAG Backend API
A production-ready Retrieval-Augmented Generation (RAG) system built with FastAPI, featuring document processing, vector search, and conversational AI capabilities.
๐ Table of Contents
- Features
- Tech Stack
- Prerequisites
- Installation
- Configuration
- Running the Application
- Testing
- Development Workflow
- Project Structure
- API Documentation
- ContrXuting
โจ Features
- ๐ JWT-based authentication with refresh tokens
- ๐ PDF document processing and vectorization
- ๐๏ธ Vector similarity search using LanceDB
- ๐ฌ Conversational AI with context retrieval
- ๐ Dataset management and metadata tracking
- โ๏ธ S3-compatXle storage integration
- ๐ณ Full Docker support with health checks
- ๐งช Comprehensive test suite
๐ ๏ธ Tech Stack
- Language: Python 3.12+
- Framework: FastAPI
- Package Manager: UV (modern Python package manager)
- ORM: SQLAlchemy 2.0
- Database: PostgreSQL
- Vector Store: LanceDB
- Embeddings: Sentence Transformers (gtr-t5-large)
- LLM: Mistral AI
- Document Processing: Docling
- Storage: S3-compatXle (Scaleway, AWS, etc.)
- Containerization: Docker + Docker Compose
๐ฆ Prerequisites
System Requirements
Windows Users ๐ช
# 1. Install Chocolatey (Package Manager) - Run as Administrator
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
# 2. Install Python 3.12
choco install python312 -y
# 3. Install PostgreSQL (for local development)
choco install postgresql15 -y
# 4. Install Visual C++ Build Tools (required for some Python packages)
choco install visualstudio2022buildtools -y
# 5. Restart your terminal
macOS Users ๐
# 1. Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 2. Install Python 3.12
brew install python@3.12
# 3. Install PostgreSQL (for local development)
brew install postgresql@15
# 4. Install OpenCV (required for document processing)
brew install opencv
# 5. Restart your terminal
Install UV Package Manager
Windows ๐ช
# Install UV using PowerShell (Run as Administrator)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# Close and reopen your terminal, then verify
uv --version
macOS/Linux ๐๐ง
# Install UV
curl -LsSf https://astral.sh/uv/install.sh | sh
# Reload shell configuration
source ~/.zshrc # or ~/.bashrc for bash users
# Verify installation
uv --version
Install Git (If Not Already Installed)
Windows ๐ช
# Install Git
choco install git -y
# Configure Git (replace with your info)
git config --global user.name "Your Name"
git config --global user.email "your.email@company.com"
macOS ๐
# Install Git
brew install git
# Configure Git (replace with your info)
git config --global user.name "Your Name"
git config --global user.email "your.email@company.com"
Install Docker (Optional but Recommended)
- Windows: Download Docker Desktop for Windows
- macOS: Download Docker Desktop for Mac
๐ Installation
1. Clone the Repository
# Clone the repository
git clone <repository-url>
cd rag-backend-api
# Switch to development branch (if applicable)
git checkout develop
2. Create Virtual Environment
Windows ๐ช
# Create UV virtual environment with Python 3.12
uv venv --python 3.12
# Activate virtual environment
.venv\Scripts\activate
# Verify Python version
python --version # Should show Python 3.12.x
macOS/Linux ๐๐ง
# Create UV virtual environment with Python 3.12
uv venv --python 3.12
# Activate virtual environment
source .venv/bin/activate
# Verify Python version
python --version # Should show Python 3.12.x
3. Install Dependencies
# Install all dependencies (including dev dependencies)
uv sync
# For production only (without dev dependencies)
uv sync --no-dev
Platform-Specific Troubleshooting
Windows ๐ช
# If psycopg2-binary fails
# Make sure PostgreSQL is installed, then:
$env:PATH += ";C:\Program Files\PostgreSQL\15\bin"
uv pip install psycopg2-binary
# If Visual C++ errors occur
# Install Visual Studio Build Tools from:
# https://visualstudio.microsoft.com/visual-cpp-build-tools/
macOS ARM (M1/M2/M3) ๐
# If PyTorch installation fails
uv pip install torch==2.6.0 torchvision==0.21.0
# If psycopg2 fails
brew install postgresql@15
export PATH="/opt/homebrew/opt/postgresql@15/bin:$PATH"
uv pip install psycopg2-binary
โ๏ธ Configuration
1. Create Environment File
Windows ๐ช
# Copy example configuration
Copy-Item .env.example .env
# Edit with notepad
notepad .env
macOS/Linux ๐๐ง
# Copy example configuration
cp .env.example .env
# Edit with your preferred editor
nano .env # or vim, code, etc.
2. Configure Environment Variables
Update the .env file with your actual values:
# Application Mode
WORKING_MODE=development
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=rag_db
DB_USER=your_db_user
DB_PASSWORD=your_secure_password
DB_SCHEMA=public
# S3 Storage Configuration
S3_REGION=eu-west-3
S3_ACCESS_KEY=your_access_key
S3_ACCESS_KEY_SECRET=your_secret_key
S3_ENDPOINT=https://s3.eu-west-3.amazonaws.com
S3_BUCKET_NAME=your_bucket_name
# Mistral AI API
MISTRAL_API_KEY=your_mistral_api_key
MISTRAL_API_URL=https://api.mistral.ai/v1
# JWT Authentication
SECRET_KEY=your-super-secret-key-minimum-32-characters
ACCESS_TOKEN_EXPIRE_MINUTES=60
ALGORITHM=HS256
# Password Encryption
ENCRYPT_KEY=your-encryption-key
# Development Settings (optional)
ECHO_SQL=false
โ ๏ธ Security Warning: Never commit
.envfiles to version control!
3. Initialize Database
# Run database migrations
alembic upgrade head
๐ Database Access (Important)
The PostgreSQL database is IP-whitelisted for security reasons.
โก๏ธ Before running the application, you must ask the project owner/admin to add your public IP address to the database whitelist.
โ ๏ธ If your IP is not whitelisted, the database connection will fail.
๐ก How to Get Your Public IP Address
macOS / Linux ๐๐ง
curl ifconfig.me
or
curl https://api.ipify.org
Windows ๐ช (PowerShell)
curl ifconfig.me
or
(Invoke-WebRequest -uri "https://api.ipify.org").Content
๐ Next Steps
Send the resulting IP address to the administrator so it can be approved and added to the whitelist.
โ ๏ธ Note: If you are on a dynamic network (VPN, mobile hotspot, etc.), your IP may change and need to be re-approved.
๐ฏ Running the Application
Option 1: Local Development (Recommended) โก
Windows ๐ช
# Activate virtual environment
.venv\Scripts\activate
# Start the API server with auto-reload
uv run uvicorn th2rag.main:app --reload --host 0.0.0.0 --port 8000
macOS/Linux ๐๐ง
# Activate virtual environment
source .venv/bin/activate
# Start the API server with auto-reload
uv run uvicorn th2rag.main:app --reload --host 0.0.0.0 --port 8000
Access Points:
- ๐ Swagger UI: http://localhost:8000/docs
- ๐ ReDoc: http://localhost:8000/redoc
- โค๏ธ Health Check: http://localhost:8000/health
Option 2: Docker (Production-like) ๐ณ
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f api
# Stop services
docker-compose down
Updating Environment Variables in Docker
# Important: Restart does NOT reload .env!
# You must stop and recreate containers:
docker-compose down
docker-compose up -d
docker-compose logs -f api
๐งช Testing
Run Tests Locally
Windows ๐ช
# Activate virtual environment
.venv\Scripts\activate
# Run all tests
uv run pytest
# Run with verbose output
uv run pytest -v
# Run specific test file
uv run pytest test\test_auth.py
# Run with coverage
uv run pytest --cov=src --cov-report=html
uv run pytest --cov=src --cov-report=term-missing
# Open coverage report
start htmlcov\index.html
macOS/Linux ๐๐ง
# Activate virtual environment
source .venv/bin/activate
# Run all tests
uv run pytest
# Run with verbose output
uv run pytest -v
# Run specific test file
uv run pytest test/test_auth.py
# Run with coverage
uv run pytest --cov=src --cov-report=html
uv run pytest --cov=src --cov-report=term-missing
# Open coverage report
open htmlcov/index.html
Run Tests in Docker
# Ensure containers are running
docker-compose up -d
# Run tests inside container
docker-compose exec api pytest -v
๐ Development Workflow
Branch Strategy
This project follows a Git workflow with feature branches:
# 1. Create a new feature branch from main/develop
git checkout -b feature/your-feature-name
# 2. Make your changes and commit regularly
git add .
git commit -m "feat: description of your changes"
# 3. Push to remote
git push origin feature/your-feature-name
# 4. Create a Pull Request on GitHub
Pre-commit Setup (Code Quality Checks)
Pre-commit hooks automatically check your code before each commit.
1. Install Pre-commit
Windows ๐ช
uv pip install pre-commit
macOS/Linux ๐๐ง
uv pip install pre-commit
2. Install Git Hooks
# Install the pre-commit hooks
pre-commit install
# (Optional) Run against all files to test
pre-commit run --all-files
3. Create Pre-commit Configuration
Create .pre-commit-config.yaml in your project root:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
args: ['--maxkb=1000']
- id: check-json
- id: check-merge-conflict
- id: detect-private-key
- repo: https://github.com/psf/black
rev: 23.12.1
hooks:
- id: black
language_version: python3.12
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.9
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
hooks:
- id: mypy
additional_dependencies: [types-all]
args: [--ignore-missing-imports]
Commit Message Convention
Follow conventional commits for clear history:
# Format: <type>(<scope>): <subject>
git commit -m "feat(auth): add refresh token endpoint"
git commit -m "fix(database): resolve connection pool issue"
git commit -m "docs(readme): update installation instructions"
git commit -m "test(auth): add JWT validation tests"
git commit -m "chore(deps): update dependencies"
Commit Types:
feat: New featurefix: Bug fixdocs: Documentation changesstyle: Code style changes (formatting)refactor: Code refactoringtest: Adding or updating testschore: Maintenance tasks
Pushing Your X Branch
Step-by-Step Guide
1. Check your current status
# See what files have changed
git status
# See the actual changes
git diff
2. Stage your changes
# Stage specific files
git add pyproject.toml
git add .pre-commit-config.yaml
git add docker-compose.yml
git add README.md
git add .env.example
# OR stage all changes
git add .
3. Commit your changes
# Commit with a descriptive message
git commit -m "feat(migration): migrate to UV package manager and update documentation"
4. Create and push your branch
Windows ๐ช
# Create and switch to X branch
git checkout -b X
# Push to remote repository
git push -u origin X
macOS/Linux ๐๐ง
# Create and switch to X branch
git checkout -b X
# Push to remote repository
git push -u origin X
5. Create a Pull Request
- Go to your GitHub repository
- Click "Compare & pull request" button
- Select base branch (usually
mainordevelop) - Add description of your changes
- Assign reviewers from your team
- Submit the pull request
Daily Workflow Example
# 1. Start of day - update your branch
git checkout X
git pull origin X
# 2. Make changes to files
# ... edit code ...
# 3. Check what changed
git status
git diff
# 4. Run tests before committing
uv run pytest
# 5. Pre-commit will automatically run when you commit
git add .
git commit -m "feat(rag): improve document chunking algorithm"
# 6. Push changes
git push origin X
# 7. If you need to sync with main branch
git checkout main
git pull origin main
git checkout X
git merge main
# Resolve any conflicts if they occur
git push origin X
Handling Pre-commit Failures
If pre-commit hooks fail:
# Pre-commit will show what failed
# Fix the issues, then:
git add .
git commit -m "your message"
# If automatic fixes were applied, stage them:
git add .
git commit --amend --no-edit
๐ Project Structure
.
โโโ .github/ # GitHub workflows and templates
โโโ alembic/ # Database migrations
โ โโโ versions/ # Migration scripts
โ โโโ env.py # Alembic environment
โโโ data/ # LanceDB vector storage
โโโ src/ # Main application source
โ โโโ auth/ # JWT authentication
โ โโโ clients/ # S3 client integration
โ โโโ conversations/ # Conversation management
โ โโโ dataset/ # Dataset handling
โ โโโ knowledge/ # Document management
โ โโโ messages/ # Message operations
โ โโโ rag/ # RAG pipeline
โ โ โโโ chunkers/ # Document chunking
โ โ โโโ converters/ # Format conversion
โ โ โโโ embeddings/ # Vector embeddings
โ โ โโโ generation/ # LLM generation
โ โ โโโ retrieval/ # Vector search
โ โ โโโ services/ # RAG orchestration
โ โ โโโ tasks/ # Background jobs
โ โโโ users/ # User management
โ โโโ utils/ # Utilities
โ โโโ main.py # Application entry
โโโ test/ # Test suite
โโโ .env.example # Environment template
โโโ .gitignore # Git ignore rules
โโโ .pre-commit-config.yaml # Pre-commit hooks
โโโ alembic.ini # Alembic config
โโโ docker-compose.yml # Docker services
โโโ Dockerfile # Container definition
โโโ pyproject.toml # Project dependencies
โโโ README.md # This file
๐ API Documentation
Authentication
POST /auth/login- Login and get tokensPOST /auth/refresh-token- Refresh access token
Users
GET /users- List users (admin)POST /users- Create userGET /users/me- Get current userGET /users/{id}- Get user by IDDELETE /users/{id}- Delete user
Conversations
GET /conversations- List conversationsPOST /conversations- Create conversationGET /conversations/{id}- Get conversation detailsDELETE /conversations/{id}- Delete conversation
Messages
GET /conversations/{id}/messages- List messagesPOST /conversations/{id}/messages- Send message and get AI responsePOST /conversations/{id}/messages/{message_id}/feedback- Add feedback
Knowledge Documents
GET /knowledge- List documentsPOST /knowledge- Upload PDF documentGET /knowledge/{id}- Get document detailsDELETE /knowledge/{id}- Delete document and vectors
Datasets
GET /datasets- List datasetsPOST /datasets- Create datasetPUT /datasets/{id}- Update datasetDELETE /datasets/{id}- Delete dataset
For detailed API schemas, visit: http://localhost:8000/docs
๐ง RAG Engine
The rag/ module is responsible for the core Retrieval-Augmented Generation (RAG) pipeline. It orchestrates document conversion, chunking, embedding, retrieval, and final answer generation.
๐ 1. Document Conversion
converters/pdf_converter.py: Converts PDF files (local or S3) to an internalDocumentformat usingdocling.
convert_pdf(source: str) -> dict
๐ซ 2. Chunking
chunkers/hybrid_chunker.py: Wrapsdocling'sHybridChunkerto split documents into semantic chunks.
HybridTextChunker.chunk_document(dl_doc) -> list
๐๏ธ 3. Embeddings
embeddings/sentence_transformer.py: Usessentence-transformers/gtr-t5-largeto convert text chunks into dense vectors.
SentenceTransformerEmbedding.encode(text: str) -> List[float]
๐๏ธ 4. Vector Store (LanceDB)
retrieval/lancedb/lancedb_storage.py: Manages chunk storage/retrieval in LanceDB.retrieval/lancedb/schemas.py: Pydantic schema definitions for LanceDB.
LanceDBStorage.add_chunks(chunks)
LanceDBStorage.query(query_vector, doc_id, limit)
๐ 5. Retrieval
retrieval/lancedb/lancedb_retriever.py: Retrieves similar document chunks using LanceDB + embeddings.
LanceDBRetriever.retrieve(query: str, doc_id: int, limit: int) -> List[Dict]
๐ 6. Generation
generation/mistral_generator.py: Calls Mistral API to generate responses using retrieved context.
MistralGenerator.generate(question, retrieved_context, prompt, history) -> str
โ๏ธ 7. RAG Service
services/rag_service.py: Orchestrates the full RAG pipeline.services/rag_service_builder.py: Builds the RAG service with configurable components.
RAGService.answer_question(question, doc_id, limit, prompt, history)
โ๏ธ 8. Background Processing
tasks/process_pdf.py: Asynchronously handles PDF-to-vector pipeline including download, convert, chunk, embed, and store.
process_pdf_background(doc_id, source)
๐ค ContrXuting
Code Review Checklist
Before submitting a PR, ensure:
- โ
All tests pass (
uv run pytest) - โ Pre-commit hooks pass
- โ Code is documented with docstrings
- โ New features have tests
- โ README updated if needed
- โ Commit messages follow convention
- โ No sensitive data in commits
Adding New Features
1. Database Changes
# Edit src/models.py
# Generate migration
alembic revision --autogenerate -m "add new feature"
# Review and apply
alembic upgrade head
2. New Embedding Model
# src/rag/embeddings/custom_embedding.py
from th2rag.rag.embeddings.base import BaseEmbedding
class CustomEmbedding(BaseEmbedding):
def encode(self, text: str) -> List[float]:
# Implementation
pass
3. New LLM Generator
# src/rag/generation/custom_generator.py
from th2rag.rag.generation.base import BaseGenerator
class CustomGenerator(BaseGenerator):
def generate(self, question: str, context: str) -> str:
# Implementation
pass
๐ Troubleshooting
Windows-Specific Issues ๐ช
Port already in use:
# Find process
netstat -ano | findstr :8000
# Kill process (replace PID)
taskkill /PID <PID> /F
Python not found:
# Add Python to PATH
$env:Path += ";C:\Python312;C:\Python312\Scripts"
Permission errors:
# Run PowerShell as Administrator
# Or adjust execution policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
macOS-Specific Issues ๐
Port already in use:
# Find and kill process
lsof -ti:8000 | xargs kill -9
SSL certificate errors:
# Update certificates
pip install --upgrade certifi
Common Issues (All Platforms)
Database connection failed:
- Verify PostgreSQL is running
- Check credentials in
.env - Ensure database exists
Docker container won't start:
docker-compose logs api
docker-compose down -v
docker-compose up -d --build
Pre-commit hooks fail:
# Update hooks
pre-commit autoupdate
pre-commit run --all-files
๐ Support
- ๐ง Email: your-team@company.com
- ๐ฌ Slack: #rag-backend-support
- ๐ Issues: GitHub Issues
- ๐ Wiki: Project Wiki
๐ License
[Specify your license here]
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file th2rag-0.0.2.tar.gz.
File metadata
- Download URL: th2rag-0.0.2.tar.gz
- Upload date:
- Size: 77.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
806de84c40d360aacd5b47cd680101312c883780b737b5cba09dd7751b633e80
|
|
| MD5 |
2246daf10bc5942eaca879fb066bc776
|
|
| BLAKE2b-256 |
1c3e713d74a97ef085f9b6deb302e23b39b26886aba2cda5b2e075b200adfac6
|
Provenance
The following attestation bundles were made for th2rag-0.0.2.tar.gz:
Publisher:
pypi-publish.yml on apowerb/th2rag
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
th2rag-0.0.2.tar.gz -
Subject digest:
806de84c40d360aacd5b47cd680101312c883780b737b5cba09dd7751b633e80 - Sigstore transparency entry: 2289688998
- Sigstore integration time:
-
Permalink:
apowerb/th2rag@0d6cc80e1c9fb3010f83d5ebcbcb3d2e49d470f0 -
Branch / Tag:
refs/tags/v0.0.2 - Owner: https://github.com/apowerb
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pypi-publish.yml@0d6cc80e1c9fb3010f83d5ebcbcb3d2e49d470f0 -
Trigger Event:
release
-
Statement type:
File details
Details for the file th2rag-0.0.2-py3-none-any.whl.
File metadata
- Download URL: th2rag-0.0.2-py3-none-any.whl
- Upload date:
- Size: 98.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4b8249d4d94e9c277a8be9f0d29f8bf09b5625f94349b14a57cdd28b4bcb7139
|
|
| MD5 |
e1eccb4df35b1d2b398c6cf7cca58cc2
|
|
| BLAKE2b-256 |
53ea8fa947c1d1207c1354daea168481ddce1e8c9f63b692a3da8066298444ee
|
Provenance
The following attestation bundles were made for th2rag-0.0.2-py3-none-any.whl:
Publisher:
pypi-publish.yml on apowerb/th2rag
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
th2rag-0.0.2-py3-none-any.whl -
Subject digest:
4b8249d4d94e9c277a8be9f0d29f8bf09b5625f94349b14a57cdd28b4bcb7139 - Sigstore transparency entry: 2289689082
- Sigstore integration time:
-
Permalink:
apowerb/th2rag@0d6cc80e1c9fb3010f83d5ebcbcb3d2e49d470f0 -
Branch / Tag:
refs/tags/v0.0.2 - Owner: https://github.com/apowerb
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pypi-publish.yml@0d6cc80e1c9fb3010f83d5ebcbcb3d2e49d470f0 -
Trigger Event:
release
-
Statement type: