Build a Voice AI Agent With the OpenAI Realtime API
Learn to build a voice AI agent with the OpenAI Realtime API. Connect over WebSocket, configure a session, add tools, and handle interruptions in Python.
By Galactic News Editorial · Published 2026-11-18T16:43:15+00:00 · Updated 2026-11-18T16:43:15+00:00
Build a Voice AI Agent With the OpenAI Realtime API
The OpenAI Realtime API lets one model listen and speak in a single live session. There is no separate transcription step. There is no separate voice step. Audio streams in, and audio streams back. This tutorial builds a working voice agent with it. You will connect over WebSocket, configure a session, add a tool, and handle interruptions. The example uses Python and the OpenAI Agents SDK. The same ideas apply to raw WebSocket code.
What the OpenAI Realtime API Is
The Realtime API is a speech-to-speech interface. One model handles listening, reasoning, and speaking. The connection stays open for the whole conversation. The model hears the caller, decides what to do, and answers out loud. It can also call your functions mid-conversation. That makes it a real voice agent, not a chatbot with a microphone bolted on.
The API reached general availability on 28 August 2025. The current model to start with is gpt-realtime-2.1. A cheaper mini model, gpt-realtime-2.1-mini, covers lighter workloads. The original gpt-realtime model shuts down on 20 January 2027, so name the 2.1 model in new code.
Every message on the connection is a JSON event. Your code sends audio and control events. The API sends back audio deltas, transcripts, and tool-call events. Turn detection is built in. The server notices when the caller stops speaking and when they start talking over the agent.
Choose Your Transport: WebSocket, WebRTC, or SIP
Pick the transport by where the audio starts. The session protocol is the same in each case. Only the audio path changes.
| Transport | Best for | Audio path |
|---|---|---|
| WebSocket | Servers, telephony bridges, custom pipelines | Base64 PCM16 audio inside JSON events over wss://api.openai.com/v1/realtime |
| WebRTC | Browsers and mobile apps | Opus audio over SRTP, events on a data channel named oai-events |
| SIP | Phone lines | Direct SIP trunk to OpenAI, no media bridge to build |
For WebRTC, never ship your standard API key to the client. Your backend mints a short-lived client secret with POST /v1/realtime/client_secrets. The secret expires after 10 to 7,200 seconds. The default is 600 seconds. The browser uses it to open the session, and the real key stays on your server.
How to Build a Voice AI Agent With the OpenAI Realtime API
These steps use the Python Agents SDK. The SDK manages the WebSocket session, the event loop, and tool calls for you.
- Set up the project. Use Python 3.10 or higher. Install the SDK with
pip install openai-agents. Set your key withexport OPENAI_API_KEY="your-key". - Define the agent. Create a
RealtimeAgentwith a name and short instructions. Keep the instructions conversational. Tell the model to answer briefly, in plain spoken language. - Configure the runner. Create a
RealtimeRunnerwith the starting agent. Set the model togpt-realtime-2.1. Usepcm16audio format. Pick a voice such asash. Turn onsemantic_vadfor turn detection, withinterrupt_responseset to true. Add transcription withgpt-4o-mini-transcribeif you want a text transcript alongside the audio. - Start the session. Call
runner.run()to get a session, then enter its context. The connection opens when you enter the context. Send a first message withsession.send_message(). For raw microphone audio, usesession.send_audio()with PCM16 chunks. - Handle audio events. Loop over the session events. Audio events carry the spoken reply in
event.audio.data. Play it or forward it to the caller. Theagent_endevent marks the end of one assistant turn. Theerrorevent carries failures. - Add a tool. Give the agent a function tool, such as an order lookup. The model calls it mid-turn when it needs real data. Your code runs the function and returns the result to the session. The model then continues speaking with the answer.
- Handle interruptions. Server-side voice activity detection fires when the caller starts talking over the agent. Stop playback at once. Then truncate the in-flight reply so the model knows how much audio was actually heard. The SDK surfaces these events for you. In raw WebSocket code, send a
conversation.item.truncateevent with the reply id and the milliseconds played. - Test the voice first. Try your instructions in the OpenAI Playground with the realtime model before you wire up code. Tune the greeting, the tone, and the tool descriptions there. Then copy the working instructions into your agent.
import asyncio
from agents.realtime import RealtimeAgent, RealtimeRunner
agent = RealtimeAgent(
name="Assistant",
instructions="You are a helpful voice assistant. Keep responses short and conversational.",
)
runner = RealtimeRunner(
starting_agent=agent,
config={
"model_settings": {
"model_name": "gpt-realtime-2.1",
"audio": {
"input": {
"format": "pcm16",
"transcription": {"model": "gpt-4o-mini-transcribe"},
"turn_detection": {
"type": "semantic_vad",
"interrupt_response": True,
},
},
"output": {"format": "pcm16", "voice": "ash"},
},
}
},
)
async def main() -> None:
session = await runner.run()
async with session:
await session.send_message("Say hello in one short sentence.")
async for event in session:
if event.type == "audio":
pass # Forward or play event.audio.data.
elif event.type == "agent_end":
break
elif event.type == "error":
print(f"Error: {event.error}")
if __name__ == "__main__":
asyncio.run(main())
What a Voice Agent Costs
The Realtime API bills by the token, not by the minute. Audio tokens cost far more than text tokens. Caller audio counts as one token per 100 milliseconds. The model's own audio counts as one token per 50 milliseconds. Context grows each turn, because earlier audio is re-sent as input on later turns.
| Model | Audio input | Cached audio input | Audio output |
|---|---|---|---|
| gpt-realtime-2.1 | $32 per million tokens | $0.40 per million tokens | $64 per million tokens |
| gpt-realtime-2.1-mini | $10 per million tokens | $0.30 per million tokens | $20 per million tokens |
Prompt caching is the biggest cost lever. Cached audio input bills at $0.40 per million tokens instead of $32. Keep prompts stable across turns so the cache hits. Check the live OpenAI pricing page before you budget a deployment, because rates change.
Common Mistakes to Avoid
- Never put your API key in browser JavaScript. Mint ephemeral client secrets on your backend.
- Do not write long, written-style instructions. Voice replies should be short and spoken.
- Do not ignore interruptions. If the agent keeps talking over the caller, the call feels broken.
- Do not let sessions run unbounded. Context accumulates every turn, and cost grows with it.
- Do not skip the greeting. Tell callers they are speaking with an automated voice agent.
- Do not hard-code the model name everywhere. Keep it in one config value so upgrades are easy.
Bottom Line
Start with the Agents SDK over WebSocket and gpt-realtime-2.1. Keep instructions short. Add one tool at a time. Test interruptions early, because they define how the agent feels. Watch cached input to control cost. That is a working voice agent in under a hundred lines of code.