A robust FastAPI-based backend service for the Buddhist AI Arena evaluation platform, providing authentication, challenge management, model evaluation, and real-time translation services.
- Framework: FastAPI 0.108.0
- Database: PostgreSQL with SQLAlchemy 2.0+ & SQLModel
- Authentication: Auth0 with JWT tokens
- Caching: Redis 5.0+
- Migrations: Alembic 1.12+
- File Storage: AWS S3 with aioboto3
- Background Tasks: Threading with queue-based workers
- AI Providers: OpenAI, Anthropic, Google Gemini, DeepSeek
- Evaluation: Hugging Face datasets & evaluate library
- Server: Uvicorn with auto-reload
- Python 3.9 or higher (3.10+ recommended)
- PostgreSQL 12 or higher
- Redis server (local or remote)
- AWS account with S3 bucket (for file storage)
- Auth0 account and application credentials
- API keys for AI providers (OpenAI, Anthropic, Google, DeepSeek)
git clone <repository-url>
cd arena/backendWindows:
python -m venv .venv
.venv\Scripts\activatemacOS/Linux:
python3 -m venv .venv
source .venv/bin/activatepip install -r requirements.txtCreate a new PostgreSQL database:
-- Connect to PostgreSQL
psql -U postgres
-- Create database
CREATE DATABASE arena_db;
-- Create user (optional)
CREATE USER arena_user WITH PASSWORD 'your_password';
-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE arena_db TO arena_user;Option A: Local Redis (Recommended for development)
Windows:
- Download Redis from Redis Windows
- Run
redis-server.exe
macOS:
brew install redis
brew services start redisLinux:
sudo apt-get install redis-server
sudo systemctl start redisOption B: Cloud Redis
- Use services like Redis Cloud, AWS ElastiCache, or Upstash
- Get the connection URL
Create a .env file in the backend directory:
# Database Configuration (Required)
DATABASE_URL=postgresql://username:password@localhost:5432/arena_db
# Redis Configuration (Required)
REDIS_URL=redis://localhost:6379/0
# Auth0 Configuration (Required)
AUTH0_DOMAIN=your-domain.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_AUDIENCE=your-api-audience
# CORS Origins (Required for frontend connection)
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173,http://127.0.0.1:3000,http://127.0.0.1:5173
# AI API Keys for Translation (Required for translation features)
OPENAI_API_KEY=sk-your-openai-api-key
ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key
GOOGLE_API_KEY=your-google-api-key
DEEPSEEK_API_KEY=session_your-novita-ai-session-key
# AWS S3 Configuration (Required for file uploads)
AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=your-aws-secret-key
AWS_BUCKET_NAME=your-bucket-name
AWS_REGION=us-east-1
# System Prompt (Optional - has default)
SYSTEM_PROMPT=You are a professional translation engine. Translate the given text accurately while preserving meaning, tone, and context. Output only the translated text without any additional commentary.
# Model Providers (Required - JSON format)
MODEL_PROVIDERS={"claude-3-5-sonnet-20241022": "anthropic", "claude-3-5-haiku-20241022": "anthropic", "claude-3-opus-20240229": "anthropic", "gemini-1.5-pro": "google", "gemini-1.5-flash": "google", "gpt-4o-mini": "openai", "gpt-4o": "openai", "gpt-4": "openai", "gpt-3.5-turbo": "openai", "deepseek/deepseek-v3.1": "deepseek-v3"}
# Pecha Studio Link (Optional)
STUDIO_LINK=https://studio.pecha.aiInitialize and run Alembic migrations to create database tables:
# Initialize Alembic (only if not already initialized)
alembic init alembic
# Run migrations to create all tables
alembic upgrade headNote: If you encounter migration issues, you can reset the database:
# Downgrade all migrations
alembic downgrade base
# Re-run migrations
alembic upgrade headStart the development server with auto-reload:
# Make sure your virtual environment is activated
python main.py
# Or using uvicorn directly
uvicorn main:app --reload --host 0.0.0.0 --port 8000The API will be available at:
- API Base URL: http://localhost:8000
- Interactive Docs (Swagger): http://localhost:8000/docs
- Alternative Docs (ReDoc): http://localhost:8000/redoc
- API Documentation: http://localhost:8000/documentation
For production deployment:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4backend/
βββ alembic/ # Database migrations
β βββ versions/ # Migration versions
β βββ env.py # Alembic environment config
β βββ script.py.mako # Migration template
βββ CRUD/ # CRUD operations
β βββ model.py # Model CRUD operations
β βββ s3_utils.py # S3 helper functions
β βββ upload_file_to_s3.py # File upload logic
β βββ ground_truth_upload_s3.py
βββ Evaluation/ # Evaluation logic
β βββ evaluation.py # Automatic evaluation system
βββ models/ # SQLAlchemy ORM models
β βββ user.py # User model
β βββ challenge.py # Challenge model
β βββ submission.py # Submission model
β βββ model.py # AI Model model
β βββ result.py # Result model
β βββ arena_challenge.py # Arena challenge model
β βββ arena_rating.py # Arena rating model
β βββ ... # Other models
βββ routers/ # API route handlers
β βββ user.py # User endpoints
β βββ challenge.py # Challenge endpoints
β βββ submission.py # Submission endpoints
β βββ arena_challenge.py # Arena challenge endpoints
β βββ arena_ranking.py # Ranking/leaderboard endpoints
β βββ translate_v2.py # Translation endpoints
β βββ template_v2.py # Template management
β βββ tools.py # Utility tools
β βββ ... # Other routers
βββ schemas/ # Pydantic schemas
β βββ user.py # User schemas
β βββ challenge.py # Challenge schemas
β βββ submission.py # Submission schemas
β βββ ... # Other schemas
βββ service/ # Business logic services
β βββ translate_v2_service.py
βββ templates/ # HTML templates
β βββ documentation.html # API documentation page
βββ samples/ # Sample JSON files
β βββ ocr challenge.json
β βββ ocr submission.json
βββ commentaries_and_sanskrit/ # Buddhist texts data
β βββ choejuk.json
β βββ dorjee_choepa.json
β βββ ...
βββ main.py # FastAPI application entry point
βββ database.py # Database configuration
βββ auth.py # Auth0 JWT authentication
βββ redis_client.py # Redis caching client
βββ submission_worker.py # Background worker for submissions
βββ submission_cache.py # Submission progress caching
βββ background_tasks.py # Background task management
βββ requirements.txt # Python dependencies
βββ alembic.ini # Alembic configuration
βββ .env # Environment variables (create this)
βββ README.md # This file
- Auth0 Integration: Secure JWT-based authentication
- Role-based Access: Protected endpoints with user verification
- Automatic Token Validation: JWT signature verification with Auth0 JWKS
- Create & Manage Challenges: OCR, translation, and custom evaluation tasks
- Arena Challenges: Head-to-head model comparisons
- Template System: Reusable challenge templates
- Category Organization: Group challenges by type and domain
- Queue-based Workers: Non-blocking submission processing
- Progress Tracking: Real-time submission status via Redis cache
- Automatic Evaluation: Integrated evaluation metrics (BLEU, WER, etc.)
- S3 File Storage: Secure file upload and management
- Multi-provider Support: OpenAI, Anthropic, Google, DeepSeek
- Streaming Responses: Real-time translation output
- Model Comparison: Side-by-side translation comparison
- Custom Templates: Configurable prompt templates
- ELO Rating System: Arena-style model rankings
- Score-based Leaderboards: Performance metrics tracking
- Vote Counting: User voting and preferences
- Real-time Updates: Live ranking calculations
- Redis Caching: Fast data retrieval for frequently accessed data
- Submission Progress Cache: Real-time status updates
- JWKS Caching: LRU cache for Auth0 public keys
- Query Optimization: Efficient database queries
| Variable | Required | Default | Description |
|---|---|---|---|
DATABASE_URL |
Yes | - | PostgreSQL connection string |
REDIS_URL |
Yes | - | Redis connection URL |
AUTH0_DOMAIN |
Yes | - | Your Auth0 domain |
AUTH0_CLIENT_ID |
Yes | - | Auth0 application client ID |
AUTH0_AUDIENCE |
Yes | - | Auth0 API audience identifier |
ALLOWED_ORIGINS |
Yes | localhost URLs | Comma-separated CORS origins |
OPENAI_API_KEY |
Yes* | - | OpenAI API key for GPT models |
ANTHROPIC_API_KEY |
Yes* | - | Anthropic API key for Claude |
GOOGLE_API_KEY |
Yes* | - | Google API key for Gemini |
DEEPSEEK_API_KEY |
Yes* | - | DeepSeek API key |
AWS_ACCESS_KEY_ID |
Yes | - | AWS access key for S3 |
AWS_SECRET_ACCESS_KEY |
Yes | - | AWS secret key for S3 |
AWS_BUCKET_NAME |
Yes | - | S3 bucket name for file storage |
AWS_REGION |
Yes | us-east-1 |
AWS region for S3 bucket |
SYSTEM_PROMPT |
No | Default prompt | System prompt for translations |
MODEL_PROVIDERS |
Yes | - | JSON mapping models to providers |
STUDIO_LINK |
No | - | Link to Pecha Studio |
Note: AI API keys marked with * are required only if you plan to use translation features with those specific providers.
When you modify database models:
# Generate a new migration
alembic revision --autogenerate -m "Description of changes"
# Review the generated migration file in alembic/versions/
# Apply the migration
alembic upgrade head# Check current migration version
alembic current
# View migration history
alembic history
# Upgrade to specific version
alembic upgrade <revision_id>
# Downgrade one version
alembic downgrade -1
# Downgrade to base (clear all tables)
alembic downgrade base# WARNING: This will delete all data!
alembic downgrade base
alembic upgrade headOnce the server is running, access the interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- Get an Auth0 access token from your frontend application
- Click the "Authorize" button in Swagger UI
- Enter
Bearer <your_token>in the Auth0Bearer field - Click "Authorize" to apply the token to all requests
Authentication & Users
POST /user- Create a new userGET /user/{user_id}- Get user details
Challenges
GET /challenges- List all challengesPOST /challenge- Create a challenge (protected)GET /challenge/{challenge_id}- Get challenge details
Submissions
POST /submission- Submit a solution (protected)GET /submission/{submission_id}- Get submission statusGET /submission/{submission_id}/progress- Get real-time progress
Arena
GET /arena-challenges- List arena challengesPOST /arena-challenge/{id}/vote- Vote on model comparisonGET /arena-rankings- Get model rankings
Translation
POST /translate-v2/chat- Chat-based translation (streaming)POST /translate-v2/compare- Compare multiple modelsGET /templates-v2- List available templates
Tools
POST /tools/convert-ewts-to-unicode- Convert EWTS to Tibetan Unicode
Problem: "DATABASE_URL is not set"
- Solution: Ensure
.envfile exists with correctDATABASE_URL - Verify PostgreSQL is running:
pg_isready
Problem: "Connection refused to database"
- Solution: Check PostgreSQL service status
- Verify connection details (host, port, username, password)
- Test connection:
psql -U username -d arena_db
Problem: "REDIS_URL is not set"
- Solution: Add
REDIS_URL=redis://localhost:6379/0to.env
Problem: "Redis connection failed"
- Solution: Ensure Redis server is running
- Windows: Check if
redis-server.exeis running - macOS/Linux: Run
redis-cli ping(should return "PONG")
Problem: "alembic.util.exc.CommandError: Target database is not up to date"
- Solution: Run
alembic upgrade head
Problem: "Table already exists"
- Solution: Reset migrations:
alembic downgrade base alembic upgrade head
Problem: "Invalid token"
- Solution: Check Auth0 configuration (domain, audience)
- Verify token is not expired
- Ensure frontend and backend use same Auth0 settings
Problem: "Unable to verify token"
- Solution: Check internet connection (needs to fetch JWKS)
- Verify
AUTH0_DOMAINis correct
Problem: "ModuleNotFoundError"
- Solution: Ensure virtual environment is activated
- Reinstall dependencies:
pip install -r requirements.txt
Problem: "ImportError: attempted relative import with no known parent package"
- Solution: Run from project root:
python main.py
- Set all environment variables in your hosting platform
- Use production database (not local PostgreSQL)
- Use production Redis (managed Redis service recommended)
- Update ALLOWED_ORIGINS with your frontend production URL
- All environment variables configured
- Database migrations run:
alembic upgrade head - Redis connection tested and working
- S3 bucket configured with proper permissions
- Auth0 application configured with production URLs
- AI API keys have sufficient credits
- CORS origins include production frontend URL
Render / Railway / Heroku:
- Set environment variables in dashboard
- Set build command:
pip install -r requirements.txt - Set start command:
uvicorn main:app --host 0.0.0.0 --port $PORT
AWS / DigitalOcean / VPS:
- Use systemd or supervisor to manage the process
- Set up nginx as reverse proxy
- Use gunicorn with uvicorn workers:
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
Docker:
FROM python:3.10
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Regular backups are crucial:
# Backup PostgreSQL database
pg_dump -U username arena_db > backup_$(date +%Y%m%d).sql
# Restore from backup
psql -U username arena_db < backup_20250101.sqlRun the application in development mode and test endpoints:
# Start server
python main.py
# Test root endpoint
curl http://localhost:8000/
# Test with httpie (install: pip install httpie)
http http://localhost:8000/challengesOpenAI:
- Sign up at https://platform.openai.com
- Navigate to API Keys section
- Create new secret key
Anthropic:
- Sign up at https://console.anthropic.com
- Go to API Keys
- Generate new key
Google Gemini:
- Visit https://makersuite.google.com/app/apikey
- Create API key
- Enable Gemini API
AWS S3:
- Create AWS account
- Create IAM user with S3 permissions
- Generate access keys
- Create S3 bucket in desired region
- Create a new branch for your feature
- Make your changes
- Run migrations if models changed:
alembic revision --autogenerate - Test all endpoints
- Submit a pull request
For issues and questions:
- Check the troubleshooting section above
- Review API documentation at
/docs - Check FastAPI logs for detailed error messages
- Verify all environment variables are set correctly
Note: This backend requires a PostgreSQL database and Redis server. For frontend setup instructions, see https://github.com/OpenPecha/openpecha_evalai_frontend/README.md.