Add browser WebRTC + server sideband support for realtime speech-to-speech

Merged
DO
4mo ago
+6705-172

Browser WebRTC for realtime speech-to-speech

Adds a browser / client WebRTC path to pydantic_ai.realtime. The browser exchanges audio directly with the provider over WebRTC — lowest latency, browser-grade media — while your server keeps the tools, conversation history, and API keys. Three planes:

  • Media (the audio): browser ↔ provider, peer-to-peer. Your server is never in the audio path.
  • Signaling (the one-time SDP offer/answer handshake): your server relays it, so the browser never holds a key.
  • Control (the agent + tool loop): your server attaches a sideband — a normal realtime control connection to the same call, identified by its call_id — over which the existing RealtimeSession runs your tools and builds history.

Built in the shared OpenAI-protocol layer, so OpenAI and Azure OpenAI both get it.

Usage

The browser creates an SDP offer and POSTs it to your server. Your server relays it with the agent-level answer_webrtc_offer — which resolves and bakes in the agent's instructions, tools, capabilities, and model settings through the same shared resolution path as session() — starts the sideband, and returns the SDP answer:

import asyncio

from pydantic_ai import Agent
from pydantic_ai.realtime import WebRTCSession
from pydantic_ai.realtime.openai import OpenAIRealtimeModel, OpenAIRealtimeModelSettings

agent = Agent(instructions='You are a helpful voice assistant.')

model = OpenAIRealtimeModel('gpt-realtime')
realtime = agent.realtime(model, model_settings=OpenAIRealtimeModelSettings(voice='marin'))

# POST endpoint the browser sends its SDP offer to:
async def offer(sdp_offer: str) -> str:
    answer = await realtime.answer_webrtc_offer(sdp_offer)  # agent config baked in
    # Attach the sideband before returning the answer, so the tools are live before the browser speaks.
    asyncio.create_task(run_sideband(answer.session))
    return answer.sdp  # relay back to the browser

async def run_sideband(call: WebRTCSession) -> None:
    async with realtime.session(provider_session=call) as session:
        async for event in session:
            ...  # transcripts, tool calls/results, turn boundaries — normal realtime events

The browser owns the audio; the server-side session runs the agent loop and records ordinary ModelMessage history (so you can still hand off to a text Agent.run(...) afterward).

A runnable FastAPI + browser demo is included under examples/pydantic_ai_examples/realtime_webrtc/ — it works against OpenAI (openai:gpt-realtime) and Azure OpenAI (WEBRTC_REALTIME_MODEL=azure:<deployment>), both verified live end to end.

Public API

  • AgentRealtime.answer_webrtc_offer(sdp_offer) -> WebRTCAnswer and AgentRealtime.create_client_secret(*, expires_after_seconds=None) -> RealtimeClientSecret (via agent.realtime(model, ...)) — resolve the bound agent configuration (dynamic instructions, toolsets, capabilities, merged settings) exactly as session() does, and relay/mint via the model.
  • RealtimeModel.answer_webrtc_offer(...) / RealtimeModel.create_client_secret(...) — the lower-level signaling mechanism the agent-level methods build on.
  • AgentRealtime.session(..., provider_session: RealtimeProviderSession | None = None) — attach the sideband to a negotiated call.
  • Artifacts in pydantic_ai.realtime: WebRTCSession (concrete) behind the RealtimeProviderSession protocol, WebRTCAnswer, RealtimeClientSecret.
  • AzureRealtimeModel(credential=...) — authenticate Azure signaling with a Microsoft Entra ID token instead of an API key.

Not included / out of scope

  • xAI and Gemini: both are WebSocket-only (no call_id sideband), so WebRTC does not apply to them. XaiRealtimeModel / GoogleRealtimeModel raise a clear error if asked to negotiate a WebRTC offer.
  • Azure Entra on the provider: this PR authenticates via the model; moving Entra credentials onto AzureProvider (so all Azure models get them) is handled alongside the Voice Live work (#6642).
  • This PR stacks on the base realtime feature (#6324) and only contains the WebRTC additions.