CoolFace
Apppublic

alishba20-05/Robotics-book

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
App README

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

bash
GET /health

ChatKit Endpoint

bash
POST /chatkit

Handles chat completions with streaming support, conversation history, and selected-text context.

Chat History

bash
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:

VariableDescriptionExample
QDRANT_URLQdrant Cloud cluster URLhttps://xxx.qdrant.cloud
QDRANT_API_KEYQdrant API keyxxx
COHERE_API_KEYCohere API key for embeddingsxxx
GEMINI_API_KEYGoogle Gemini API keyxxx
NEON_DATABASE_URLNeon Postgres connection stringpostgresql://user:pass@host/db
CHATKIT_BACKEND_PORTServer port (default: 7860)7860

๐Ÿš€ Local Development

bash
# 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.py

Server will start at: http://localhost:7860

๐Ÿ“– Using the API

Example: Chat Request

python
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

python
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:

javascript
// 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 identifier
  • โ€”created_at - Session creation timestamp
  • โ€”last_activity - Last message timestamp

chat_messages

  • โ€”id (PK) - Message UUID
  • โ€”session_id (FK) - References chat_sessions
  • โ€”role - 'user' or 'assistant'
  • โ€”content - Message text
  • โ€”selected_text - Optional highlighted text context
  • โ€”timestamp - 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 > Logs

Health check endpoint for monitoring:

bash
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