AsifAliAstolixgen/physical-ai-book-api
Backend - Physical AI & Humanoid Robotics Book
FastAPI backend providing RAG chatbot, personalization, and translation services for the AI-native textbook.
Features
- RAG Chatbot: Two-mode Q&A system (book-wide and selection-based)
- Personalization: Content adaptation based on user hardware and experience
- Translation: Multi-language support (EN, UR, FR, AR, DE) with caching
- Vector Search: Qdrant for semantic search
- Database: Neon Serverless Postgres for user data
- LLM Integration: OpenAI GPT-4 and embeddings
Architecture
backend/
├── main.py # FastAPI app entry point
├── config.py # Configuration and settings
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
├── alembic/ # Database migrations
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
│ └── 20250101_0000_001_initial_schema.py
├── models/ # SQLAlchemy models
│ ├── __init__.py
│ ├── user.py # User profiles
│ └── content.py # Reading progress, RAG logs, translation cache
├── services/ # Business logic
│ ├── qdrant_service.py # Vector database operations
│ └── embedding_service.py # OpenAI embeddings
├── api/ # API endpoints
│ ├── rag/
│ │ ├── book_qa.py # Book-wide Q&A
│ │ └── selection_qa.py # Selection-based Q&A
│ ├── personalization/
│ │ ├── user_profile.py # User profile CRUD
│ │ └── content_adapter.py # Content adaptation
│ └── translation/
│ └── translate.py # Translation with caching
└── scripts/
└── generate_embeddings.py # Embed docs and upload to QdrantSetup
1. Prerequisites
- Python 3.11+
- PostgreSQL (Neon Serverless or local)
- Qdrant Cloud account (or local instance)
- OpenAI API key
2. Install Dependencies
cd backend
pip install -r requirements.txt3. Configure Environment
Copy .env.example to .env and fill in your credentials:
cp .env.example .envRequired environment variables:
# Qdrant Vector Database
QDRANT_URL=https://your-cluster.qdrant.tech
QDRANT_API_KEY=your-qdrant-api-key
QDRANT_COLLECTION_NAME=physical-ai-book
# Neon Serverless Postgres
DATABASE_URL=postgresql://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb
# OpenAI API
OPENAI_API_KEY=sk-...
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
OPENAI_CHAT_MODEL=gpt-4-turbo-preview
# App Settings
APP_NAME="Physical AI Book API"
ENVIRONMENT=development
DEBUG=true
HOST=0.0.0.0
PORT=8000
CORS_ORIGINS=["http://localhost:3000", "https://yourdomain.github.io"]4. Initialize Database
Run Alembic migrations to create tables:
alembic upgrade headThis creates:
user_profiles- User hardware, experience, preferencesreading_progress- Chapter completion trackingrag_query_logs- Chatbot analyticstranslation_cache- Cached translations
5. Generate Embeddings
Embed all markdown files and upload to Qdrant:
python -m scripts.generate_embeddingsThis will:
- Scan
docs/directory for markdown files - Chunk content by sections
- Generate embeddings using OpenAI
- Upload to Qdrant with metadata
6. Run Development Server
uvicorn main:app --reload --host 0.0.0.0 --port 8000Server will start at: http://localhost:8000
- API Docs: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
API Endpoints
RAG (Retrieval-Augmented Generation)
Book-wide Q&A
POST /api/rag/book-qa
Content-Type: application/json
{
"query": "What is ROS 2?",
"user_id": "uuid-optional"
}Response:
{
"answer": "ROS 2 (Robot Operating System 2) is...",
"sources": [
{"section_id": "modules/ros2/index", "score": 0.92},
{"section_id": "foundations/index", "score": 0.85}
],
"response_time_ms": 1243
}Selection-based Q&A
POST /api/rag/selection-qa
Content-Type: application/json
{
"query": "What does this mean?",
"selected_text": "Quality of Service (QoS) policies...",
"user_id": "uuid-optional"
}Translation
Translate Section
POST /api/translation/translate
Content-Type: application/json
{
"section_id": "modules/ros2/index",
"target_language": "ur"
}Response:
{
"translated_content": "# ROS 2: روبوٹک اعصابی نظام\n\n...",
"cache_hit": false,
"translation_time_ms": 3456
}Supported Languages
GET /api/translation/supported-languagesResponse:
{
"languages": [
{"code": "en", "name": "English", "direction": "ltr"},
{"code": "ur", "name": "Urdu", "direction": "rtl"},
{"code": "fr", "name": "French", "direction": "ltr"},
{"code": "ar", "name": "Arabic", "direction": "rtl"},
{"code": "de", "name": "German", "direction": "ltr"}
]
}Personalization
Create User Profile
POST /api/personalization/profile
Content-Type: application/json
{
"email": "user@example.com",
"hardware": {
"has_rtx_gpu": true,
"has_jetson": false,
"jetson_model": "none",
"robot_type": "none",
"has_realsense": false,
"has_lidar": false
},
"experience": {
"ros2": "beginner",
"ml": "intermediate",
"robotics": "beginner",
"simulation": "none"
},
"preferences": {
"language": "en",
"theme": "dark"
}
}Adapt Content
POST /api/personalization/adapt-content
Content-Type: application/json
{
"section_id": "modules/isaac/index",
"user_id": "uuid"
}Response:
{
"section_id": "modules/isaac/index",
"original_length": 5432,
"adapted_length": 6789,
"adaptations": [
{
"position": "after",
"target_heading": "Hardware Requirements",
"content": "### ☁️ Cloud GPU Alternative...",
"reason": "User has no RTX GPU"
},
{
"position": "before",
"target_heading": null,
"content": "> 📚 New to ROS 2?...",
"reason": "User is ROS 2 beginner"
}
],
"adapted_content": "..."
}Database Schema
user_profiles
reading_progress
Tracks user progress through chapters.
ragquerylogs
Logs all chatbot queries for analytics.
translation_cache
Caches translations using SHA-256 content hash for automatic invalidation.
Services
Qdrant Service
Vector database operations:
create_collection_if_not_exists()- Initialize collectionupsert_chunks(chunks)- Upload embeddingssearch(query_vector, top_k, filters)- Semantic search
Embedding Service
OpenAI embedding generation:
embed_query(text)- Single query embeddinggenerate_embeddings_batch(texts)- Batch embeddingscompute_content_hash(content)- SHA-256 hash
Personalization Rules
Content adaptations based on user profile:
Development
Run Tests
pytest tests/Linting
ruff check .
black .Type Checking
mypy .Update Database Schema
After modifying models:
# Auto-generate migration
alembic revision --autogenerate -m "Description"
# Apply migration
alembic upgrade headRe-generate Embeddings
After updating content:
python -m scripts.generate_embeddingsDeployment
Production Checklist
- [ ] Set
DEBUG=falsein.env - [ ] Set
ENVIRONMENT=production - [ ] Update
CORS_ORIGINSto production domain - [ ] Use production database URL
- [ ] Rotate API keys
- [ ] Enable HTTPS
- [ ] Set up monitoring (health check endpoint)
- [ ] Configure rate limiting
- [ ] Set up logging aggregation
Deploy to Hugging Face Spaces (Free)
- Create a new Space at https://huggingface.co/new-space
- Choose Docker as the SDK
- Set visibility (public or private)
- Clone the Space repository:
git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
cd YOUR_SPACE_NAME- Copy backend files:
cp -r /path/to/backend/* .- Push to Hugging Face:
git add .
git commit -m "Initial deployment"
git push- Set Secrets in Space Settings:
OPENAI_API_KEY- Your OpenAI API keyQDRANT_URL- Qdrant Cloud URLQDRANT_API_KEY- Qdrant API keyDATABASE_URL- Neon Postgres connection stringJWT_SECRET- Random secret for JWT tokensENVIRONMENT- Set toproduction
Your API will be available at: https://YOUR_USERNAME-YOUR_SPACE_NAME.hf.space
Deploy to Cloud
Example with Google Cloud Run:
# Build container
docker build -t physical-ai-book-api .
# Push to registry
docker tag physical-ai-book-api gcr.io/PROJECT_ID/physical-ai-book-api
docker push gcr.io/PROJECT_ID/physical-ai-book-api
# Deploy
gcloud run deploy physical-ai-book-api \
--image gcr.io/PROJECT_ID/physical-ai-book-api \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars "DATABASE_URL=...,OPENAI_API_KEY=..."Cost Estimates
Free Tier Limits
- Qdrant Cloud: 1GB storage (free)
- Neon Postgres: 512MB storage (free)
- OpenAI:
- Embeddings: ~$0.13 per 1M tokens
- GPT-4 Turbo: ~$10 per 1M input tokens
- Translation cache reduces costs by 80-90%
Monthly Costs (Estimate)
Assuming 1,000 users, 10,000 queries/month:
- Qdrant: $0 (free tier)
- Neon: $0 (free tier)
- OpenAI Embeddings (one-time): ~$5
- OpenAI Chat: ~$20-50/month
- Total: $20-50/month
Troubleshooting
Qdrant Connection Failed
- Check
QDRANT_URLandQDRANT_API_KEY - Verify cluster is running
- Check firewall rules
Database Connection Error
- Verify
DATABASE_URLformat - Check Neon instance is active
- Run
alembic upgrade head
OpenAI Rate Limit
- Implement request queuing
- Use batch endpoints
- Consider caching responses
Slow Embeddings
- Use batch processing (done in script)
- Consider pre-generating embeddings
- Cache frequently accessed embeddings
License
MIT License - See LICENSE file for details
Support
For issues, questions, or contributions:
- GitHub Issues: https://github.com/yourusername/ai-humanoid-robotics-as/issues
- Documentation: https://yourdomain.github.io/ai-humanoid-robotics-as/
