noorulsehar/physical-ai-humanoid-robotics-book-backend
0
Physical AI Humanoid Robotics Book - Python Backend API
๐ A high-performance FastAPI backend for the Physical AI Humanoid Robotics Book project
๐ฏ Features
- โก FastAPI Framework: High-performance async API with automatic OpenAPI documentation
- ๐ JWT Authentication: Secure user authentication with token-based sessions
- ๐๏ธ PostgreSQL Database: Async SQLAlchemy ORM with connection pooling
- ๐ง Qdrant Vector DB: RAG (Retrieval-Augmented Generation) for intelligent chat
- ๐ค OpenRouter Integration: AI-powered translation and personalization
- ๐ Smart CORS: Wildcard pattern matching for flexible frontend integration
- ๐ Production Ready: Optimized for both traditional and serverless (Vercel) deployment
- ๐ Automatic Docs: Swagger UI & ReDoc included out-of-the-box
- ๐ง Environment-Aware: Separate configurations for development, testing, and production
๐ Project Structure
physical-ai-humanoid-robotics-book-backend/
โโโ ๐ app.py # Main FastAPI application
โโโ ๐ main.py # Local development entry point
โโโ ๐ vercel_handler.py # Vercel serverless handler
โโโ ๐ requirements.txt # Python dependencies
โโโ ๐ .env.example # Environment variables template
โโโ ๐ vercel.json # Vercel deployment configuration
โโโ ๐ Dockerfile.python # Docker configuration
โโโ ๐ README.md # This file
โ
โโโ ๐ config/
โ โโโ __init__.py
โ โโโ settings.py # Application settings and configuration
โ
โโโ ๐ middleware/
โ โโโ __init__.py
โ โโโ cors_config.py # CORS configuration with wildcard support
โ
โโโ ๐ utils/
โ โโโ __init__.py
โ โโโ db.py # Database connection and utilities
โ โโโ qdrant_client.py # Qdrant vector database client
โ โโโ auth_service.py # Authentication utilities (JWT)
โ โโโ models.py # SQLAlchemy database models
โ
โโโ ๐ routes/
โโโ __init__.py
โโโ auth.py # Authentication routes
โโโ translation.py # Translation routes
โโโ personalization.py # Personalization routes
โโโ chat.py # RAG chat routes๐ Quick Start
Prerequisites
- Python 3.11+ (Recommended: 3.11 or higher)
- PostgreSQL 14+ (or compatible database)
- Qdrant (optional, for RAG features)
- OpenRouter API Key (get one from openrouter.ai)
1. Clone & Setup
# Clone the repository
git clone <your-repository-url>
cd physical-ai-humanoid-robotics-book-backend
# Create virtual environment
python -m venv venv
# Activate virtual environment
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt2. Environment Configuration
# Copy environment template
cp .env.example .env
# Edit .env with your values
nano .env # or use your favorite editorRequired `.env` values:
# Server Configuration
CENTRAL_BACKEND_PORT=3001
NODE_ENV=development
# Database
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/ai_book_db
# AI Services
OPENROUTER_API_KEY=your_openrouter_api_key_here
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
OPENROUTER_CHAT_MODEL=google/gemini-2.0-flash-exp:free
OPENROUTER_EMBEDDING_MODEL=openai/text-embedding-ada-002
# Vector Database (Optional)
QDRANT_URL=http://localhost:6333
QDRANT_API_KEY=optional_qdrant_key
QDRANT_COLLECTION_NAME=book_content
# Security
SECRET_KEY=your_super_secret_jwt_key_here_min_32_chars
BETTER_AUTH_SECRET=your_better_auth_secret_here
# CORS Configuration (for development)
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173,https://*.vercel.app3. Database Setup
# Ensure PostgreSQL is running
# Create database (if not exists)
createdb ai_book_db
# The application will automatically create tables on first run
# For manual table creation:
python -c "
from utils.db import init_db
import asyncio
asyncio.run(init_db())
print('Database initialized!')
"4. Start Development Server
# Option 1: Using main.py (auto-reload enabled)
python main.py
# Option 2: Using uvicorn directly
uvicorn app:app --reload --host 0.0.0.0 --port 3001
# Option 3: With custom port
python main.py --port 3001
# Server will be available at: http://localhost:30015. Verify Installation
# Check health endpoint
curl http://localhost:3001/health
# Expected response: {"status":"ok","timestamp":"2024-01-01T12:00:00Z"}๐ API Documentation
Once running, access the interactive API docs:
- Swagger UI: http://localhost:3001/docs
- ReDoc: http://localhost:3001/redoc
๐ API Endpoints
Health Check
GET /health- Server health statusGET /chat/health- Chat service health
Authentication
GET /api/auth/auth-health- Auth service statusPOST /api/auth/sign-up/email- Register new userPOST /api/auth/sign-in/email- Login userPOST /api/auth/sign-out- Logout userGET /api/auth/get-session- Get current session
AI Translation
POST /api/gemini/translate- Translate text with AI
{
"text": "Hello world",
"target_language": "Spanish",
"context": "Casual conversation"
}POST /api/translate- Alternative translation endpoint
{
"text": "Humanoid robotics is fascinating",
"target_language": "French"
}Content Personalization
POST /api/personalize- Personalize content based on user profile
{
"user_id": "user_123",
"content": "Original content",
"preferences": {"difficulty": "beginner", "topics": ["robotics"]}
}RAG Chat
POST /chat- Intelligent chat with book content context
{
"message": "What are humanoid robots?",
"user_id": "user_123",
"session_id": "session_456"
}๐ณ Docker Deployment
1. Build Docker Image
# Build with Python 3.11
docker build -f Dockerfile.python -t physical-ai-backend .
# Build with custom tag
docker build -f Dockerfile.python -t physical-ai-backend:latest .2. Run Container
# Basic run
docker run -p 3001:3001 --name ai-backend physical-ai-backend
# With environment file
docker run -p 3001:3001 --env-file .env --name ai-backend physical-ai-backend
# With volume for logs
docker run -p 3001:3001 -v ./logs:/app/logs --env-file .env --name ai-backend physical-ai-backend3. Docker Compose (Recommended)
Create a docker-compose.yml file:
version: '3.8'
services:
postgres:
image: postgres:15-alpine
environment:
POSTGRES_DB: ai_book_db
POSTGRES_USER: ai_user
POSTGRES_PASSWORD: ai_password
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ai_user"]
interval: 10s
timeout: 5s
retries: 5
qdrant:
image: qdrant/qdrant:latest
ports:
- "6333:6333"
- "6334:6334"
volumes:
- qdrant_data:/qdrant/storage
backend:
build:
context: .
dockerfile: Dockerfile.python
ports:
- "3001:3001"
environment:
DATABASE_URL: postgresql+asyncpg://ai_user:ai_password@postgres:5432/ai_book_db
QDRANT_URL: http://qdrant:6333
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY}
SECRET_KEY: ${SECRET_KEY}
depends_on:
postgres:
condition: service_healthy
qdrant:
condition: service_started
volumes:
- .:/app
- ./logs:/app/logs
volumes:
postgres_data:
qdrant_data:Run with Docker Compose:
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
# Stop and remove volumes
docker-compose down -vโ๏ธ Vercel Deployment
1. Install Vercel CLI
npm install -g vercel
# or
yarn global add vercel2. Deploy to Vercel
# Login to Vercel
vercel login
# Deploy from current directory
vercel
# Deploy with production flag
vercel --prod
# Set environment variables
vercel env add OPENROUTER_API_KEY
vercel env add DATABASE_URL
vercel env add SECRET_KEY3. Configure Vercel Environment Variables
In Vercel Dashboard โ Project โ Settings โ Environment Variables:
DATABASE_URL=postgresql+asyncpg://...
OPENROUTER_API_KEY=sk-or-...
SECRET_KEY=your-secret-key-here
BETTER_AUTH_SECRET=your-auth-secret
QDRANT_URL=https://your-qdrant-instance
QDRANT_API_KEY=your-qdrant-key
NODE_ENV=production
ALLOWED_ORIGINS=https://your-frontend.vercel.app,https://*.vercel.app4. Manual Deployment via Git
# Link your repository
vercel git connect
# Each push to main branch triggers deployment
git push origin main๐ง Configuration
Environment Variables
Database Models
The application uses these main models:
- User: User accounts and profiles
- Session: User authentication sessions
- Account: Linked authentication accounts
- ChatHistory: Store chat conversations
- UserPreferences: User personalization settings
๐งช Testing
Run Tests
# Install test dependencies
pip install pytest pytest-asyncio httpx
# Run all tests
pytest
# Run with coverage
pytest --cov=app --cov-report=html
# Run specific test file
pytest tests/test_auth.py -vTest Endpoints with curl
# Health check
curl http://localhost:3001/health
# Auth health
curl http://localhost:3001/api/auth/auth-health
# Sign up
curl -X POST http://localhost:3001/api/auth/sign-up/email \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"secure123","name":"Test User"}'
# Translate
curl -X POST http://localhost:3001/api/gemini/translate \
-H "Content-Type: application/json" \
-d '{"text":"Hello world","target_language":"Spanish"}'๐ ๏ธ Development
Code Quality Tools
# Install development dependencies
pip install black isort flake8 mypy
# Format code
black .
isort .
# Lint code
flake8 .
# Type checking
mypy .
# Run all checks
./scripts/check.shDebugging
# Enable debug mode
export NODE_ENV=development
python main.py --debug
# With detailed logging
export LOG_LEVEL=DEBUG
python main.pyDatabase Migrations
For schema changes, use Alembic:
# Initialize alembic (first time only)
alembic init migrations
# Create migration
alembic revision --autogenerate -m "Description"
# Apply migration
alembic upgrade head
# Rollback migration
alembic downgrade -1๐ Monitoring & Logging
Access Logs
# Local development logs
tail -f logs/app.log
# Docker logs
docker logs -f ai-backend
# Docker Compose logs
docker-compose logs -f backendHealth Monitoring
# Check all health endpoints
curl http://localhost:3001/health
curl http://localhost:3001/chat/health
curl http://localhost:3001/api/auth/auth-health
# Prometheus metrics (if enabled)
curl http://localhost:3001/metrics๐ Security Best Practices
- Secrets Management:
- Never commit
.envfiles - Use environment variables in production
- Rotate secrets regularly
- Database Security:
- Use strong passwords
- Enable SSL for production databases
- Restrict database access by IP
- API Security:
- Validate all input data
- Rate limiting for public endpoints
- JWT token expiration (default: 24 hours)
- CORS Configuration:
# Production configuration
ALLOWED_ORIGINS=https://your-domain.com,https://*.your-domain.com
# Development configuration
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173๐จ Troubleshooting
Common Issues & Solutions
1. Database Connection Failed
# Check PostgreSQL is running
sudo systemctl status postgresql
# Test connection
psql -U username -d ai_book_db -h localhost
# Update DATABASE_URL in .env
DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/ai_book_db2. Port Already in Use
# Find process using port 3001
sudo lsof -i :3001
# Kill the process
sudo kill -9 <PID>
# Or change port in .env
CENTRAL_BACKEND_PORT=30023. Import Errors
# Reinstall dependencies
pip uninstall -r requirements.txt -y
pip install -r requirements.txt
# Check Python version
python --version # Should be 3.11+
# Recreate virtual environment
rm -rf venv
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt4. CORS Issues
# Check ALLOWED_ORIGINS
echo $ALLOWED_ORIGINS
# Test CORS headers
curl -I -X OPTIONS http://localhost:3001/api/auth/sign-in/email5. JWT Authentication Issues
# Verify SECRET_KEY length (min 32 chars)
echo ${#SECRET_KEY}
# Check token expiration
jwt.decode(token, SECRET_KEY, algorithms=["HS256"])Debug Mode
# Enable full debug output
export DEBUG=true
export LOG_LEVEL=DEBUG
python main.py
# Check logs in real-time
tail -f logs/app.log๐ค Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests and checks
- Submit a pull request
Development Setup
# Fork and clone
git clone https://github.com/your-username/physical-ai-humanoid-robotics-book-backend.git
cd physical-ai-humanoid-robotics-book-backend
# Set up development environment
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install -r requirements-dev.txt
# Run tests
pytest
# Make your changes and test๐ License
MIT License - see LICENSE file for details.
๐ Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: support@example.com
๐ Acknowledgments
- FastAPI - The modern web framework
- OpenRouter - AI model routing service
- Qdrant - Vector similarity search engine
- Vercel - Serverless deployment platform
<div align="center">
Made with โค๏ธ for the Physical AI Humanoid Robotics Book Project
โก Get Started | ๐ API Docs | ๐ณ Docker | โ๏ธ Vercel
</div>
