Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(gemini-live): forward audio buffer commit and correct Vertex PCM rate (#29946)

Sameer Kankutec30297e98a99
diff --git a/litellm/litellm_core_utils/realtime_streaming.py b/litellm/litellm_core_utils/realtime_streaming.py
index 4b7f0e22198..0d5d4a2086c 100644
--- a/litellm/litellm_core_utils/realtime_streaming.py
+++ b/litellm/litellm_core_utils/realtime_streaming.py
@@ -111,8 +111,12 @@ class RealTimeStreaming:
"input_audio_buffer.append",
"input_audio_buffer.commit",
"input_audio_buffer.clear",
+ "input_audio_buffer.end",
]
)
+ _CLIENT_AUDIO_BUFFER_COMMIT_TYPES = frozenset(
+ ["input_audio_buffer.commit", "input_audio_buffer.end"]
+ )
_AUDIO_FORMAT_MAP: Dict[str, Dict[str, Any]] = {
"pcm16": {"type": "audio/pcm", "rate": 24000},
"g711_ulaw": {"type": "audio/G711-ulaw", "rate": 8000},
@@ -308,6 +312,48 @@ class RealTimeStreaming:
return False
return not self.provider_config.requires_session_configuration()
+ @staticmethod
+ def _collapse_buffered_audio_messages(messages: List[str]) -> List[str]:
+ """Apply ``input_audio_buffer.clear`` semantics before replaying buffered frames.
+
+ During deferred Gemini Live setup, ``clear`` is buffered alongside appends.
+ On flush each append becomes a provider ``realtimeInput``; ``clear`` must
+ drop preceding uncommitted appends instead of being forwarded as a no-op.
+ """
+ collapsed: List[str] = []
+ pending_appends: List[str] = []
+
+ for message in messages:
+ try:
+ msg_type = json.loads(message).get("type")
+ except (json.JSONDecodeError, TypeError):
+ collapsed.extend(pending_appends)
+ pending_appends = []
+ collapsed.append(message)
+ continue
+
+ if msg_type == "input_audio_buffer.append":
+ pending_appends.append(message)
+ elif msg_type == "input_audio_buffer.clear":
+ pending_appends = []
+ elif msg_type in RealTimeStreaming._CLIENT_AUDIO_BUFFER_COMMIT_TYPES:
+ collapsed.extend(pending_appends)
+ pending_appends = []
+ collapsed.append(message)
+ else:
+ collapsed.extend(pending_appends)
+ pending_appends = []
+ collapsed.append(message)
+
+ collapsed.extend(pending_appends)
+ return collapsed
+
+ def _sync_pending_messages_byte_total(self) -> None:
+ self._pending_messages_byte_total = sum(
+ len(message.encode("utf-8"))
+ for message in self._pending_messages_until_setup
+ )
+
def _should_buffer_client_message_until_setup(self, message: str) -> bool:
if not self._uses_deferred_backend_setup():
return False
@@ -323,6 +369,18 @@ class RealTimeStreaming:
return msg_obj.get("type") in RealTimeStreaming._CLIENT_AUDIO_BUFFER_TYPES
def _buffer_pending_message_until_setup(self, message: str) -> None:
+ try:
+ msg_type = json.loads(message).get("type")
+ except (json.JSONDecodeError, TypeError):
+ msg_type = None
+
+ if msg_type == "input_audio_buffer.clear":
+ self._pending_messages_until_setup = self._collapse_buffered_audio_messages(
+ self._pending_messages_until_setup + [message]
+ )
+ self._sync_pending_messages_byte_total()
+ return
+
msg_bytes = len(message.encode("utf-8"))
if (
len(self._pending_messages_until_setup)
@@ -340,7 +398,9 @@ class RealTimeStreaming:
)
async def _flush_pending_messages_until_setup(self) -> bool:
- pending = self._pending_messages_until_setup
+ pending = self._collapse_buffered_audio_messages(
+ self._pending_messages_until_setup
+ )
self._pending_messages_until_setup = []
self._pending_messages_byte_total = 0
for idx, message in enumerate(pending):
@@ -425,16 +485,13 @@ class RealTimeStreaming:
if sent:
self._guardrail_turn_detection_update_sent = True
- def _has_realtime_guardrails(self) -> bool:
- """Return True if any callback is registered for realtime guardrail event types."""
+ def _has_realtime_guardrails_for_event_hooks(
+ self,
+ event_hooks: List[Any],
+ ) -> bool:
+ """Return True if any callback would run for one of ``event_hooks``."""
from litellm.integrations.custom_guardrail import CustomGuardrail
- from litellm.types.guardrails import GuardrailEventHooks
- _realtime_event_types = [
- GuardrailEventHooks.realtime_input_transcription,
- GuardrailEventHooks.pre_call,
- GuardrailEventHooks.post_call,
- ]
return any(
isinstance(cb, CustomGuardrail)
and any(
@@ -442,31 +499,45 @@ class RealTimeStreaming:
data=self.request_data,
event_type=et,
)
- for et in _realtime_event_types
+ for et in event_hooks
)
for cb in litellm.callbacks
)
- def _has_audio_transcription_guardrails(self) -> bool:
- """Return True if any callback needs to run on audio transcriptions (VAD path).
+ def _has_realtime_guardrails(self) -> bool:
+ """Return True if any callback is registered for realtime guardrail event types."""
+ from litellm.types.guardrails import GuardrailEventHooks
- When this returns True, we inject a session.update to disable the LLM's
- auto-response so the guardrail can gate it first.
+ return self._has_realtime_guardrails_for_event_hooks(
+ [
+ GuardrailEventHooks.realtime_input_transcription,
+ GuardrailEventHooks.pre_call,
+ GuardrailEventHooks.post_call,
+ ]
+ )
- Must match the same hook criteria as run_realtime_guardrails() so that
- any guardrail that would actually check the transcript also disables
- auto-response before the transcript arrives.
+ def _has_audio_transcription_guardrails(self) -> bool:
+ """Return True when a guardrail is configured for the audio/VAD transcript path.
+
+ Only ``realtime_input_transcription`` hooks disable ``server_vad`` auto-response.
+ ``pre_call`` / ``post_call`` guardrails (e.g. Model Armor on chat completions)
+ must not override ``turn_detection.create_response`` on realtime sessions.
"""
- return self._has_realtime_guardrails()
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ return self._has_realtime_guardrails_for_event_hooks(
+ [GuardrailEventHooks.realtime_input_transcription]
+ )
async def run_realtime_guardrails(
self,
transcript: str,
item_id: Optional[str] = None,
pre_block_backend_message: Optional[str] = None,
+ event_hooks: Optional[List[Any]] = None,
) -> bool:
"""
- Run registered guardrails on a completed speech transcription.
+ Run registered guardrails on realtime text (transcript, user message, tool output).
Returns True if blocked (synthetic warning already sent to client).
Returns False if clean (caller should send response.create to the backend).
@@ -477,15 +548,17 @@ class RealTimeStreaming:
specific message to be sent first — e.g. Gemini Live requires a
matching ``toolResponse`` immediately after a ``toolCall`` before any
other client messages can be accepted.
+
+ ``event_hooks`` selects which guardrail modes to evaluate. Audio/VAD
+ transcript completion uses ``realtime_input_transcription`` only;
+ typed user messages and tool outputs use ``pre_call``.
"""
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.types.guardrails import GuardrailEventHooks
- _realtime_event_types = [
- GuardrailEventHooks.realtime_input_transcription,
- GuardrailEventHooks.pre_call,
- GuardrailEventHooks.post_call,
- ]
+ if event_hooks is None:
+ event_hooks = [GuardrailEventHooks.realtime_input_transcription]
+ _realtime_event_types = event_hooks
_check_data = {**self.request_data, "transcript": transcript}
_already_run: set = set()
@@ -992,6 +1065,8 @@ class RealTimeStreaming:
guardrail_turn_detection_injected = False
msg_type: Optional[str] = None
try:
+ from litellm.types.guardrails import GuardrailEventHooks
+
msg_obj = json.loads(message)
msg_type = msg_obj.get("type")
@@ -1044,6 +1119,7 @@ class RealTimeStreaming:
blocked = await self.run_realtime_guardrails(
output_text,
pre_block_backend_message=sanitized_msg,
+ event_hooks=[GuardrailEventHooks.pre_call],
)
if blocked:
# ``_pending_guardrail_message`` is
@@ -1069,7 +1145,8 @@ class RealTimeStreaming:
combined_text = " ".join(texts)
if combined_text:
blocked = await self.run_realtime_guardrails(
- combined_text
+ combined_text,
+ event_hooks=[GuardrailEventHooks.pre_call],
)
if blocked:
# Store the guardrail reason so the next response.create
diff --git a/litellm/llms/gemini/realtime/transformation.py b/litellm/llms/gemini/realtime/transformation.py
index 212287fb7f8..51fa395d899 100644
--- a/litellm/llms/gemini/realtime/transformation.py
+++ b/litellm/llms/gemini/realtime/transformation.py
@@ -195,13 +195,48 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
def get_audio_mime_type(self, input_audio_format: str = "pcm16"):
mime_types = {
- "pcm16": "audio/pcm",
+ "pcm16": "audio/pcm;rate=24000",
"g711_ulaw": "audio/pcmu",
"g711_alaw": "audio/pcma",
}
return mime_types.get(input_audio_format, "application/octet-stream")
+ def _manual_turn_detection_enabled(
+ self, session_configuration_request: Optional[str]
+ ) -> bool:
+ if not session_configuration_request:
+ return False
+ try:
+ setup = json.loads(session_configuration_request).get("setup", {})
+ automatic_detection = setup.get("realtimeInputConfig", {}).get(
+ "automaticActivityDetection", {}
+ )
+ return (
+ isinstance(automatic_detection, dict)
+ and automatic_detection.get("disabled") is True
+ )
+ except (json.JSONDecodeError, TypeError, AttributeError):
+ return False
+
+ def _handle_input_audio_buffer_commit_or_end(
+ self, session_configuration_request: Optional[str]
+ ) -> List[str]:
+ """Map OpenAI buffer commit/end to Gemini Live turn-boundary signals."""
+ if self._manual_turn_detection_enabled(session_configuration_request):
+ realtime_input_dict: BidiGenerateContentRealtimeInput = {
+ "activityEnd": True,
+ }
+ verbose_logger.debug(
+ "Gemini Realtime: Sending activityEnd realtimeInput to backend"
+ )
+ else:
+ realtime_input_dict = {"audioStreamEnd": True}
+ verbose_logger.debug(
+ "Gemini Realtime: Sending audioStreamEnd realtimeInput to backend"
+ )
+ return [json.dumps({"realtimeInput": realtime_input_dict})]
+
def map_automatic_turn_detection(
self, value: OpenAIRealtimeTurnDetection
) -> AutomaticActivityDetection:
@@ -656,6 +691,19 @@ class GeminiRealtimeConfig(BaseRealtimeConfig):
)
messages.append(gemini_msg)
return messages
+
+ if msg_type in ("input_audio_buffer.commit", "input_audio_buffer.end"):
+ return self._handle_input_audio_buffer_commit_or_end(
+ session_configuration_request
+ )
+
+ if msg_type == "input_audio_buffer.clear":
+ # Local OpenAI buffer op — nothing to forward to Gemini Live.
+ verbose_logger.debug(
+ "Gemini Realtime: input_audio_buffer.clear is a local buffer op"
+ )
+ return []
+
# Unknown/unsupported OpenAI event type — drop silently rather than
# forwarding raw JSON as text input to the model.
return []
diff --git a/litellm/llms/vertex_ai/realtime/transformation.py b/litellm/llms/vertex_ai/realtime/transformation.py
index ea4dbccc8c8..d6441db7856 100644
--- a/litellm/llms/vertex_ai/realtime/transformation.py
+++ b/litellm/llms/vertex_ai/realtime/transformation.py
@@ -90,7 +90,8 @@ class VertexAIRealtimeConfig(GeminiRealtimeConfig):
def get_audio_mime_type(self, input_audio_format: str = "pcm16") -> str:
mime_types = {
- "pcm16": "audio/pcm;rate=16000",
+ # Gemini Live native audio (OpenAI GA realtime default) is 24kHz PCM.
+ "pcm16": "audio/pcm;rate=24000",
"g711_ulaw": "audio/pcmu",
"g711_alaw": "audio/pcma",
}
diff --git a/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py b/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py
index 0f8d5cfd85a..ca709e768e5 100644
--- a/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py
+++ b/tests/test_litellm/litellm_core_utils/test_realtime_streaming.py
@@ -1159,11 +1159,10 @@ async def test_realtime_text_input_guardrail_uses_pre_call_mode():
assert (
streaming._has_realtime_guardrails() is True
), "pre_call guardrail should be recognized as a realtime guardrail"
- # pre_call guardrail SHOULD trigger the audio/VAD session.update injection so
- # that the LLM does not auto-respond before the guardrail can check the transcript.
+ # pre_call-only guardrails gate typed user messages / tool output, not audio VAD.
assert (
- streaming._has_audio_transcription_guardrails() is True
- ), "pre_call guardrail should trigger audio transcription guardrail path"
+ streaming._has_audio_transcription_guardrails() is False
+ ), "pre_call-only guardrail must not disable server_vad auto-response"
litellm.callbacks = [] # cleanup
@@ -1245,11 +1244,10 @@ async def test_realtime_session_created_injects_session_update_for_audio_guardra
@pytest.mark.asyncio
-async def test_realtime_session_created_injects_session_update_for_pre_call_guardrail():
+async def test_realtime_session_created_does_not_inject_session_update_for_pre_call_only():
"""
- Test that when a pre_call guardrail is configured, session.created triggers the
- session.update injection (create_response: false) so the LLM does not auto-respond
- before the guardrail can check the voice transcript.
+ pre_call-only guardrails must not inject create_response:false on realtime
+ sessions — that breaks server_vad for audio-only voice agents (e.g. Model Armor).
"""
import litellm
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -1288,22 +1286,62 @@ async def test_realtime_session_created_injects_session_update_for_pre_call_guar
streaming = RealTimeStreaming(client_ws, backend_ws, logging_obj)
await streaming.backend_to_client_send_messages()
- # session.update SHOULD be injected so the LLM waits for guardrail approval
sent_to_backend = [
json.loads(c.args[0]) for c in backend_ws.send.call_args_list if c.args
]
session_updates = [e for e in sent_to_backend if e.get("type") == "session.update"]
assert (
- len(session_updates) == 1
- ), f"pre_call guardrail should inject session.update to gate audio responses, got: {sent_to_backend}"
- # GA shape: turn_detection must be nested under audio.input, not at top-level session
- injected_session = session_updates[0]["session"]
- assert (
- injected_session["type"] == "realtime"
- ), "GA session.update must include session.type='realtime'"
- assert (
- injected_session["audio"]["input"]["turn_detection"]["create_response"] is False
- ), "GA session.update must nest turn_detection under audio.input"
+ len(session_updates) == 0
+ ), f"pre_call-only guardrail must not inject session.update, got: {sent_to_backend}"
+
+ litellm.callbacks = [] # cleanup
+
+
+async def test_pre_call_and_post_call_guardrails_do_not_disable_server_vad():
+ """Model Armor-style pre_call + post_call must not gate audio VAD."""
+ import litellm
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ class ModelArmorStyleGuardrail(CustomGuardrail):
+ async def apply_guardrail(
+ self, inputs, request_data, input_type, logging_obj=None
+ ):
+ return inputs
+
+ litellm.callbacks = [
+ ModelArmorStyleGuardrail(
+ guardrail_name="model_armor_all_pre_call",
+ event_hook=GuardrailEventHooks.pre_call,
+ default_on=False,
+ ),
+ ModelArmorStyleGuardrail(
+ guardrail_name="model_armor_all_post_call",
+ event_hook=GuardrailEventHooks.post_call,
+ default_on=False,
+ ),
+ ]
+
+ client_ws = MagicMock()
+ backend_ws = MagicMock()
+ logging_obj = MagicMock()
+ streaming = RealTimeStreaming(
+ client_ws,
+ backend_ws,
+ logging_obj,
+ request_data={
+ "metadata": {
+ "guardrails": [
+ "model_armor_all_pre_call",
+ "model_armor_all_post_call",
+ ]
+ }
+ },
+ )
+
+ assert streaming._has_realtime_guardrails() is True
+ assert streaming._has_audio_transcription_guardrails() is False
litellm.callbacks = [] # cleanup
@@ -2306,3 +2344,56 @@ async def test_audio_delta_frame_parsed_at_most_once():
await streaming.backend_to_client_send_messages()
assert calls["n"] == 1
+
+
+def test_collapse_buffered_audio_messages_applies_clear_semantics():
+ old = json.dumps({"type": "input_audio_buffer.append", "audio": "old"})
+ cleared = json.dumps({"type": "input_audio_buffer.clear"})
+ new = json.dumps({"type": "input_audio_buffer.append", "audio": "new"})
+ commit = json.dumps({"type": "input_audio_buffer.commit"})
+
+ collapsed = RealTimeStreaming._collapse_buffered_audio_messages(
+ [old, cleared, new, commit]
+ )
+
+ assert collapsed == [new, commit]
+
+
+async def test_deferred_setup_clear_drops_buffered_appends_on_flush():
+ client_ws = MagicMock()
+ backend_ws = MagicMock()
+ logging_obj = MagicMock()
+ streaming = RealTimeStreaming(client_ws, backend_ws, logging_obj)
+
+ old_audio = json.dumps({"type": "input_audio_buffer.append", "audio": "old"})
+ clear_msg = json.dumps({"type": "input_audio_buffer.clear"})
+ new_audio = json.dumps({"type": "input_audio_buffer.append", "audio": "new"})
+
+ streaming._pending_messages_until_setup = [old_audio, clear_msg, new_audio]
+ streaming._sync_pending_messages_byte_total()
+
+ streaming._send_to_backend = AsyncMock(return_value=True) # type: ignore[method-assign]
+
+ await streaming._flush_pending_messages_until_setup()
+
+ assert streaming._send_to_backend.await_count == 1
+ assert streaming._send_to_backend.await_args_list[0].args[0] == new_audio
+
+
+async def test_deferred_setup_clear_drops_appends_when_buffered():
+ client_ws = MagicMock()
+ backend_ws = MagicMock()
+ logging_obj = MagicMock()
+ streaming = RealTimeStreaming(client_ws, backend_ws, logging_obj)
+
+ old_audio = json.dumps({"type": "input_audio_buffer.append", "audio": "old"})
+ clear_msg = json.dumps({"type": "input_audio_buffer.clear"})
+ new_audio = json.dumps({"type": "input_audio_buffer.append", "audio": "new"})
+
+ streaming._buffer_pending_message_until_setup(old_audio)
+ streaming._buffer_pending_message_until_setup(clear_msg)
+ streaming._buffer_pending_message_until_setup(new_audio)
+
+ assert streaming._pending_messages_until_setup == [new_audio]
diff --git a/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py b/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py
index 53f0766dbcb..85da855f8ef 100644
--- a/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py
+++ b/tests/test_litellm/llms/gemini/realtime/test_gemini_realtime_transformation.py
@@ -1283,6 +1283,63 @@ def test_gemini_realtime_pipecat_semantic_vad_omits_realtime_input_config():
assert setup["tools"][0]["function_declarations"][0]["name"] == "terminate_call"
+def test_gemini_input_audio_buffer_commit_maps_to_audio_stream_end():
+ config = GeminiRealtimeConfig()
+ setup = {
+ "setup": {
+ "realtimeInputConfig": {
+ "automaticActivityDetection": {"disabled": False},
+ }
+ }
+ }
+ messages = config.transform_realtime_request(
+ json.dumps({"type": "input_audio_buffer.commit"}),
+ "gemini-live-2.5-flash-native-audio",
+ session_configuration_request=json.dumps(setup),
+ )
+ assert len(messages) == 1
+ assert json.loads(messages[0]) == {"realtimeInput": {"audioStreamEnd": True}}
+
+
+def test_gemini_input_audio_buffer_end_maps_to_audio_stream_end():
+ config = GeminiRealtimeConfig()
+ messages = config.transform_realtime_request(
+ json.dumps({"type": "input_audio_buffer.end"}),
+ "gemini-live-2.5-flash-native-audio",
+ session_configuration_request=None,
+ )
+ assert len(messages) == 1
+ assert json.loads(messages[0]) == {"realtimeInput": {"audioStreamEnd": True}}
+
+
+def test_gemini_input_audio_buffer_clear_is_local_noop():
+ config = GeminiRealtimeConfig()
+ messages = config.transform_realtime_request(
+ json.dumps({"type": "input_audio_buffer.clear"}),
+ "gemini-live-2.5-flash-native-audio",
+ session_configuration_request=None,
+ )
+ assert messages == []
+
+
+def test_gemini_input_audio_buffer_commit_maps_to_activity_end_when_manual_vad():
+ config = GeminiRealtimeConfig()
+ setup = {
+ "setup": {
+ "realtimeInputConfig": {
+ "automaticActivityDetection": {"disabled": True},
+ }
+ }
+ }
+ messages = config.transform_realtime_request(
+ json.dumps({"type": "input_audio_buffer.commit"}),
+ "gemini-live-2.5-flash-native-audio",
+ session_configuration_request=json.dumps(setup),
+ )
+ assert len(messages) == 1
+ assert json.loads(messages[0]) == {"realtimeInput": {"activityEnd": True}}
+
+
def test_gemini_subsequent_session_update_with_turn_detection_only_preserves_original_tools():
"""A subsequent session.update carrying only turn_detection (the
guardrail-injected disable) must keep the original tools/generationConfig."""