litellm/tests/e2e/llm_translation/realtime/realtime_client.py
Mateo Wang 4c8b90945f
fix(realtime)!: send the Gemini Live setup at the first content so session.update settings apply (#39864)
* fix(realtime): send Gemini Live setup on the client's first message so session.update modalities apply

Gemini and Vertex AI Live accept exactly one setup per session, and the proxy sent its
default audio setup at connect, so a client's session.update (GA output_modalities or
beta modalities) was dropped and every answer came back as audio. The setup now goes
out on the client's first message: a session.update becomes that setup, anything else
gets the model default. Bedrock Nova Sonic keeps its connect-time setup through a
provider hook. Text setups label deltas response.output_text.delta, and downgrading
TEXT to AUDIO on an audio-only model logs a warning

* fix(realtime): keep one Gemini Live response modality and skip the "inf" token limit in the setup

* fix(realtime): merge every session.update sent before the first content frame into the Gemini Live setup

Gemini and Vertex Live accept one setup per connection, so the bridge used to
turn only the first session.update into that setup and drop the rest without
telling the client. Now every session.update that arrives before the first
content frame is held, deep-merged (later values win per field), acknowledged
with a session.updated built from the setup it would produce, and the merged
session becomes the one setup sent with the first conversation item, audio
frame, or tool result. The session events also surface the systemInstruction
text as instructions, which the old string check never matched because the
setup carries it as a Content object.

* fix(realtime): cap the session.update merge depth so the recursive detector accepts it

_merge_session_fields recurses once per nested mapping level, so CI's
recursive_detector flagged it. Bound the descent at eight levels (the OpenAI
session object nests four deep at most), replace anything deeper wholesale
with the later session.update's value, and list the helper with the other
depth-capped functions the detector allows.

* fix(gemini-live): accept a string output modality and drop values Live cannot produce

A bare string output_modalities is read as a one-element list and modality values Gemini Live cannot produce are dropped with a warning instead of reaching the backend, so a malformed session.update no longer costs the session. Transcription guardrails now fold their VAD disable into the first held session.update only, so the merged setup carries it exactly once.

* fix(gemini realtime): answer an error for session updates Gemini Live cannot apply

An output modality the model cannot produce, or a session.update sent after the
first content, now gets an invalid_request_error event instead of a silent swap
or drop, unless drop_params is set. The synthetic session.created reports the
model's default modality, setupComplete no longer adds an extra session.updated,
and merging nested session updates is linear in their size

* fix(gemini realtime): send the setup before guardrail blocks and idle deadlines, mark push-to-talk turns

A pre_call guardrail blocking the first typed message now goes out after the
setup, so Gemini and Vertex no longer close the session with 1007.

Push-to-talk sessions (turn_detection null or create_response false) wrap each
audio turn in empty activityStart and activityEnd messages, which Gemini needs
when automatic activity detection is off.

A session with no content after 60 seconds sends its setup, since Vertex
refuses a setup 300 seconds after connect. Held session.update frames past
10 MB answer session_update_too_large, and deferred mode now errors on a
second session.update unless drop_params is set.

* fix(realtime): ack unchanged Gemini Live session.update resends and honor null turn_detection

An update that leaves the applied setup unchanged now gets session.updated
instead of session_update_not_applied, so clients that resend their session
with the first response keep working. Deferred setup mode merges held updates
like the default mode, turn_detection null turns Gemini's activity detection
off, drop_params drops a voice outside the documented Live voices, and the
lazy setup deadline moves to 240 seconds

* fix(realtime): keep Vertex activity detection off for null turn_detection and set up deferred sessions before text content

* fix(realtime): refuse unscreenable Gemini audio, send held setup after buffered audio, reject unknown Vertex voices

A realtime_input_transcription guardrail cannot screen Gemini Live audio before the answer starts, so audio input under one is refused with an audio_input_not_screenable error instead of reaching the model. In deferred setup mode a session.update that follows buffered audio is sent as setup at once. Only conversation content triggers the setup, so control events no longer lock in a default one. Vertex rejects an undocumented voice on the session.update, or drops it with drop_params, while Google AI Studio forwards any name.

* fix(realtime): hold first content so a following session.update joins the Gemini setup

Convert flat realtime tool schemas through Gemini's schema builder, and collapse a text and audio pair to what the model can produce on text-only models too

