Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
105 changes: 44 additions & 61 deletions litellm/litellm_core_utils/realtime_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def __init__(
provider_config: Optional[BaseRealtimeConfig] = None,
model: str = "",
user_api_key_dict: Optional[Any] = None,
request_data: Optional[Dict] = None,
):
self.websocket = websocket
self.backend_ws = backend_ws
Expand All @@ -68,6 +69,10 @@ def __init__(
self.current_delta_type: Optional[ALL_DELTA_TYPES] = None
self.session_configuration_request: Optional[str] = None
self.user_api_key_dict = user_api_key_dict
self.request_data: Dict = request_data or {}
# Set to True after a text-input guardrail block so we can swallow the client's
# subsequent response.create (which would conflict with the block response).
self._swallow_next_response_create: bool = False

def _should_store_message(
self,
Expand Down Expand Up @@ -231,15 +236,23 @@ async def _send_to_backend(self, message: str) -> None:
await self.backend_ws.send(message)

def _has_realtime_guardrails(self) -> bool:
"""Return True if any callback is registered for realtime_input_transcription."""
"""Return True if any callback is registered for realtime guardrail event types."""
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 cb.should_run_guardrail(
data={},
event_type=GuardrailEventHooks.realtime_input_transcription,
and any(
cb.should_run_guardrail(
data=self.request_data,
event_type=et,
)
for et in _realtime_event_types
)
for cb in litellm.callbacks
)
Expand All @@ -258,17 +271,25 @@ async def run_realtime_guardrails(
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,
]
_check_data = {**self.request_data, "transcript": transcript}
_already_run: set = set()

for callback in litellm.callbacks:
if not isinstance(callback, CustomGuardrail):
continue
if (
callback.should_run_guardrail(
data={"transcript": transcript},
event_type=GuardrailEventHooks.realtime_input_transcription,
)
is not True
if id(callback) in _already_run:
continue
if not any(
callback.should_run_guardrail(data=_check_data, event_type=et)
for et in _realtime_event_types
):
continue
Comment on lines +289 to 306

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

post_call guardrails run on user input, not LLM output

run_realtime_guardrails checks all three event types (pre_call, post_call, realtime_input_transcription) when deciding whether to run a guardrail. This means a guardrail configured with mode: post_call — which is semantically meant to run on the LLM's response — will instead be called on the user's input text during both the conversation.item.create path and the audio transcription path.

A post_call guardrail author may have written detection logic that only makes sense for response content (e.g., checking for hallucinations, formatting violations, or PII in the assistant's reply). Running that same apply_guardrail on user input text could produce false positives or false negatives.

Consider either:

  1. Only matching pre_call and realtime_input_transcription for the input-side check (since those are semantically about guarding input), or
  2. Documenting that post_call guardrails will also gate user input in the realtime context so guardrail authors can account for it.

_already_run.add(id(callback))
try:
await callback.apply_guardrail(
inputs={"texts": [transcript], "images": []},
Expand All @@ -293,20 +314,15 @@ async def run_realtime_guardrails(
safe_msg = str(detail)
else:
safe_msg = str(e) or "I'm sorry, that request was blocked by the content filter."
# Cancel any in-flight response before speaking the warning.
# This handles the race where create_response fired before we could intercept.
await self._send_to_backend(json.dumps({"type": "response.cancel"}))
# Ask the model to speak the warning — TTS audio plays naturally in the client
await self._send_to_backend(
# Return the error directly to the WebSocket consumer.
await self.websocket.send_text(
json.dumps(
{
"type": "response.create",
"response": {
"modalities": ["text", "audio"],
"instructions": (
f"Say exactly and only: \"{safe_msg}\". "
"Do not add anything else."
),
"type": "error",
"error": {
"type": "guardrail_violation",
"message": safe_msg,
"code": "content_policy_violation",
},
}
)
Expand Down Expand Up @@ -348,23 +364,6 @@ async def _handle_provider_config_message(self, raw_response) -> None:
if isinstance(transformed_response, list)
else [transformed_response]
)
for event in events:
## GUARDRAIL: inject create_response=false on session.created
if isinstance(event, dict) and event.get("type") == "session.created":
if self._has_realtime_guardrails():
await self._send_to_backend(
json.dumps(
{
"type": "session.update",
"session": {
"turn_detection": {
"type": "server_vad",
"create_response": False,
}
},
}
)
)
for event in events:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removal of create_response: false injection may cause double responses for audio/VAD path

The previous code injected session.update with create_response: false into the backend session when guardrails were registered. This prevented the LLM from auto-responding to VAD speech completions before the guardrail had a chance to run.

With this code removed, when server VAD detects speech completion, the backend will auto-generate a response (create_response defaults to true). Then, after the transcription arrives and guardrails pass, the proxy also sends a manual response.create (lines 383-384 in the provider_config path, and lines 415-417 in the raw path). This could result in two LLM responses for each clean audio transcription.

For the new text-input (conversation.item.create) path this isn't an issue since the client explicitly controls response.create. But for the existing audio transcription guardrail flow, this removal appears to be a regression. Consider keeping the create_response: false injection for audio-based guardrails, or gating the proxy's manual response.create on whether auto-response is already enabled.

event_str = json.dumps(event)
## GUARDRAIL: run on transcription events in provider_config path too
Expand Down Expand Up @@ -397,28 +396,6 @@ async def _handle_raw_backend_message(self, raw_response) -> bool:
try:
event_obj = json.loads(raw_response)

if event_obj.get("type") == "session.created":
# If any realtime guardrails are registered, proactively
# set create_response=false so the LLM never auto-responds
# before our guardrail has a chance to run.
if self._has_realtime_guardrails():
await self._send_to_backend(
json.dumps(
{
"type": "session.update",
"session": {
"turn_detection": {
"type": "server_vad",
"create_response": False,
}
},
}
)
)
verbose_logger.debug(
"[realtime guardrail] injected create_response=false into session"
)

if (
event_obj.get("type")
== "conversation.item.input_audio_transcription.completed"
Expand Down Expand Up @@ -490,6 +467,11 @@ async def client_ack_messages(self):
msg_obj = json.loads(message)
msg_type = msg_obj.get("type")

# Swallow the client's response.create if we just blocked an item.
if msg_type == "response.create" and self._swallow_next_response_create:
self._swallow_next_response_create = False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_swallow_next_response_create can lose track when multiple items are blocked consecutively

If the client sends two conversation.item.create messages that are both blocked in a row (without an intervening response.create), the flag is set to True twice. The next single response.create clears it, but the second response.create (for the second blocked item) will pass through to the backend, potentially triggering a response for content that was blocked.

Consider using a counter instead of a boolean:

Suggested change
if msg_type == "response.create" and self._swallow_next_response_create:
self._swallow_next_response_create = False
if msg_type == "response.create" and self._swallow_next_response_create:
self._swallow_next_response_create -= 1

(with corresponding change to set self._swallow_next_response_create += 1 on block, and initializing as 0 instead of False).

continue # block response already sent by guardrail

if msg_type == "conversation.item.create":
# Check user text messages for prompt injection
item = msg_obj.get("item", {})
Expand All @@ -506,6 +488,7 @@ async def client_ack_messages(self):
combined_text
)
if blocked:
self._swallow_next_response_create = True
continue # don't forward to backend

except (json.JSONDecodeError, AttributeError):
Expand Down
2 changes: 2 additions & 0 deletions litellm/llms/openai/realtime/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ async def async_realtime(
timeout: Optional[float] = None,
query_params: Optional[RealtimeQueryParams] = None,
user_api_key_dict: Optional[Any] = None,
litellm_metadata: Optional[dict] = None,
**kwargs: Any,
):
import websockets
Expand Down Expand Up @@ -142,6 +143,7 @@ async def async_realtime(
cast(ClientConnection, backend_ws),
logging_obj,
user_api_key_dict=user_api_key_dict,
request_data={"litellm_metadata": litellm_metadata or {}},
)
await realtime_streaming.bidirectional_forward()

Expand Down
6 changes: 6 additions & 0 deletions litellm/realtime_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ async def _arealtime(
or get_secret_str("OPENAI_API_KEY")
)

# Build metadata for guardrail checking.
_litellm_metadata: dict = {**(kwargs.get("litellm_metadata") or {})}
_guardrails = (kwargs.get("metadata") or {}).get("guardrails") or kwargs.get("guardrails") or []
if _guardrails:
_litellm_metadata["guardrails"] = _guardrails

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Guardrail metadata only plumbed for OpenAI provider

The litellm_metadata (with guardrails list) is only constructed and passed in the openai branch. Other providers that use RealTimeStreaming (Azure, XAI) also support guardrails via the same class, but they don't receive litellm_metadata/request_data. This means non-default_on guardrails (those that need explicit guardrails: [...] in the request) won't be picked up for those providers.

If this is intentional (OpenAI-only for now), it might be worth a code comment. Otherwise, consider extracting the metadata build to a shared helper before the provider branches so all providers benefit.

await openai_realtime.async_realtime(
model=model,
websocket=websocket,
Expand All @@ -160,6 +165,7 @@ async def _arealtime(
timeout=timeout,
query_params=query_params,
user_api_key_dict=kwargs.get("user_api_key_dict"),
litellm_metadata=_litellm_metadata,
)
elif _custom_llm_provider == "bedrock":
# Extract AWS parameters from kwargs
Expand Down
Loading
Loading