A real-time voice agent built with Python that uses OpenAI's Realtime API for natural voice conversations.
- Real-time audio streaming: Capture audio from your microphone and stream it to OpenAI
- Natural conversations: Use OpenAI's Realtime API for low-latency voice interactions
- Audio playback: Play back AI responses through your speakers
- WebSocket-based: Efficient bidirectional communication with OpenAI
The voice agent consists of several key components:
- Audio Capture Module (
audio_capture.py): Handles microphone input and audio streaming - OpenAI Client Module (
openai_client.py): Manages WebSocket connection to OpenAI Realtime API - Audio Playback Module (
audio_playback.py): Handles audio output and playback - Main Orchestrator (
main.py): Coordinates all components and manages the conversation flow
- Python 3.9 or higher
- OpenAI API key with Realtime API access
- Microphone and speakers
- Internet connection
cd python-voice-agentpython -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activatepip install -r requirements.txtCopy the example environment file and add your OpenAI API key:
cp .env.example .envEdit .env and add your OpenAI API key:
OPENAI_API_KEY=your_api_key_here
Run the voice agent:
python main.pyThe agent will:
- Initialize the connection to OpenAI Realtime API
- Start listening to your microphone
- Begin the conversation - just start speaking!
- Press
Ctrl+Cto stop
You can modify settings in config.py:
SAMPLE_RATE: Audio sample rate (default: 24000 Hz)CHANNELS: Audio channels (default: 1 - mono)CHUNK_SIZE: Audio chunk size for streaming (default: 4096)MODEL: OpenAI model to use (default: "gpt-4o-realtime-preview-2024-12-17")
The AudioCapture class uses PyAudio to:
- Open an audio stream from your microphone
- Capture audio in chunks
- Convert audio to base64-encoded format
- Stream audio data to the OpenAI client
The OpenAIRealtimeClient class:
- Establishes a WebSocket connection to OpenAI's Realtime API
- Sends audio chunks for processing
- Receives transcriptions and audio responses
- Handles conversation state and events
The AudioPlayback class:
- Receives audio responses from OpenAI
- Decodes base64 audio data
- Plays audio through your speakers
- Manages playback queue for smooth output
User speaks → Microphone → Audio Capture → Base64 encoding
↓
OpenAI Realtime API
↓
Audio Response (base64)
↓
Speaker ← Audio Playback ← Base64 decoding ← Response
class AudioCapture:
def start_stream(self, callback)
def stop_stream()
def is_active()class OpenAIRealtimeClient:
async def connect()
async def send_audio(audio_data: bytes)
async def disconnect()
def set_audio_callback(callback)class AudioPlayback:
def play_audio(audio_data: bytes)
def stop()
def is_playing()- Make sure you've created a
.envfile with yourOPENAI_API_KEY - Verify the API key is valid and has Realtime API access
- Check that your microphone is connected and enabled
- Verify microphone permissions on your OS
- Check your internet connection
- Verify your API key has access to the Realtime API
- Check OpenAI service status
- Adjust
SAMPLE_RATEinconfig.py - Check your microphone settings
- Ensure a stable internet connection
python-voice-agent/
├── README.md # This file
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
├── .env # Your API keys (gitignored)
├── config.py # Configuration settings
├── audio_capture.py # Microphone input handling
├── audio_playback.py # Audio output handling
├── openai_client.py # OpenAI Realtime API integration
├── main.py # Main orchestrator
└── .gitignore # Git ignore rules
This project was built following these steps:
- Initial Setup: Created project structure and configuration files
- Dependencies: Set up Python packages (websockets, pyaudio, openai, etc.)
- Audio Capture: Implemented microphone input with PyAudio
- OpenAI Integration: Built WebSocket client for Realtime API
- Audio Playback: Created audio output system
- Orchestration: Integrated all components in main.py
- Documentation: Added comprehensive docs and comments
- Sample Rate: 24000 Hz (required by OpenAI Realtime API)
- Encoding: 16-bit PCM
- Channels: Mono (1 channel)
- Transport: Base64-encoded for WebSocket transmission
The OpenAI Realtime API uses WebSocket for bidirectional streaming:
- Events from client:
input_audio_buffer.append,conversation.item.create - Events from server:
response.audio.delta,response.text.delta,response.done
- Audio is streamed in chunks to minimize latency
- Base64 encoding adds ~33% overhead but enables WebSocket transport
- Async I/O ensures non-blocking audio processing
To extend this voice agent:
- Add custom instructions in
openai_client.py - Implement voice activity detection in
audio_capture.py - Add conversation history management
- Implement function calling capabilities
MIT License - feel free to use and modify as needed.
For issues or questions:
- Check the troubleshooting section above
- Review OpenAI API documentation
- Verify your environment setup
Note: This project requires an OpenAI API key with access to the Realtime API. The Realtime API may incur costs based on usage.