* fix(realtime): check AI Studio Live voices like Vertex

* fix(realtime): forward any voice to AI Studio Live models that accept it

* fix(realtime): map OpenAI TTS voices before the Live voice check, keep outage spend rows, share the playground session config

The Live voice gate now judges the Gemini voice an OpenAI TTS name maps to, so fable and onyx reach Vertex as Umbriel and Orus again. An upstream close before the held setup was sent is logged as a session, not a refusal. The playground sends one server_vad session config for typed and voice turns, and the e2e, integration, and dashboard tests follow lazy setup.

* fix(realtime): take the lazy setup clock as a dependency so its tests run on a stepped clock

The deadline and grace tests waited on real 50 ms timers, and the merge cost
check compared wall-clock runs. The session now reads an injected clock,
time.monotonic by default, the two tests step it, and the merge cost check
moves to the CodSpeed benchmarks. The Nova Sonic style handler test passes
the backend through wrap_backend, which main added after the test was written
2026-10-30 01:31:39 -07:00

425 lines
13 KiB
Python

"""Client for realtime e2e tests over the proxy's /v1/realtime websocket.
The proxy normalizes every provider's realtime stream into the OpenAI GA event
schema toward the client, so one GA-speaking websocket client validates every
provider and only the model alias changes. Every other e2e suite is HTTP-only;
this is the one suite that opens a websocket, using websockets.sync so it stays
synchronous like the rest of tests/e2e. Sent and received events are pydantic
models, matching the suite's no-raw-dicts rule.
"""
from __future__ import annotations
import time
from collections.abc import Generator, Iterator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from itertools import chain, repeat
from typing import Final, TypeVar
from urllib.parse import urlencode
from pydantic import BaseModel, ConfigDict
from websockets.sync.client import connect
from websockets.sync.connection import Connection
from e2e_config import unique_marker, ws_base_url
from e2e_metadata import step
from proxy_client import ProxyClient
from models import LiteLLMParamsBody
_M = TypeVar("_M", bound=BaseModel)
def realtime_ws_url(model: str) -> str:
return f"{ws_base_url()}/v1/realtime?{urlencode({'model': model})}"
@dataclass(frozen=True, slots=True)
class RealtimeProvider:
"""A realtime provider the suite exercises. `litellm_params` is the deployment
the suite registers through /model/new (the gateway resolves the os.environ/*
credential refs), so the suite is self-contained and never depends on a static
gateway model_list. Every provider here is provisioned and asserted: per
tests/e2e/AGENTS.md the suite never skips a provider, so a provider whose
credentials or upstream realtime model are missing on the gateway is a hard
failure, not a skip."""
id: str
alias: str
litellm_params: LiteLLMParamsBody
modalities: tuple[str, ...] = ("text",)
PROVIDERS = (
RealtimeProvider(
"openai",
"openai-realtime",
LiteLLMParamsBody(
model="openai/gpt-realtime-2",
api_key="os.environ/OPENAI_API_KEY",
),
),
RealtimeProvider(
"azure",
"azure-realtime",
LiteLLMParamsBody(
model="azure/gpt-realtime",
api_key="os.environ/AZURE_API_KEY",
api_version="2025-08-28",
realtime_protocol="GA",
),
),
RealtimeProvider(
"gemini",
"gemini-realtime",
LiteLLMParamsBody(
model="gemini/gemini-3.1-flash-live-preview",
api_key="os.environ/GEMINI_API_KEY",
),
modalities=("audio",),
),
RealtimeProvider(
"vertex_ai",
"vertex-realtime",
LiteLLMParamsBody(
model="vertex_ai/gemini-live-2.5-flash-native-audio",
vertex_location="us-central1",
vertex_credentials="os.environ/VERTEXAI_CREDENTIALS",
),
modalities=("audio",),
),
RealtimeProvider(
"bedrock",
"bedrock-realtime",
LiteLLMParamsBody(
model="bedrock/amazon.nova-2-sonic-v1:0",
aws_access_key_id="os.environ/AWS_ACCESS_KEY_ID",
aws_secret_access_key="os.environ/AWS_SECRET_ACCESS_KEY",
aws_region_name="os.environ/AWS_REGION",
),
),
# RealtimeProvider(
# "xai",
# "xai-realtime",
# LiteLLMParamsBody(
# model="xai/grok-4-1-fast",
# api_key="os.environ/XAI_API_KEY",
# ),
# ), # TODO: Enable once xai Grok Voice realtime is passing end-to-end here
)
def realtime_model(provider: RealtimeProvider, provisioned: Mapping[str, str]) -> str:
"""Return the provisioned deployment name for this provider. Every provider in
PROVIDERS is provisioned at session start, so a missing entry is a harness bug,
never an environment skip - the suite hard-fails instead (see tests/e2e/AGENTS.md)."""
model = provisioned.get(provider.id)
assert model is not None, (
f"{provider.id} was not provisioned; the realtime_models fixture is broken"
)
return model
# ---- sent events -------------------------------------------------------
class JsonSchemaProperty(BaseModel):
type: str
class JsonSchema(BaseModel):
type: str = "object"
properties: dict[str, JsonSchemaProperty]
required: list[str]
class FunctionTool(BaseModel):
type: str = "function"
name: str
description: str
parameters: JsonSchema
class SessionConfig(BaseModel):
modalities: list[str] = ["text"]
instructions: str | None = None
tools: list[FunctionTool] | None = None
tool_choice: str | None = None
class SessionUpdate(BaseModel):
type: str = "session.update"
session: SessionConfig
class InputTextContent(BaseModel):
type: str = "input_text"
text: str
class MessageItem(BaseModel):
type: str = "message"
role: str = "user"
content: list[InputTextContent]
class FunctionCallOutputItem(BaseModel):
type: str = "function_call_output"
call_id: str
output: str
class ConversationItemCreate(BaseModel):
type: str = "conversation.item.create"
item: MessageItem | FunctionCallOutputItem
class ResponseCreate(BaseModel):
type: str = "response.create"
class InputAudioBufferAppend(BaseModel):
type: str = "input_audio_buffer.append"
audio: str
def user_message(text: str) -> ConversationItemCreate:
return ConversationItemCreate(
item=MessageItem(content=[InputTextContent(text=text)])
)
# ---- received events ---------------------------------------------------
class ServerEnvelope(BaseModel):
model_config = ConfigDict(extra="allow")
type: str = ""
class DeltaEvent(BaseModel):
type: str
delta: str = ""
class FunctionCallArgumentsDone(BaseModel):
type: str
call_id: str
arguments: str
class ContentPart(BaseModel):
model_config = ConfigDict(extra="allow")
text: str | None = None
transcript: str | None = None
class OutputItem(BaseModel):
model_config = ConfigDict(extra="allow")
type: str | None = None
name: str | None = None
call_id: str | None = None
content: list[ContentPart] | None = None
class OutputItemDone(BaseModel):
type: str
item: OutputItem
class ResponsePayload(BaseModel):
model_config = ConfigDict(extra="allow")
usage: dict[str, object] | None = None
output: list[OutputItem] | None = None
class TextDone(BaseModel):
type: str
response_id: str
text: str
class ResponseDone(BaseModel):
type: str
response: ResponsePayload
@dataclass(frozen=True, slots=True)
class ReceivedEvent:
type: str
payload: str
def events_of_type(
events: tuple[ReceivedEvent, ...], event_type: str
) -> tuple[ReceivedEvent, ...]:
return tuple(e for e in events if e.type == event_type)
def parse_last(
events: tuple[ReceivedEvent, ...], event_type: str, model: type[_M]
) -> _M | None:
matches = events_of_type(events, event_type)
return model.model_validate_json(matches[-1].payload) if matches else None
_TEXT_DELTA_TYPES = (
# beta protocol (OpenAI-Beta: realtime=v1)
"response.text.delta",
"response.audio_transcript.delta",
# GA protocol (default toward the proxy)
"response.output_text.delta",
"response.output_audio_transcript.delta",
)
def _text_from_response_done(events: tuple[ReceivedEvent, ...]) -> str:
done = parse_last(events, "response.done", ResponseDone)
if done is None or not done.response.output:
return ""
parts: list[str] = []
for item in done.response.output:
if item.type != "message":
continue
for content in item.content or []:
if content.text:
parts.append(content.text)
elif content.transcript:
parts.append(content.transcript)
return "".join(parts)
def transcript(events: tuple[ReceivedEvent, ...]) -> str:
for delta_type in _TEXT_DELTA_TYPES:
text = "".join(
DeltaEvent.model_validate_json(e.payload).delta
for e in events_of_type(events, delta_type)
)
if text:
return text
return _text_from_response_done(events)
def function_call_item(events: tuple[ReceivedEvent, ...]) -> OutputItem | None:
for event in events_of_type(events, "response.output_item.done"):
item = OutputItemDone.model_validate_json(event.payload).item
if item.type == "function_call":
return item
return None
# ---- session + client --------------------------------------------------
def as_text(message: str | bytes) -> str:
return message.decode("utf-8") if isinstance(message, bytes) else message
@dataclass(frozen=True, slots=True)
class RealtimeSession:
connection: Connection
@step("Send the realtime event {event.type} over the websocket")
def send(self, event: SessionUpdate | ConversationItemCreate | ResponseCreate | InputAudioBufferAppend) -> None:
self.connection.send(event.model_dump_json(by_alias=True, exclude_none=True))
@step("Wait for a {stop_type} event on the realtime websocket")
def collect_until(
self, stop_type: str, *, timeout: float
) -> tuple[ReceivedEvent, ...]:
deadline = time.monotonic() + timeout
collected: list[ReceivedEvent] = []
while time.monotonic() < deadline:
try:
text = as_text(
self.connection.recv(timeout=deadline - time.monotonic())
)
except TimeoutError:
break
event = ReceivedEvent(
type=ServerEnvelope.model_validate_json(text).type, payload=text
)
collected.append(event)
if event.type == stop_type:
return tuple(collected)
raise TimeoutError(
f"no {stop_type!r} within {timeout}s; got {[e.type for e in collected]}"
)
@step("Stream the spoken question as mic chunks, then silence until the turn goes idle")
def stream_and_collect(
self,
chunks: Sequence[InputAudioBufferAppend],
*,
tail: InputAudioBufferAppend,
interval: float,
idle: float,
timeout: float,
) -> tuple[ReceivedEvent, ...]:
"""Send `chunks`, then `tail` every `interval` seconds like a live mic, until
no event arrives for `idle` seconds or `timeout` elapses."""
return tuple(self._live_mic_events(chunks, tail=tail, interval=interval, idle=idle, timeout=timeout))
def _live_mic_events(
self,
chunks: Sequence[InputAudioBufferAppend],
*,
tail: InputAudioBufferAppend,
interval: float,
idle: float,
timeout: float,
) -> Iterator[ReceivedEvent]:
start: Final = time.monotonic()
last_event = start # rebind-ok: the idle timer restarts at every received event
for frame in chain(chunks, repeat(tail)):
if (now := time.monotonic()) - start >= timeout or now - last_event >= idle:
return
self.send(frame)
for event in self._events_until(now + interval):
last_event = time.monotonic()
yield event
def _events_until(self, deadline: float) -> Iterator[ReceivedEvent]:
while (remaining := deadline - time.monotonic()) > 0 and (text := self._recv_text(remaining)) is not None:
yield ReceivedEvent(type=ServerEnvelope.model_validate_json(text).type, payload=text)
def _recv_text(self, timeout: float) -> str | None:
try:
return as_text(self.connection.recv(timeout=timeout))
except TimeoutError:
return None
@dataclass(frozen=True, slots=True)
class RealtimeClient:
proxy: ProxyClient
@step("Add a realtime deployment that calls {provider.litellm_params.model}")
def provision(self, provider: RealtimeProvider) -> tuple[str, str]:
"""Register this provider's realtime deployment through /model/new and return
(model_name, model_id). The name is marker-unique so it never collides with a
same-named deployment already on the shared proxy, and mode=realtime makes it
show up as a realtime model on /model/info. add_deployment runs synchronously,
so the deployment is connectable as soon as this returns."""
model_name = f"{provider.alias}-{unique_marker()}"
model_id = self.proxy.create_model(
model_name, provider.litellm_params, mode="realtime"
)
return model_name, model_id
@step("Open a /v1/realtime websocket session to {model}")
@contextmanager
def connect(
self, *, key: str, model: str, timeout: float = 15.0
) -> Generator[RealtimeSession, None, None]:
with connect(
realtime_ws_url(model),
additional_headers={"Authorization": f"Bearer {key}"},
open_timeout=timeout,
) as connection:
yield RealtimeSession(connection=connection)
def build_client(proxy: ProxyClient) -> RealtimeClient:
return RealtimeClient(proxy=proxy)