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 in Python

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.

TransportBest forAudio path
WebSocketServers, telephony bridges, custom pipelinesBase64 PCM16 audio inside JSON events over wss://api.openai.com/v1/realtime
WebRTCBrowsers and mobile appsOpus audio over SRTP, events on a data channel named oai-events
SIPPhone linesDirect 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.

  1. Set up the project. Use Python 3.10 or higher. Install the SDK with pip install openai-agents. Set your key with export OPENAI_API_KEY="your-key".
  2. Define the agent. Create a RealtimeAgent with a name and short instructions. Keep the instructions conversational. Tell the model to answer briefly, in plain spoken language.
  3. Configure the runner. Create a RealtimeRunner with the starting agent. Set the model to gpt-realtime-2.1. Use pcm16 audio format. Pick a voice such as ash. Turn on semantic_vad for turn detection, with interrupt_response set to true. Add transcription with gpt-4o-mini-transcribe if you want a text transcript alongside the audio.
  4. 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 with session.send_message(). For raw microphone audio, use session.send_audio() with PCM16 chunks.
  5. 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. The agent_end event marks the end of one assistant turn. The error event carries failures.
  6. 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.
  7. 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.truncate event with the reply id and the milliseconds played.
  8. 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.

ModelAudio inputCached audio inputAudio 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

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.