A Django backend server that connects Twilio phone calls to OpenAI's Realtime API, enabling voice conversations with AI agents over the phone.
- π― WebSocket Integration: Real-time connection to OpenAI's Realtime API
- π Twilio Integration: Handle incoming phone calls and stream audio
- π€ Agent Management: Configurable AI agents with different personalities and settings
- π΅ Audio Streaming: Bidirectional audio streaming between Twilio and OpenAI
- π Session Tracking: Track call sessions and conversation logs
- βοΈ Admin Interface: Django admin for managing agents and viewing call history
Twilio Call β Django WebSocket β OpenAI Realtime API
β β β
Phone User β Audio Stream β AI Assistant Response
- Python 3.10+
- Redis server (for Django Channels)
- Twilio account
- OpenAI API key with Realtime API access
-
Clone and install dependencies:
pip install -r requirements.txt
-
Environment Configuration: Create a
.env
file based onenv_example.txt
:OPENAI_API_KEY=your_openai_api_key_here TWILIO_ACCOUNT_SID=your_twilio_account_sid_here TWILIO_AUTH_TOKEN=your_twilio_auth_token_here SECRET_KEY=your_secret_key_here DEBUG=True REDIS_URL=redis://localhost:6379
-
Database Setup:
python manage.py migrate python manage.py create_default_agent python manage.py createsuperuser
-
Start Redis Server:
redis-server
-
Run the Development Server:
python manage.py runserver
-
Configure Webhook URL in your Twilio phone number settings:
https://your-domain.com/api/webhook/
-
Status Callback URL (optional):
https://your-domain.com/api/status/
Access the Django admin at /admin/
to:
- Create and manage AI agent configurations
- Set voice, temperature, instructions, and other parameters
- View call session history and conversation logs
The WebSocket endpoint for real-time communication:
wss://your-domain.com/ws/realtime/{session_id}/
Endpoint | Method | Description |
---|---|---|
/api/webhook/ |
POST | Twilio webhook for incoming calls |
/api/status/ |
POST | Twilio status callback |
/api/health/ |
GET | Health check endpoint |
/admin/ |
GET | Django admin interface |
- Purpose: Define AI agent behavior and settings
- Fields: name, instructions, voice, temperature, audio formats, VAD settings
- Methods:
to_openai_config()
- converts to OpenAI session format
- Purpose: Track individual call sessions
- Fields: session_id, twilio_call_sid, agent_config, call timing, conversation_log
- Methods:
add_to_conversation_log()
- log conversation events
The RealtimeConsumer
handles:
- Connection Management: Establish connections to OpenAI Realtime API
- Audio Streaming: Bidirectional audio between Twilio and OpenAI
- Session Configuration: Apply agent settings to OpenAI session
- Message Routing: Route messages between Twilio and OpenAI
- Error Handling: Graceful error handling and connection cleanup
twilio_stream_start
: Stream initializationtwilio_media
: Audio data packetstwilio_stream_stop
: Stream termination
session.created
: Session establishedresponse.audio.delta
: Audio response chunksresponse.text.delta
: Text response chunksconversation.item.created
: New conversation item
realtime_backend/
βββ realtime_api/ # Main application
β βββ consumers.py # WebSocket consumer
β βββ models.py # Database models
β βββ views.py # HTTP views
β βββ routing.py # WebSocket routing
β βββ admin.py # Admin configuration
βββ realtime_backend/ # Django project settings
βββ requirements.txt # Python dependencies
βββ README.md # This file
-
WebSocket Consumer (
consumers.py
):- Handles real-time communication
- Manages OpenAI API connections
- Processes audio streaming
-
Models (
models.py
):- Agent configuration management
- Call session tracking
- Conversation logging
-
Views (
views.py
):- Twilio webhook handlers
- TwiML response generation
- Health check endpoints
- WebSocket Server: Use Daphne or similar ASGI server
- Redis: Configure Redis for production use
- SSL/TLS: Ensure HTTPS/WSS for secure connections
- Environment Variables: Secure API key management
- Logging: Configure appropriate logging levels
- Monitoring: Set up health checks and monitoring
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "realtime_backend.asgi:application"]
-
WebSocket Connection Failed:
- Check OpenAI API key and permissions
- Verify Realtime API access
- Check network connectivity
-
Audio Quality Issues:
- Verify audio format settings (PCM16)
- Check VAD threshold settings
- Review network latency
-
Twilio Integration:
- Verify webhook URL accessibility
- Check Twilio credentials
- Review TwiML response format
Enable debug logging in settings.py
:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'realtime_api': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License.
For issues and questions:
- Check the troubleshooting section
- Review Django Channels documentation
- Consult OpenAI Realtime API documentation
- Check Twilio WebSocket documentation