alishba20-05/Robotics-book
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference --- <!-- title: RAG Chatbot Backend - Physical AI & Humanoid Robotics emoji: ๐ค colorFrom: green colorTo: blue sdk: docker sdkversion: "3.11" appfile: app.py pinned: false license: mit --> ---
๐ค RAG Chatbot Backend
AI-Powered Assistant for Physical AI & Humanoid Robotics Textbook
This is the backend API for an intelligent chatbot that helps students learn about humanoid robotics, physical AI, kinematics, actuators, sensors, and control systems.
โจ Features
- ๐ง RAG (Retrieval-Augmented Generation) - Answers grounded in textbook content
- ๐ฌ OpenAI ChatKit Integration - Professional chat interface
- ๐ Selected-Text Questioning - Ask questions about highlighted text
- ๐พ Conversation History - Persistent chat sessions with PostgreSQL
- ๐ฏ Vector Search - Semantic search powered by Qdrant
- โก Streaming Responses - Real-time AI responses
๐ ๏ธ Tech Stack
- LLM: Google Gemini 2.5 Flash
- Vector DB: Qdrant Cloud
- Embeddings: Cohere
- Database: Neon Serverless Postgres
- Framework: FastAPI + OpenAI ChatKit
- Deployment: Hugging Face Spaces
๐ก API Endpoints
Health Check
GET /healthChatKit Endpoint
POST /chatkitHandles chat completions with streaming support, conversation history, and selected-text context.
Chat History
GET /api/history/{session_id}Retrieves conversation history for a session.
๐ Required Environment Variables
Set these in your Hugging Face Space Settings > Variables and secrets:
๐ Local Development
# Clone the repository
git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
cd YOUR_SPACE_NAME
# Install dependencies
pip install -r requirements.txt
# Set environment variables
cp .env.example .env
# Edit .env with your API keys
# Initialize database
python -c "from database import init_database; init_database()"
# Run the server
python app.pyServer will start at: http://localhost:7860
๐ Using the API
Example: Chat Request
import requests
response = requests.post(
"https://YOUR-SPACE-NAME.hf.space/chatkit",
json={
"messages": [
{"role": "user", "content": "What is inverse kinematics?"}
]
},
headers={
"X-Session-Id": "your-session-id",
"X-Selected-Text": "" # Optional: highlighted text context
},
stream=True
)
for line in response.iter_lines():
print(line.decode())Example: Get Chat History
import requests
response = requests.get(
"https://YOUR-SPACE-NAME.hf.space/api/history/your-session-id"
)
history = response.json()
print(history)๐ Frontend Integration
Update your frontend to use this backend:
// src/components/Chatkit-chatbot/index.jsx
const { control } = useChatKit({
api: {
url: 'https://YOUR-SPACE-NAME.hf.space/chatkit',
domainKey: 'production',
fetch: customFetch,
},
// ... other config
});๐ Project Structure
โโโ app.py # Hugging Face Spaces entry point
โโโ chatkit_server.py # Main FastAPI application
โโโ database.py # SQLAlchemy models & database setup
โโโ requirements.txt # Python dependencies
โโโ .env.example # Environment variables template
โโโ agent/
โ โโโ rag_agent.py # RAG agent with tool calling
โโโ src/
โ โโโ utils/
โ โโโ config.py # Configuration management
โ โโโ logger.py # Logging utilities
โ โโโ models.py # Pydantic models
โ โโโ qdrant_client.py # Vector DB client
โโโ tools/
โโโ agent_tools.py # Qdrant retrieval tools
โโโ memory_store.py # Memory management๐๏ธ Database Schema
chat_sessions
session_id(PK) - Unique session identifiercreated_at- Session creation timestamplast_activity- Last message timestamp
chat_messages
id(PK) - Message UUIDsession_id(FK) - References chat_sessionsrole- 'user' or 'assistant'content- Message textselected_text- Optional highlighted text contexttimestamp- Message creation time
๐ Security Notes
- โ All API keys stored as Hugging Face Secrets
- โ CORS enabled for your frontend domain
- โ Database uses SSL connections
- โ No sensitive data in logs
- โ ๏ธ Make this Space private if you're using paid API keys
๐ Monitoring
View logs in Hugging Face Spaces:
Settings > LogsHealth check endpoint for monitoring:
curl https://YOUR-SPACE-NAME.hf.space/health๐ Troubleshooting
Space won't start
- Check logs in HF Spaces dashboard
- Verify all environment variables are set
- Ensure database connection string is correct
Database connection errors
- Verify Neon Postgres URL format
- Check if SSL mode is enabled:
?sslmode=require - Ensure database exists and is accessible
Qdrant connection errors
- Verify cluster URL and API key
- Check if collection exists
- Ensure API key has correct permissions
ChatKit errors
- Check if session ID is valid UUID format
- Verify messages format is correct
- Ensure streaming is properly handled
๐ License
MIT License - See LICENSE file for details
๐ค Contributing
This is a production deployment space. For contributions, please visit the main repository.
๐ง Support
For issues related to:
- Backend API: Check logs and troubleshooting section
- Frontend Integration: Update API URL in your frontend
- Hugging Face Spaces: See HF Spaces Documentation
Built with โค๏ธ for the Physical AI & Humanoid Robotics Community
Powered by: OpenAI ChatKit โข Google Gemini โข Qdrant โข Neon Postgres โข Cohere
