Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/openai/openai-cookbook/llms.txt

Use this file to discover all available pages before exploring further.

Text-based agents are powerful, but voice unlocks an entirely different class of experience: hands-free interfaces, accessibility tools, customer service bots that feel natural to talk to, and telephony systems that don’t force users to navigate menus. The OpenAI Realtime API makes this accessible by handling the hardest parts — audio streaming, speech recognition, turn detection, and speech synthesis — so you can focus on the agent behavior itself. This guide covers the Realtime API’s core features, shows how to connect it to the Agents SDK, and walks through the patterns you’ll need for production voice agents.

What the Realtime API provides

The Realtime API is a WebSocket-based API that streams audio in both directions simultaneously. Unlike a pipeline that chains Whisper → GPT-4o → TTS, the Realtime API uses a single model that accepts and produces audio natively, which eliminates the latency introduced by converting between modalities at each step.

Real-time audio streaming

Audio is streamed in chunks rather than sent as a complete file. Responses begin before the full input has been processed.

Voice activity detection

The API detects when the user stops speaking and automatically triggers a response, removing the need to manage push-to-talk logic.

Interruption handling

If the user speaks while the model is responding, the model stops mid-sentence and yields to the new input — matching natural conversation patterns.

Context management

The session maintains conversation history across turns, and the truncation parameter automatically manages context size to preserve cache efficiency.

Creating a Realtime session

A Realtime session captures your configuration: the model, the voice, the system instructions, and audio format preferences. Create one with the OpenAI Python SDK:
from openai import OpenAI

client = OpenAI()

# Create a Realtime session
session = client.beta.realtime.sessions.create(
    model="gpt-4o-realtime-preview",
    voice="alloy",
    instructions="You are a helpful voice assistant."
)
The sessions.create call returns a short-lived session token. Use this token to open the WebSocket connection from your client application. Do not expose your full API key to frontend code.

Available voices

Six voices are available. Each has a distinct character suited to different contexts:

alloy

Neutral and balanced. A good default for general-purpose assistants.

echo

Deep and measured. Works well for authoritative or informational content.

shimmer

Warm and approachable. Suited to consumer-facing and healthcare contexts.

ash

Crisp and professional. A strong choice for enterprise and productivity apps.

coral

Bright and conversational. Natural fit for customer service interactions.

sage

Calm and deliberate. Effective for educational or coaching scenarios.

Audio formats

The Realtime API supports the following audio formats for both input and output:
FormatDescription
pcm16Raw 16-bit PCM at 24 kHz, mono. Lowest latency; no decoding overhead.
g711_ulaw8 kHz μ-law PCM. Standard for telephony (PSTN, SIP).
g711_alaw8 kHz A-law PCM. Telephony standard common in Europe and Asia.
For web and mobile applications, pcm16 provides the best quality. For telephony integrations, use the appropriate G.711 variant to avoid transcoding.

Connecting voice to the Agents SDK

The Agents SDK’s voice extension lets you run any agent graph through a voice pipeline with minimal changes. Install the voice extra:
pip install "openai-agents[voice]"
Then wrap your existing agent workflow in a VoicePipeline:
import asyncio
from agents import Agent, function_tool
from agents.voice import VoicePipeline, SingleAgentVoiceWorkflow

@function_tool
def get_account_balance(user_id: str) -> str:
    """Return the account balance for the given user ID."""
    # Replace with a real database lookup
    return f"Your balance is $142.50."

account_agent = Agent(
    name="Account Agent",
    instructions=(
        "You are a helpful account assistant. "
        "Answer questions about balances and recent transactions."
    ),
    tools=[get_account_balance]
)

async def run_voice_agent():
    pipeline = VoicePipeline(
        workflow=SingleAgentVoiceWorkflow(account_agent)
    )
    # pipeline.run() streams audio I/O; connect it to your audio device
    await pipeline.run()

asyncio.run(run_voice_agent())
The pipeline handles the full lifecycle: capturing microphone audio, sending it to the Realtime API, receiving the audio response, and playing it back through the speakers.

Building a multi-agent voice assistant

The voice pipeline composes with the orchestrator pattern. You can build a triage agent that routes voice requests to specialist agents — and the user experiences it as a single coherent conversation:
from agents import Agent, WebSearchTool, FileSearchTool, function_tool, set_default_openai_key
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
from agents.voice import VoicePipeline, SingleAgentVoiceWorkflow

set_default_openai_key("YOUR_API_KEY")

search_agent = Agent(
    name="Search Agent",
    instructions=prompt_with_handoff_instructions(
        "Answer real-time questions using web search."
    ),
    tools=[WebSearchTool()]
)

knowledge_agent = Agent(
    name="Knowledge Agent",
    instructions=prompt_with_handoff_instructions(
        "Answer questions about our product catalogue using file search."
    ),
    tools=[FileSearchTool(vector_store_ids=["vs_your_store_id"])]
)

@function_tool
def get_account_info(user_id: str) -> dict:
    """Return account information for the given user."""
    return {"balance": "$142.50", "tier": "Pro", "user_id": user_id}

account_agent = Agent(
    name="Account Agent",
    instructions=prompt_with_handoff_instructions(
        "Help users with account information and billing questions."
    ),
    tools=[get_account_info]
)

triage_agent = Agent(
    name="Triage Agent",
    instructions=prompt_with_handoff_instructions(
        "Greet the user and route their request to the most appropriate specialist agent."
    ),
    handoffs=[search_agent, knowledge_agent, account_agent]
)
Use prompt_with_handoff_instructions on every agent that participates in handoffs. It injects the necessary context for the agent to understand when and how to transfer the conversation.

Setting up the voice pipeline end to end

1

Install dependencies

pip install openai "openai-agents[voice]" sounddevice numpy
2

Define your agent graph

Create your agents, attach tools, and configure handoffs as you would for a text-based workflow. The voice layer wraps any existing agent graph.
3

Create the pipeline

Wrap your entry-point agent in a VoicePipeline using SingleAgentVoiceWorkflow or a custom workflow class for more control over the session lifecycle.
4

Connect audio I/O

Pass an audio input source (microphone stream) and audio output sink (speakers or buffer) to the pipeline. The SDK handles VAD, chunking, and playback timing.
5

Run and iterate

Start the pipeline with await pipeline.run(). Use tracing in the OpenAI dashboard to review turn boundaries, handoff decisions, and tool calls.

Context and long conversations

Voice conversations can run long. The Realtime API supports a 32k token context window, but quality can degrade as the context fills up. Two strategies help:
Set the truncation parameter in your session configuration. The API automatically compresses older context to stay within the window while preserving recent turns and cache efficiency:
session = client.beta.realtime.sessions.create(
    model="gpt-4o-realtime-preview",
    voice="alloy",
    instructions="You are a helpful voice assistant.",
    # truncation="auto"  # parameter available in GA release
)

Use cases

Customer service bots

Route inbound calls to billing, technical support, or account management specialists. Handoffs happen mid-conversation without the user being transferred to a different system.

Voice interfaces for apps

Add a voice entry point to any existing in-app workflow. Users speak naturally; the triage agent routes to the right specialist in the background.

Telephony integration

Use G.711 audio formats to connect voice agents to PSTN or SIP infrastructure. The model handles the conversation; your telephony layer handles routing and recording.

Accessibility tools

Serve users who find text interfaces difficult by providing a natural voice alternative to any capability your agent graph already supports.

Further reading

Build docs developers (and LLMs) love