Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 102 additions & 25 deletions litellm/litellm_core_utils/realtime_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,12 @@ def __init__(
"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},
Expand Down Expand Up @@ -308,6 +312,48 @@ def _uses_deferred_backend_setup(self) -> bool:
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
Expand All @@ -323,6 +369,18 @@ def _should_buffer_client_message_until_setup(self, message: str) -> bool:
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)
Expand All @@ -340,7 +398,9 @@ def _buffer_pending_message_until_setup(self, message: str) -> None:
)

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):
Expand Down Expand Up @@ -425,48 +485,59 @@ async def _maybe_send_guardrail_turn_detection_update(self) -> None:
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(
cb.should_run_guardrail(
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]
Comment thread
Sameerlite marked this conversation as resolved.
Resolved
)

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).
Expand All @@ -477,15 +548,17 @@ async def run_realtime_guardrails(
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()

Expand Down Expand Up @@ -992,6 +1065,8 @@ async def client_ack_messages(self): # noqa: PLR0915
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")

Expand Down Expand Up @@ -1044,6 +1119,7 @@ async def client_ack_messages(self): # noqa: PLR0915
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
Expand All @@ -1069,7 +1145,8 @@ async def client_ack_messages(self): # noqa: PLR0915
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
Expand Down
50 changes: 49 additions & 1 deletion litellm/llms/gemini/realtime/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,48 @@ def map_generation_complete_event(

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:
Expand Down Expand Up @@ -656,6 +691,19 @@ def transform_realtime_request(
)
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 []
Expand Down
3 changes: 2 additions & 1 deletion litellm/llms/vertex_ai/realtime/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ def validate_environment(

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",
}
Expand Down
Loading
Loading