Add realtime speech-to-speech support

Closed
DE
5mo ago
+9101-12

Adds native support for realtime, bidirectional speech-to-speech (and live video) models behind a
small provider-agnostic abstraction that lives alongside the request-response Model interface, with
two providers out of the box — OpenAI Realtime and Gemini Live.

Builds on the approach explored in #4375 (closed), incorporating its review feedback and migrating to
the GA OpenAI Realtime API (the beta surface is no longer supported).

What's added

  • pydantic_ai.realtime — provider-facing ABCs and the session:
    • RealtimeModel (connect() opens a connection) and RealtimeConnection (send() content in,
      iterate events out) — a sans-IO-style boundary so adding a provider is one file.
    • RealtimeSession — wraps a connection and runs the tool loop automatically: intercepts each
      ToolCall, executes it, sends the ToolResult back, and emits ToolCallStarted /
      ToolCallCompleted. Tools listed in background_tools run concurrently (the model keeps
      talking while they work) and are multiplexed through one queue so a completion never stalls the
      stream; others run synchronously. A ToolResult is always returned, so the model never stalls.
      Tracks cumulative usage (a RunUsage) across the session.
    • Typed inputs — AudioInput, TextInput, ImageInput (a video frame), ToolResult, plus the
      manual turn-taking verbs CommitAudio, ClearAudio, CreateResponse, CancelResponse,
      TruncateOutput.
    • Typed events — AudioDelta, Transcript, InputTranscript (streamed), ToolCall,
      TurnComplete, SpeechStarted/SpeechStopped, Usage, RateLimits, Reconnected,
      SessionError (with type/code/recoverable), plus the session-level ToolCallStarted /
      ToolCallCompleted.
  • Agent.realtime_session(model, *, deps, model_settings, instructions, background_tools) — the
    high-level entry point; resolves the agent's per-run toolsets and instructions into a session and
    forwards instrumentation.
  • OpenAI provider (pydantic_ai.realtime.openai) over websockets: GA /v1/realtime, PCM16 @
    24 kHz, function calling, input transcription, and barge-in. Configurable turn-taking
    (ServerVAD / SemanticVAD / None for push-to-talk), input noise reduction, output modalities,
    and output speed; token usage and rate-limit snapshots; and an optional ReconnectPolicy that
    re-dials with backoff. It defers response.create while a response is active (so a background-tool
    result landing mid-answer is still announced, not dropped) and does not replay it after a barge-in.
  • Gemini provider (pydantic_ai.realtime.google) over the google-genai SDK: PCM16 @ 16 kHz
    input (24 kHz output), one response modality per session, and native live video frames (each
    ImageInput is sent as a video blob) — enabling "show me this" camera interactions. A broad,
    optional configuration surface: voice / language_code / multi_speaker, affective_dialog
    and proactive_audio (native-audio), AutomaticVAD (disabled + start/end sensitivity + padding/
    silence), activity_handling, turn_coverage, transcription language hints, ContextCompression
    for long sessions, transparent reconnect via session resumption (enable_session_resumption +
    ReconnectPolicy, which restores server state), and a config_overrides escape hatch. Generation
    parameters (temperature, top_p, top_k, max_tokens, seed, google_thinking_config,
    google_video_resolution) are read from model_settings, consistent with the non-realtime Google
    model. Authenticates with an API key or Vertex AI via Application Default Credentials
    (vertexai=True), useful where org policy disallows API keys.
  • Observability — when the agent is instrumented (logfire.instrument_pydantic_ai()), a session
    emits an OpenTelemetry span tree: the realtime <model> session (cumulative usage + transcript as
    gen_ai.input.messages when include_content) with an execute_tool span per tool call
    (including any delegated text-agent run) nested underneath.
  • Optional dependency groups — realtime (websockets>=14.0) for OpenAI; the Gemini provider
    uses google-genai, already a pydantic-ai dependency (google group).

Design notes

  • Separate from Model on purpose. Realtime is a long-lived, full-duplex session, not
    request-response — so it gets its own ABCs, while reusing ToolDefinition and ModelSettings.
  • Structured output is delegated, not faked. Realtime models don't support structured output, so
    the recommended pattern is to expose a single tool that hands off to a normal Agent with an
    output_type. The finance example demonstrates this end-to-end.
  • Provider-agnostic. Everything above the provider (RealtimeSession, Agent.realtime_session,
    instrumentation) depends only on the ABCs and shared types; a new provider (Nova Sonic, ...) is a
    connect() + event-mapping module. Provider-specific knobs (VAD types, reconnect, voice config)
    live in the provider module, with names mirrored across providers where the concept is shared.

Docs & examples

  • Guide: docs/realtime.md (quickstart, configuration incl. a Gemini config matrix, turn-taking &
    barge-in, push-to-talk, images/live vision, usage & cost, Logfire, reconnect, delegation); API
    reference: docs/api/realtime.md. Both added to nav.
  • Two runnable examples (each with its own docs page):
    • realtime_finance/ — a voice finance assistant where the realtime model delegates to a
      supervisor agent whose typed Pydantic tool outputs render as cards, showing both sync and
      background ("subagent") dispatch. A UI settings panel switches provider/model/voice and
      provider-specific tuning.
    • realtime_camera/ — a "talk and show your camera" assistant on Gemini Live, streaming mic audio
      • ~1 fps frames, with a Watch toggle for proactive narration. Runs on localhost; documents
        exposing it to a phone over HTTPS via a Cloudflare quick tunnel, and Vertex AI auth.

Tests

  • Network-free tests under tests/realtime/ (fake connection/model, fake websocket, fake google-genai
    session); 100% coverage of the pydantic_ai.realtime module. Optional-dependency and
    instrumentation imports are guarded so the slim/evals CI jobs collect cleanly. Pyright/mypy/ruff clean.

  • Closes #1447

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • PR title is fit for the release changelog.

Context: Found while building project at Vstorm · github.com/vstorm-co.