litellm/tests/unit/responses/test_responses_websocket_all_providers.py
quietjules 0134008628
fix(responses): write one failure row per Responses WebSocket turn the deployment refuses (#50731)
* fix(responses): write one failure row per refused Responses WebSocket turn

A turn the deployment refuses on an open native or managed Responses WebSocket now writes its own spend
log failure row when it is refused, with its own request id, the turn's start time and request, the
socket's resolved model group and the websocket call type. Before, refused turns wrote nothing until the
socket closed, and then only one row for the whole socket, carrying the socket's open time and first frame.

Guardrail-blocked turns go through the same row builder, so their rows now carry the model group and call
type too. Turns refused or crashed in the turn check before a session-limit cancel also keep their rows.

The socket's close-time failure hooks still run once to settle the admission budget reservation, but when
the close failure is the first refused turn the spend logger skips the duplicate row.

* fix(responses): keep forged logging state out of refused-turn rows and wait for each row

A refused turn's failure row now leaves out the top-level fields the HTTP path strips from a client body, plus standard_callback_dynamic_params and litellm_params, so a frame cannot forge its own logging state or turn off message redaction. The relay now waits for each refused turn's row before it reads the next frame, and the write still finishes if the socket is cancelled meanwhile

* ci: start the unit workflow GitHub never created for the previous push

* fix(responses): keep the client's request tags on refused-turn rows

A refused turn's row now carries the key's tags plus the client's User-Agent tags, computed from the socket's request headers like its success rows, while the headers themselves stay out of the row

* fix(responses): keep a refused turn's frame from forging its spend row and store no blocked prompt

A refused turn's failure row now takes only the turn's model and call id from the frame, ignores frame metadata tags and model_group, and logs non-object metadata as empty instead of dropping the row. Guardrail-blocked frames no longer carry a stored request.

* fix(proxy): keep the socket's session id, guardrail records, and router-key strip on refused WebSocket turn rows

* fix(proxy): use the public router-reserved metadata field list, as main renamed it

* fix(responses): give refused WebSocket turn rows the socket's session id

When a socket's request carries no trace id, the router minted its own for the relayed turns, so success rows and refused-turn rows had different session ids. The endpoint now hands the router the socket's trace id

The refused-turn row test's session-limit case jumps the loop clock past the limit once the relay is parked, instead of racing a 50 ms timer

* test(responses): expect the parallel-slot refusal at the WebSocket handshake

Main now refuses a cached key that is over its limits before the request body is read, so a second socket on a key whose only parallel slot an open socket holds is refused at the upgrade instead of with a 429 frame. The test still checks that the refused turn's failure row keeps the slot held until the first socket closes

* fix(responses): take a refused WebSocket turn's agent and session fields from the socket

A frame's metadata.agent_id, billing_agent_id or session_id no longer lands on the refused turn's spend row. The row copies those fields from the socket, like its success rows

The integration test no longer pins the reopened socket's 1011 close, which is incidental to the held slot it checks

* test(responses): expect a 403 when a held parallel slot refuses a second WebSocket handshake

* test(responses): expect a held parallel slot to refuse a second socket's first turn with a 429 frame

Main's #51675 skips the headers-only limit check for a bodyless GET, and every WebSocket upgrade is one, so a second socket on a key whose only parallel slot is held now opens and its first turn gets a 429 max_parallel_requests frame and close 1008 instead of a 403 at the handshake

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-16 22:08:06 -08:00

5162 lines
193 KiB
Python

"""
Unit tests to verify that all providers support Responses API WebSocket mode.
Tests that:
1. All providers with ResponsesAPIConfig support websocket mode
2. Providers with native websocket support use direct connection
3. Providers without native websocket support use ManagedResponsesWebSocketHandler
"""
import asyncio
import itertools
import json
from collections.abc import AsyncIterator, Mapping
from datetime import datetime, timezone
from functools import partial
from typing import TYPE_CHECKING, Final
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
import respx
from litellm.llms.azure.responses.transformation import AzureOpenAIResponsesAPIConfig
from litellm.llms.chatgpt.responses.transformation import ChatGPTResponsesAPIConfig
from litellm.llms.custom_llm import CustomLLM
from litellm.llms.databricks.responses.transformation import (
DatabricksResponsesAPIConfig,
)
from litellm.llms.fireworks_ai.responses.transformation import (
FireworksAIResponsesAPIConfig,
)
from litellm.llms.github_copilot.responses.transformation import (
GithubCopilotResponsesAPIConfig,
)
from litellm.llms.hosted_vllm.responses.transformation import (
HostedVLLMResponsesAPIConfig,
)
from litellm.llms.litellm_proxy.responses.transformation import (
LiteLLMProxyResponsesAPIConfig,
)
from litellm.llms.manus.responses.transformation import ManusResponsesAPIConfig
from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
from litellm.llms.openrouter.responses.transformation import (
OpenRouterResponsesAPIConfig,
)
from litellm.llms.perplexity.responses.transformation import PerplexityResponsesConfig
from litellm.llms.volcengine.responses.transformation import (
VolcEngineResponsesAPIConfig,
)
from litellm.llms.xai.responses.transformation import XAIResponsesAPIConfig
from litellm.redis.stores.connection import connect
from litellm.redis.stores.router_usage import CounterIncrement, RouterUsageStore, UsageCounter
from litellm.types.utils import GenericStreamingChunk
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import ResponsesWsTurnAdmission
from litellm.router_utils.pre_call_checks.model_rate_limit_check import ModelRateLimitingCheck
class TestResponsesAPIWebSocketSupport:
"""Test that all providers have websocket support configured correctly"""
def test_openai_supports_native_websocket(self):
"""OpenAI should support native websocket"""
config = OpenAIResponsesAPIConfig()
assert (
config.supports_native_websocket() is True
), "OpenAI should support native websocket"
def test_azure_supports_native_websocket(self):
"""Azure should support native websocket"""
config = AzureOpenAIResponsesAPIConfig()
assert (
config.supports_native_websocket() is True
), "Azure should support native websocket"
def test_azure_websocket_url_uses_v1_path(self):
"""Azure WebSocket URL must use /openai/v1/responses (no api-version)"""
config = AzureOpenAIResponsesAPIConfig()
url = config.get_websocket_url(
api_base="https://myresource.cognitiveservices.azure.com",
litellm_params={"api_version": "2025-04-01-preview"},
)
assert url == "wss://myresource.cognitiveservices.azure.com/openai/v1/responses"
assert "api-version" not in url
def test_azure_websocket_url_strips_existing_path(self):
"""api_base that already contains /openai/responses must be cleaned"""
config = AzureOpenAIResponsesAPIConfig()
url = config.get_websocket_url(
api_base="https://myresource.cognitiveservices.azure.com/openai/responses",
litellm_params={},
)
assert url == "wss://myresource.cognitiveservices.azure.com/openai/v1/responses"
def test_azure_websocket_url_strips_query_params(self):
config = AzureOpenAIResponsesAPIConfig()
url = config.get_websocket_url(
api_base="https://myresource.cognitiveservices.azure.com/openai/responses?api-version=2024-05-01-preview",
litellm_params={},
)
assert url == "wss://myresource.cognitiveservices.azure.com/openai/v1/responses"
def test_azure_websocket_url_requires_api_base(self):
config = AzureOpenAIResponsesAPIConfig()
with pytest.raises(ValueError, match='api_base is required for Azure WebSocket'):
config.get_websocket_url(api_base=None, litellm_params={})
def test_azure_model_not_in_websocket_url(self):
"""Azure sends the model in the body, so it must not be appended to the URL"""
assert AzureOpenAIResponsesAPIConfig().model_in_websocket_url() is False
def test_openai_default_websocket_url_converts_scheme(self):
"""The base get_websocket_url default converts the HTTP endpoint to wss://"""
config = OpenAIResponsesAPIConfig()
url = config.get_websocket_url(
api_base="https://api.openai.com/v1", litellm_params={}
)
assert url == "wss://api.openai.com/v1/responses"
def test_openai_model_in_websocket_url_default(self):
assert OpenAIResponsesAPIConfig().model_in_websocket_url() is True
def test_fireworks_ai_uses_managed_websocket(self):
"""Fireworks AI should use managed websocket handler"""
assert (
FireworksAIResponsesAPIConfig().supports_native_websocket() is False
), "Fireworks AI should use managed websocket handler"
def test_xai_uses_managed_websocket(self):
"""XAI should use managed websocket handler"""
config = XAIResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "XAI should use managed websocket handler"
def test_github_copilot_uses_managed_websocket(self):
"""GitHub Copilot should use managed websocket handler"""
config = GithubCopilotResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "GitHub Copilot should use managed websocket handler"
def test_chatgpt_uses_managed_websocket(self):
"""ChatGPT should use managed websocket handler"""
config = ChatGPTResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "ChatGPT should use managed websocket handler"
def test_litellm_proxy_uses_managed_websocket(self):
"""LiteLLM Proxy should use managed websocket handler"""
config = LiteLLMProxyResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "LiteLLM Proxy should use managed websocket handler"
def test_volcengine_uses_managed_websocket(self):
"""VolcEngine should use managed websocket handler"""
config = VolcEngineResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "VolcEngine should use managed websocket handler"
def test_manus_uses_managed_websocket(self):
"""Manus should use managed websocket handler"""
config = ManusResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "Manus should use managed websocket handler"
def test_perplexity_uses_managed_websocket(self):
"""Perplexity should use managed websocket handler"""
config = PerplexityResponsesConfig()
assert (
config.supports_native_websocket() is False
), "Perplexity should use managed websocket handler"
def test_databricks_uses_managed_websocket(self):
"""Databricks should use managed websocket handler"""
config = DatabricksResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "Databricks should use managed websocket handler"
def test_openrouter_uses_managed_websocket(self):
"""OpenRouter should use managed websocket handler"""
config = OpenRouterResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "OpenRouter should use managed websocket handler"
def test_hosted_vllm_uses_managed_websocket(self):
"""Hosted vLLM should use managed websocket handler"""
config = HostedVLLMResponsesAPIConfig()
assert (
config.supports_native_websocket() is False
), "Hosted vLLM should use managed websocket handler"
class TestManagedWebSocketHandlerIntegration:
"""Test that ManagedResponsesWebSocketHandler is properly integrated"""
@pytest.mark.asyncio
async def test_managed_handler_instantiation(self):
"""Test that ManagedResponsesWebSocketHandler can be instantiated"""
from unittest.mock import MagicMock
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
mock_websocket = MagicMock()
mock_logging_obj = Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
)
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="test-model",
logging_obj=mock_logging_obj,
user_api_key_dict=None,
litellm_metadata={},
api_key="test-key",
api_base="https://api.example.com",
timeout=30.0,
custom_llm_provider="test_provider",
)
assert handler.model == "test-model"
assert handler.api_key == "test-key"
assert handler.api_base == "https://api.example.com"
assert handler.timeout == 30.0
assert handler.custom_llm_provider == "test_provider"
@pytest.mark.asyncio
async def test_frame_alias_resolves_to_connection_model(self, monkeypatch):
"""
A response.create frame that repeats the public model alias must reach
litellm.aresponses with the router-resolved deployment model, not the
raw alias (which fails in get_llm_provider). Regression for codex
WebSocket sessions against managed providers like bedrock_mantle.
"""
import json
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
captured: dict = {}
async def fake_aresponses(*args, **kwargs):
captured["model"] = kwargs.get("model")
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="bedrock_mantle/openai.gpt-5.5",
logging_obj=Logging(
model="bedrock_mantle/openai.gpt-5.5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
litellm_metadata={"model_group": "gpt-5.5-mantle"},
)
frame = json.dumps(
{
"type": "response.create",
"model": "gpt-5.5-mantle",
"input": [],
}
)
await handler._process_response_create(frame)
assert captured["model"] == "bedrock_mantle/openai.gpt-5.5"
@pytest.mark.asyncio
async def test_managed_socket_runs_the_frame_guard_on_every_turn(self, monkeypatch):
import json
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame, ManagedResponsesWebSocketHandler
async def guard(frame: str) -> GuardedResponsesWsFrame:
body = json.loads(frame)
if "forbidden" in body["input"]:
raise ValueError("blocked by guardrail")
return GuardedResponsesWsFrame(
frame=json.dumps({**body, "input": body["input"].upper()}),
guardrail_information=({"guardrail_name": "g", "guardrail_cost": 0.5},),
)
async def empty_stream():
return
yield {}
aresponses: Final = AsyncMock(side_effect=lambda **kwargs: empty_stream())
monkeypatch.setattr(litellm, "aresponses", aresponses)
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model="anthropic/claude-sonnet-4-5",
logging_obj=Logging(
model="anthropic/claude-sonnet-4-5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
litellm_metadata={"user_api_key_hash": "k1"},
frame_guard=guard,
)
await handler._process_response_create(json.dumps({"type": "response.create", "input": "say forbidden"}))
await handler._process_response_create(json.dumps({"type": "response.create", "input": "hello"}))
aresponses.assert_awaited_once()
error_event: Final = json.loads(websocket.send_text.await_args_list[0].args[0])
assert error_event["error"] == {"type": "invalid_request_error", "message": "blocked by guardrail"}
sent: Final = aresponses.await_args.kwargs
assert sent["input"] == "HELLO"
assert sent["litellm_metadata"]["user_api_key_hash"] == "k1"
assert sent["litellm_metadata"]["standard_logging_guardrail_information"] == [
{"guardrail_name": "g", "guardrail_cost": 0.5}
]
@pytest.mark.asyncio
async def test_managed_socket_unmasks_the_reply_with_the_frame_guard_s_pii_tokens(self, monkeypatch):
import json
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame, ManagedResponsesWebSocketHandler
presidio = _FakeWSGuardrail()
async def guard(frame: str) -> GuardedResponsesWsFrame:
body = json.loads(frame)
masked = await presidio.check_pii(body["input"], True, None, walk := {})
return GuardedResponsesWsFrame(
frame=json.dumps({**body, "input": masked}), pii_tokens=walk["metadata"]["pii_tokens"]
)
provider_saw: dict = {}
async def fake_aresponses(**kwargs):
provider_saw.update(kwargs)
async def stream():
yield {"type": "response.output_text.delta", "delta": "Sent to <EMAIL_ADDRESS_1>"}
yield {
"type": "response.completed",
"response": {
"id": "resp_1",
"output": [
{"type": "message", "content": [{"type": "output_text", "text": "Sent to <EMAIL_ADDRESS_1>"}]}
],
},
}
return stream()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model="anthropic/claude-sonnet-4-5",
logging_obj=Logging(
model="anthropic/claude-sonnet-4-5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
frame_guard=guard,
guardrail_callbacks=[presidio],
)
await handler._process_response_create(
json.dumps({"type": "response.create", "input": "email alice@example.com please"})
)
assert provider_saw["input"] == "email <EMAIL_ADDRESS_1> please"
sent: Final = [json.loads(call.args[0]) for call in websocket.send_text.await_args_list]
assert sent[0]["delta"] == "Sent to alice@example.com"
assert sent[1]["response"]["output"][0]["content"][0]["text"] == "Sent to alice@example.com"
@pytest.mark.asyncio
async def test_http_handler_hands_the_frame_guard_to_a_managed_socket(self):
import json
from unittest.mock import AsyncMock, MagicMock
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
guard: Final = AsyncMock(side_effect=ValueError("blocked by guardrail"))
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
websocket.receive_text = AsyncMock(side_effect=ConnectionError("client left"))
await BaseLLMHTTPHandler().async_responses_websocket(
model="anthropic/claude-sonnet-4-5",
websocket=websocket,
logging_obj=MagicMock(),
responses_api_provider_config=None,
first_message=json.dumps({"type": "response.create", "input": "say forbidden"}),
frame_guard=guard,
)
guard.assert_awaited_once()
error_event: Final = json.loads(websocket.send_text.await_args.args[0])
assert error_event["error"]["message"] == "blocked by guardrail"
@pytest.mark.parametrize("terminal_type", ["response.completed", "response.incomplete"])
@pytest.mark.asyncio
async def test_truncated_turn_is_kept_as_history_for_the_next_turn(self, monkeypatch, terminal_type: str):
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import ManagedResponsesWebSocketHandler
terminal_response: Final = {
"type": terminal_type,
"response": {
"id": "resp_turn1",
"status": "incomplete" if terminal_type == "response.incomplete" else "completed",
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "PELICAN noted"}],
}
],
},
}
async def first_stream():
yield terminal_response
async def empty_stream():
return
yield {}
aresponses_mock: Final = AsyncMock(side_effect=(first_stream(), empty_stream()))
monkeypatch.setattr(litellm, "aresponses", aresponses_mock)
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model="bedrock_mantle/openai.gpt-5.5",
logging_obj=Logging(
model="bedrock_mantle/openai.gpt-5.5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
litellm_metadata={"model_group": "gpt-5.5-mantle"},
)
turn_one_user: Final[dict[str, object]] = {
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "My secret word is PELICAN"}],
}
turn_two_user: Final[dict[str, object]] = {
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "What is my secret word?"}],
}
turn_one_frame: Final = json.dumps({"type": "response.create", "input": [turn_one_user]})
turn_two_frame: Final = json.dumps(
{
"type": "response.create",
"previous_response_id": "resp_turn1",
"input": [turn_two_user],
}
)
await handler._process_response_create(turn_one_frame)
await handler._process_response_create(turn_two_frame)
expected_input: Final[list[dict[str, object]]] = [
turn_one_user,
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "PELICAN noted"}],
},
turn_two_user,
]
second_call_input: Final = aresponses_mock.call_args_list[1].kwargs["input"]
assert second_call_input == expected_input, terminal_type
@pytest.mark.asyncio
async def test_warmup_frame_skips_provider_and_sends_synthetic_ack(
self, monkeypatch
):
"""
A generate=false warmup frame (codex prewarm) carries empty input that
managed HTTP providers reject. It must not call the provider, and should
emit synthetic response.created/completed events so Codex can proceed.
"""
import json
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
called = False
async def fail_aresponses(*args, **kwargs):
nonlocal called
called = True
raise AssertionError("provider must not be called for a warmup frame")
monkeypatch.setattr(litellm, "aresponses", fail_aresponses)
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="bedrock_mantle/openai.gpt-5.5",
logging_obj=Logging(
model="bedrock_mantle/openai.gpt-5.5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
litellm_metadata={"model_group": "gpt-5.5-mantle"},
)
frame = json.dumps(
{
"type": "response.create",
"model": "gpt-5.5-mantle",
"generate": False,
"input": [],
}
)
await handler._process_response_create(frame)
assert called is False
assert mock_websocket.send_text.call_count == 2
events = [
json.loads(call.args[0]) for call in mock_websocket.send_text.call_args_list
]
assert events[0]["type"] == "response.created"
assert events[0]["response"]["status"] == "in_progress"
assert events[1]["type"] == "response.completed"
assert events[1]["response"]["status"] == "completed"
assert events[1]["response"]["output"] == []
assert events[1]["response"]["model"] == "gpt-5.5-mantle"
@pytest.mark.asyncio
async def test_warmup_previous_response_id_not_forwarded_to_provider(
self, monkeypatch
):
import json
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
captured: dict = {}
async def fake_aresponses(*args, **kwargs):
captured.update(kwargs)
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="bedrock_mantle/openai.gpt-5.5",
logging_obj=Logging(
model="bedrock_mantle/openai.gpt-5.5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
litellm_metadata={"model_group": "gpt-5.5-mantle"},
)
await handler._process_response_create(
json.dumps(
{
"type": "response.create",
"model": "gpt-5.5-mantle",
"generate": False,
"input": [],
}
)
)
warmup_id = json.loads(mock_websocket.send_text.call_args_list[1].args[0])[
"response"
]["id"]
await handler._process_response_create(
json.dumps(
{
"type": "response.create",
"model": "gpt-5.5-mantle",
"previous_response_id": warmup_id,
"input": [
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Hi"}],
}
],
}
)
)
assert "previous_response_id" not in captured
class TestChunkTransformation:
"""Test chunk serialization and transformation for WebSocket streaming"""
def test_serialize_chunk_with_dict(self):
"""Test serialization of dict chunks"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.created",
"response": {"id": "resp_456", "status": "in_progress"},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.created" in serialized
assert "resp_456" in serialized
def test_serialize_chunk_handles_invalid_json(self):
"""Test that chunks with circular references are handled"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
# Create object with circular reference
obj = {"a": 1}
obj["self"] = obj # type: ignore
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(obj)
assert serialized is None
def test_extract_output_messages_with_text_content(self):
"""Test extraction of output messages with text content"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Hello world"}],
}
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 1
assert messages[0]["type"] == "message"
assert messages[0]["role"] == "assistant"
assert messages[0]["content"][0]["text"] == "Hello world"
def test_extract_output_messages_with_multiple_content_parts(self):
"""Test extraction with multiple content parts"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{"type": "output_text", "text": "Part 1. "},
{"type": "output_text", "text": "Part 2."},
],
}
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 1
assert messages[0]["content"][0]["text"] == "Part 1. Part 2."
def test_extract_output_messages_with_function_calls(self):
"""Test that function calls are preserved"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
{
"type": "function_call",
"id": "call_123",
"name": "get_weather",
"arguments": '{"location": "Paris"}',
}
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 1
assert messages[0]["type"] == "function_call"
assert messages[0]["id"] == "call_123"
assert messages[0]["name"] == "get_weather"
def test_extract_output_messages_filters_empty_text(self):
"""Test that messages with empty text are filtered out"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": ""}],
},
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Valid text"}],
},
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 1
assert messages[0]["content"][0]["text"] == "Valid text"
def test_extract_output_messages_handles_non_dict_items(self):
"""Test that non-dict items are skipped"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
"invalid_string",
None,
123,
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Valid"}],
},
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 1
assert messages[0]["content"][0]["text"] == "Valid"
def test_input_to_messages_with_string(self):
"""Test conversion of string input to messages"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
messages = ManagedResponsesWebSocketHandler._input_to_messages("Hello world")
assert len(messages) == 1
assert messages[0]["type"] == "message"
assert messages[0]["role"] == "user"
assert messages[0]["content"][0]["type"] == "input_text"
assert messages[0]["content"][0]["text"] == "Hello world"
def test_input_to_messages_with_list(self):
"""Test conversion of list input to messages"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
input_list = [
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Question"}],
}
]
messages = ManagedResponsesWebSocketHandler._input_to_messages(input_list)
assert len(messages) == 1
assert messages[0]["type"] == "message"
assert messages[0]["content"][0]["text"] == "Question"
def test_input_to_messages_filters_non_dict_items(self):
"""Test that non-dict items in list input are filtered"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
input_list = [
"invalid_string",
None,
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Valid"}],
},
]
messages = ManagedResponsesWebSocketHandler._input_to_messages(input_list)
assert len(messages) == 1
assert messages[0]["content"][0]["text"] == "Valid"
def test_input_to_messages_handles_empty_input(self):
"""Test that empty input returns empty list"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
assert ManagedResponsesWebSocketHandler._input_to_messages(None) == []
assert ManagedResponsesWebSocketHandler._input_to_messages([]) == []
assert ManagedResponsesWebSocketHandler._input_to_messages({}) == []
class TestUpdateProxyRequest:
"""Regression tests for ManagedResponsesWebSocketHandler._update_proxy_request.
The managed WebSocket path calls ``litellm.aresponses(model=..., **call_kwargs)``.
``litellm_params`` is not a Responses API request field, so passing it as a
top-level kwarg leaks it into the provider request body and providers that
forbid extra inputs (e.g. Anthropic) reject the call with
``litellm_params: Extra inputs are not permitted``. The request-tracking data
must ride along as ``proxy_server_request`` instead, which litellm consumes
internally and never forwards to the provider.
"""
def test_does_not_inject_litellm_params_kwarg(self):
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
call_kwargs = {
"input": "hello",
"store": True,
"litellm_metadata": {
"proxy_server_request": {"headers": {}, "body": {}},
},
}
ManagedResponsesWebSocketHandler._update_proxy_request(
call_kwargs, "anthropic/claude-sonnet-4-5"
)
assert "litellm_params" not in call_kwargs
assert call_kwargs["proxy_server_request"]["body"]["model"] == (
"anthropic/claude-sonnet-4-5"
)
assert call_kwargs["proxy_server_request"]["body"]["input"] == "hello"
def test_proxy_server_request_matches_metadata(self):
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
call_kwargs = {
"input": "hi",
"litellm_metadata": {"proxy_server_request": {"body": {}}},
}
ManagedResponsesWebSocketHandler._update_proxy_request(call_kwargs, "gpt-4o")
assert (
call_kwargs["proxy_server_request"]
== call_kwargs["litellm_metadata"]["proxy_server_request"]
)
class TestWebSocketEventTypes:
"""Test that all WebSocket event types are properly handled with dict-based chunks"""
def test_serialize_response_created_event_dict(self):
"""Test serialization of response.created event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.created",
"response_id": "resp_123",
"response": {
"id": "resp_123",
"object": "response",
"status": "in_progress",
"created_at": 1234567890,
},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.created" in serialized
assert "resp_123" in serialized
def test_serialize_response_in_progress_event_dict(self):
"""Test serialization of response.in_progress event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {"type": "response.in_progress", "response_id": "resp_123"}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.in_progress" in serialized
def test_serialize_output_item_added_event_dict(self):
"""Test serialization of response.output_item.added event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.output_item.added",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"item": {"type": "message", "role": "assistant"},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.output_item.added" in serialized
assert "msg_456" in serialized
def test_serialize_output_text_delta_event_dict(self):
"""Test serialization of response.output_text.delta event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.output_text.delta",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"content_index": 0,
"delta": "Hello",
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.output_text.delta" in serialized
assert "Hello" in serialized
def test_serialize_output_text_done_event_dict(self):
"""Test serialization of response.output_text.done event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.output_text.done",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"content_index": 0,
"text": "Hello world",
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.output_text.done" in serialized
assert "Hello world" in serialized
def test_serialize_content_part_done_event_dict(self):
"""Test serialization of response.content_part.done event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.content_part.done",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"content_index": 0,
"part": {"type": "output_text", "text": "Complete text"},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.content_part.done" in serialized
def test_serialize_output_item_done_event_dict(self):
"""Test serialization of response.output_item.done event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.output_item.done",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"item": {"type": "message", "role": "assistant", "status": "completed"},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.output_item.done" in serialized
assert "msg_456" in serialized
def test_serialize_response_completed_event_dict(self):
"""Test serialization of response.completed event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.completed",
"response_id": "resp_123",
"response": {
"id": "resp_123",
"status": "completed",
"output": [
{
"type": "message",
"content": [{"type": "output_text", "text": "Done"}],
}
],
},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.completed" in serialized
assert "resp_123" in serialized
def test_serialize_response_failed_event_dict(self):
"""Test serialization of response.failed event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.failed",
"response_id": "resp_123",
"response": {
"id": "resp_123",
"status": "failed",
"status_details": {"error": {"message": "Rate limit exceeded"}},
},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.failed" in serialized
assert "Rate limit exceeded" in serialized
def test_serialize_response_incomplete_event_dict(self):
"""Test serialization of response.incomplete event as dict"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.incomplete",
"response_id": "resp_123",
"response": {
"id": "resp_123",
"status": "incomplete",
"status_details": {"reason": "max_output_tokens"},
},
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.incomplete" in serialized
assert "max_output_tokens" in serialized
class TestMultiTurnSessionHistory:
"""Test multi-turn conversation handling via session history"""
def test_extract_output_messages_preserves_multiple_messages(self):
"""Test that multiple output messages are all preserved"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "First message"}],
},
{
"type": "function_call",
"id": "call_123",
"name": "get_weather",
"arguments": "{}",
},
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Second message"}],
},
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 3
assert messages[0]["content"][0]["text"] == "First message"
assert messages[1]["type"] == "function_call"
assert messages[2]["content"][0]["text"] == "Second message"
def test_input_to_messages_with_mixed_content_types(self):
"""Test input conversion with mixed content types"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
input_list = [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "Question"},
{"type": "input_image", "image_url": "https://example.com/img.png"},
],
}
]
messages = ManagedResponsesWebSocketHandler._input_to_messages(input_list)
assert len(messages) == 1
assert len(messages[0]["content"]) == 2
assert messages[0]["content"][0]["type"] == "input_text"
assert messages[0]["content"][1]["type"] == "input_image"
def test_extract_output_messages_with_mixed_text_types(self):
"""Test that both 'output_text' and 'text' types are extracted"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {
"id": "resp_123",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{"type": "output_text", "text": "Part 1"},
{"type": "text", "text": "Part 2"},
],
}
],
},
}
messages = ManagedResponsesWebSocketHandler._extract_output_messages(
completed_event
)
assert len(messages) == 1
assert messages[0]["content"][0]["text"] == "Part 1Part 2"
def test_extract_response_id_from_completed_event(self):
"""Test extraction of response ID from completed event"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {
"type": "response.completed",
"response": {"id": "resp_abc123", "status": "completed"},
}
response_id = ManagedResponsesWebSocketHandler._extract_response_id(
completed_event
)
assert response_id == "resp_abc123"
def test_extract_response_id_handles_missing_response(self):
"""Test that missing response dict returns None"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
completed_event = {"type": "response.completed"}
response_id = ManagedResponsesWebSocketHandler._extract_response_id(
completed_event
)
assert response_id is None
class TestWebSocketErrorHandling:
"""Test error handling in WebSocket mode"""
@pytest.mark.asyncio
async def test_managed_handler_handles_invalid_json(self):
"""Test that invalid JSON in response.create is handled gracefully"""
from unittest.mock import AsyncMock, MagicMock
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
mock_websocket.recv = AsyncMock(return_value="invalid json {{{")
mock_logging_obj = Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
)
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="test-model",
logging_obj=mock_logging_obj,
)
# Process invalid JSON
await handler._process_response_create("invalid json {{{")
# Should have sent an error event
mock_websocket.send_text.assert_called_once()
error_event = mock_websocket.send_text.call_args[0][0]
assert "error" in error_event
assert "Invalid JSON" in error_event
class TestWebSocketProjectQuotaEnforcement:
"""VERIA regression: the connection-level pre-call hook only runs once,
but a WebSocket connection accepts many response.create frames. Every
frame must be checked against any registered project ITPM/OTPM quota
callback, not just the first one."""
@pytest.mark.asyncio
async def test_managed_handler_blocks_frame_rejected_by_quota_callback(self, monkeypatch: pytest.MonkeyPatch):
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.exceptions import RateLimitError
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
aresponses_called = False
async def fake_aresponses(*args, **kwargs):
nonlocal aresponses_called
aresponses_called = True
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
quota_callback = MagicMock()
quota_callback.enforce_project_io_token_quota_for_frame = AsyncMock(
side_effect=RateLimitError(message="project OTPM exceeded", llm_provider="", model="")
)
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
mock_logging_obj = Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
)
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="test-model",
logging_obj=mock_logging_obj,
quota_callbacks=[quota_callback],
)
await handler._process_response_create(json.dumps({"type": "response.create", "input": "hi"}))
quota_callback.enforce_project_io_token_quota_for_frame.assert_awaited_once()
assert aresponses_called is False
mock_websocket.send_text.assert_called_once()
error_event = json.loads(mock_websocket.send_text.call_args[0][0])
assert (error_event["status"], error_event["error"]["type"]) == (429, "rate_limit_exceeded")
@pytest.mark.asyncio
async def test_managed_handler_forwards_frame_allowed_by_quota_callback(self, monkeypatch: pytest.MonkeyPatch):
from unittest.mock import AsyncMock, MagicMock
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
aresponses_called = False
async def fake_aresponses(*args, **kwargs):
nonlocal aresponses_called
aresponses_called = True
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
quota_callback = MagicMock()
quota_callback.enforce_project_io_token_quota_for_frame = AsyncMock(return_value=None)
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
mock_logging_obj = Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
)
handler = ManagedResponsesWebSocketHandler(
websocket=mock_websocket,
model="test-model",
logging_obj=mock_logging_obj,
quota_callbacks=[quota_callback],
)
await handler._process_response_create(json.dumps({"type": "response.create", "input": "hi"}))
quota_callback.enforce_project_io_token_quota_for_frame.assert_awaited_once()
assert aresponses_called is True
@pytest.mark.asyncio
async def test_native_handler_blocks_frame_rejected_by_quota_callback(self):
from unittest.mock import AsyncMock, MagicMock
from litellm.exceptions import RateLimitError
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
quota_callback = MagicMock()
quota_callback.enforce_project_io_token_quota_for_frame = AsyncMock(
side_effect=RateLimitError(message="project OTPM exceeded", llm_provider="", model="")
)
mock_backend_ws = MagicMock()
mock_backend_ws.send = AsyncMock()
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
handler = ResponsesWebSocketStreaming(
websocket=mock_websocket,
backend_ws=mock_backend_ws,
logging_obj=MagicMock(),
authorized_model="gpt-4o",
quota_callbacks=[quota_callback],
)
allowed = await handler._enforce_or_reject_frame(
json.dumps({"type": "response.create", "input": "hi"})
)
assert allowed is False
mock_backend_ws.send.assert_not_called()
mock_websocket.send_text.assert_called_once()
error_event = json.loads(mock_websocket.send_text.call_args[0][0])
assert (error_event["status"], error_event["error"]["type"]) == (429, "rate_limit_exceeded")
@pytest.mark.asyncio
async def test_native_handler_runs_the_frame_guard_on_every_turn_and_bills_each_turn_its_own_guardrail_records(
self,
):
from unittest.mock import AsyncMock, MagicMock
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame, ResponsesWebSocketStreaming
def connection_logging():
logging_obj = MagicMock()
logging_obj.litellm_params = {
"metadata": {
"standard_logging_guardrail_information": [{"guardrail_name": "admission", "guardrail_cost": 9.0}]
}
}
logging_obj.model_call_details = {}
logging_obj.copy_for_new_call.side_effect = lambda **_: connection_logging()
return logging_obj
async def guard(frame: str) -> GuardedResponsesWsFrame:
body = json.loads(frame)
return GuardedResponsesWsFrame(
frame=json.dumps({**body, "input": body["input"] + " [guarded]"}),
guardrail_information=({"guardrail_name": "turn", "guardrail_cost": 0.1 * len(body["input"])},),
)
frames = [json.dumps({"type": "response.create", "input": text}) for text in ("hi", "hello")]
mock_backend_ws = MagicMock()
mock_backend_ws.send = AsyncMock()
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
mock_websocket.receive_text = AsyncMock(side_effect=[frames[1], RuntimeError("client closed")])
handler = ResponsesWebSocketStreaming(
websocket=mock_websocket,
backend_ws=mock_backend_ws,
logging_obj=connection_logging(),
first_message=frames[0],
frame_guard=guard,
)
await handler.client_to_backend()
sent = [json.loads(call.args[0]) for call in mock_backend_ws.send.call_args_list]
assert [frame["input"] for frame in sent] == ["hi [guarded]", "hello [guarded]"]
assert [
turn.logging_obj.litellm_params["metadata"]["standard_logging_guardrail_information"]
for turn in handler._open_turns
] == [
[{"guardrail_name": "turn", "guardrail_cost": pytest.approx(0.2)}],
[{"guardrail_name": "turn", "guardrail_cost": pytest.approx(0.5)}],
]
@pytest.mark.asyncio
async def test_native_handler_drops_a_frame_the_guard_rejects_and_keeps_the_socket_open(self):
from unittest.mock import AsyncMock, MagicMock
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame, ResponsesWebSocketStreaming
async def guard(frame: str) -> GuardedResponsesWsFrame:
if "forbidden" in frame:
raise ValueError("turn guardrail blocked the request")
return GuardedResponsesWsFrame(frame=frame)
blocked = json.dumps({"type": "response.create", "input": "forbidden"})
allowed = json.dumps({"type": "response.create", "input": "fine"})
mock_backend_ws = MagicMock()
mock_backend_ws.send = AsyncMock()
mock_websocket = MagicMock()
mock_websocket.send_text = AsyncMock()
mock_websocket.receive_text = AsyncMock(side_effect=[allowed, RuntimeError("client closed")])
logging_obj = MagicMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = ResponsesWebSocketStreaming(
websocket=mock_websocket,
backend_ws=mock_backend_ws,
logging_obj=logging_obj,
first_message=blocked,
frame_guard=guard,
)
await handler.client_to_backend()
error_event = json.loads(mock_websocket.send_text.call_args[0][0])
assert error_event["type"] == "error"
assert error_event["error"] == {
"type": "invalid_request_error",
"message": "turn guardrail blocked the request",
}
assert [json.loads(call.args[0])["input"] for call in mock_backend_ws.send.call_args_list] == ["fine"]
assert len(handler._open_turns) == 1
@pytest.mark.asyncio
async def test_native_handler_forwards_frame_allowed_by_quota_callback(self):
from unittest.mock import AsyncMock, MagicMock
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
quota_callback = MagicMock()
quota_callback.enforce_project_io_token_quota_for_frame = AsyncMock(return_value=None)
handler = ResponsesWebSocketStreaming(
websocket=MagicMock(),
backend_ws=MagicMock(),
logging_obj=MagicMock(),
authorized_model="gpt-4o",
quota_callbacks=[quota_callback],
)
allowed = await handler._enforce_or_reject_frame(
json.dumps({"type": "response.create", "input": "hi"})
)
assert allowed is True
quota_callback.enforce_project_io_token_quota_for_frame.assert_awaited_once()
_TURN_USAGE: Final = {"input_tokens": 20, "output_tokens": 15, "total_tokens": 35}
def _turn_frames() -> tuple[str, str, str]:
return tuple(json.dumps({"type": "response.create", "input": word}) for word in ("one", "two", "three"))
def _admission_refusing_the_next_turn():
from unittest.mock import AsyncMock
from litellm.exceptions import RateLimitError
return AsyncMock(side_effect=[RateLimitError(message="crossed budget", llm_provider="", model=""), {}])
class _TokenLimits:
"""A proxy hook whose per-turn token check answers each later turn with the next outcome."""
def __init__(self, *outcomes: Exception | None) -> None:
self._outcomes: Final = iter(outcomes)
self.checked: Final[list[tuple[object, str | None]]] = []
async def enforce_token_limits_for_frame(self, user_api_key_dict: object, requested_model: str | None) -> None:
self.checked.append((user_api_key_dict, requested_model))
outcome: Final = next(self._outcomes)
if outcome is not None:
raise outcome
def _out_of_tokens() -> Exception:
from litellm.exceptions import RateLimitError
return RateLimitError(message="key is out of tokens", llm_provider="", model="")
def _counters_unverifiable() -> Exception:
from litellm.exceptions import ServiceUnavailableError
return ServiceUnavailableError(message="counters could not be verified", llm_provider="litellm_proxy", model="")
_TURN_REFUSALS: Final = pytest.mark.parametrize(
"refusal, refusal_frame",
[(_out_of_tokens(), (429, "rate_limit_exceeded")), (_counters_unverifiable(), (503, "server_error"))],
ids=["out-of-tokens", "counters-unverifiable"],
)
class _ClientSocket:
"""A client socket that, like Starlette's, stops receiving once the server closes it."""
def __init__(self, *frames: str) -> None:
self._frames: Final = iter(frames)
self.sent: Final[list[dict[str, object]]] = []
self.close_code: int | None = None
async def send_text(self, data: str) -> None:
self.sent.append(json.loads(data))
async def receive_text(self) -> str:
frame: Final = next(self._frames, None)
if self.close_code is not None or frame is None:
raise RuntimeError("WebSocket is not connected")
return frame
async def close(self, code: int = 1000, reason: str | None = None) -> None:
self.close_code = code
class _StalledClientSocket(_ClientSocket):
"""A client socket whose sends never finish, like a client that stopped reading."""
def __init__(self, *frames: str) -> None:
super().__init__(*frames)
self.send_started: Final = asyncio.Event()
async def send_text(self, data: str) -> None:
self.send_started.set()
await asyncio.Event().wait()
def _admission_crashing_the_next_turn():
from unittest.mock import AsyncMock
return AsyncMock(side_effect=[ValueError("custom check failed"), {}])
def _guard_blocking(word: str):
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame
async def guard(frame: str) -> GuardedResponsesWsFrame:
if word in json.loads(frame)["input"]:
raise ValueError("blocked by guardrail")
return GuardedResponsesWsFrame(frame=frame)
return guard
def _guard_recording(bill_refusal: AsyncMock):
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame
async def guard(frame: str) -> GuardedResponsesWsFrame:
return GuardedResponsesWsFrame(
frame=frame, guardrail_information=({"guardrail_cost": 0.5},), bill_refusal=bill_refusal
)
return guard
_OPENED_ON: Final = UsageCounter("global_router", "ws-dep", "openai/gpt-5-mini", "12-34", "otpm")
_TURNED_ON: Final = UsageCounter("global_router", "ws-dep", "openai/gpt-5-mini", "12-35", "otpm")
_OPENED_AT: Final = datetime(2026, 1, 1, 12, 34, 56, tzinfo=timezone.utc)
_TURNED_AT: Final = datetime(2026, 1, 1, 12, 35, 5, tzinfo=timezone.utc)
_WS_DEPLOYMENT: Final = {
"litellm_params": {"model": "openai/gpt-5-mini", "otpm": 4096},
"model_info": {"id": "ws-dep"},
}
_OTHER_USAGE: Final = 10
_OUTPUT_TOKENS_PER_TURN: Final = 2
_UPSTREAM_ERROR: Final = json.dumps({"type": "error", "error": {"type": "server_error", "message": "upstream failed"}})
def _turn_completed() -> str:
return json.dumps(
{
"type": "response.completed",
"response": {
"id": "resp_turn",
"status": "completed",
"output": [],
"usage": {"input_tokens": 5, "output_tokens": _OUTPUT_TOKENS_PER_TURN, "total_tokens": 7},
},
}
)
async def _socket_opened_on(usage: RouterUsageStore) -> Mapping[str, object]:
from litellm.router_utils.pre_call_checks.io_token_rate_limit_check import async_admit_io_token_turn
usage.increment_local(CounterIncrement(_OPENED_ON, _OTHER_USAGE, 60))
usage.increment_local(CounterIncrement(_TURNED_ON, _OTHER_USAGE, 60))
return await async_admit_io_token_turn(usage, _WS_DEPLOYMENT, _OPENED_AT)
def _turns_finish_at(monkeypatch: pytest.MonkeyPatch, finished_at: datetime) -> None:
monkeypatch.setattr(
"litellm.router_utils.pre_call_checks.io_token_rate_limit_check.get_utc_datetime", lambda: finished_at
)
def _later_turns_admitted_through(usage: RouterUsageStore) -> "ResponsesWsTurnAdmission":
from litellm.router_utils.pre_call_checks.io_token_rate_limit_check import async_admit_io_token_turn
return partial(async_admit_io_token_turn, usage, _WS_DEPLOYMENT, _TURNED_AT)
_ITPM_OPENED_ON: Final = UsageCounter("global_router", "ws-dep", "openai/gpt-5-mini", "12-34", "itpm")
_ITPM_DEPLOYMENT: Final = {
"litellm_params": {"model": "openai/gpt-5-mini", "itpm": 40_000},
"model_info": {"id": "ws-dep"},
}
_TURN_INPUT_TOKENS: Final = 1_000
def _turn_completed_reading_cache(cached_tokens: int) -> str:
return json.dumps(
{
"type": "response.completed",
"response": {
"id": "resp_cached_turn",
"status": "completed",
"output": [],
"usage": {
"input_tokens": _TURN_INPUT_TOKENS,
"input_tokens_details": {"cached_tokens": cached_tokens},
"output_tokens": _OUTPUT_TOKENS_PER_TURN,
"total_tokens": _TURN_INPUT_TOKENS + _OUTPUT_TOKENS_PER_TURN,
},
},
}
)
def _memory_usage() -> RouterUsageStore:
return RouterUsageStore(connect(None).router_usage())
def _rate_limit_check(usage: RouterUsageStore) -> "ModelRateLimitingCheck":
from litellm.router_utils.pre_call_checks.model_rate_limit_check import ModelRateLimitingCheck
return ModelRateLimitingCheck(usage=usage)
def _connection_logged_through(rate_limits: "ModelRateLimitingCheck", opened_with: Mapping[str, object]) -> "Logging":
import time
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.types.utils import CallTypes
connection: Final = Logging(
model="gpt-5-mini",
messages=[],
stream=False,
call_type=CallTypes.aresponses_websocket.value,
start_time=time.time(),
litellm_call_id="connection-call",
function_id="connection-call",
dynamic_async_success_callbacks=[rate_limits],
dynamic_async_failure_callbacks=[rate_limits],
)
connection.update_environment_variables(
litellm_params={"metadata": dict(opened_with), CallTypes.aresponses_websocket.value: True},
optional_params={},
)
return connection
def _provider_turn_stream(_request: httpx.Request) -> httpx.Response:
completed: Final = {
"id": "resp_turn",
"object": "response",
"created_at": 1767271505,
"status": "completed",
"model": "gpt-5-mini",
"output": [],
"parallel_tool_calls": True,
"tool_choice": "auto",
"tools": [],
"usage": {"input_tokens": 5, "output_tokens": _OUTPUT_TOKENS_PER_TURN, "total_tokens": 7},
}
return httpx.Response(
200,
headers={"content-type": "text/event-stream"},
text="".join(
f"event: {kind}\ndata: {json.dumps({'type': kind, 'response': completed})}\n\n"
for kind in ("response.created", "response.completed")
),
)
class _ProviderResponsesSocket:
"""A provider's native Responses socket that answers each ``response.create`` with a completed turn."""
def __init__(self) -> None:
self.sent: Final[list[dict[str, object]]] = []
self._replies: Final[asyncio.Queue[str]] = asyncio.Queue()
def connect(self, _url: str, **_kwargs: object) -> "_ProviderResponsesSocket":
return self
async def __aenter__(self) -> "_ProviderResponsesSocket":
return self
async def __aexit__(self, *_exc_info: object) -> None:
return None
async def send(self, message: str) -> None:
self.sent.append(json.loads(message))
await self._replies.put(_turn_completed())
async def recv(self, decode: bool = False) -> str:
return await self._replies.get()
async def close(self) -> None:
return None
class _TwoOutputTokenTurns(CustomLLM):
def __init__(self, failing_turns: frozenset[int] = frozenset()) -> None:
super().__init__()
self._failing_turns: Final = failing_turns
self._turns: Final = itertools.count(1)
async def astreaming(self, *args: object, **kwargs: object) -> AsyncIterator[GenericStreamingChunk]:
if next(self._turns) in self._failing_turns:
raise RuntimeError("upstream failed")
yield GenericStreamingChunk(
text="hi",
is_finished=True,
finish_reason="stop",
index=0,
tool_use=None,
usage={"prompt_tokens": 5, "completion_tokens": _OUTPUT_TOKENS_PER_TURN, "total_tokens": 7},
)
async def _run_managed_relay(
monkeypatch: pytest.MonkeyPatch,
provider: CustomLLM,
rate_limits: "ModelRateLimitingCheck",
frames: tuple[str, ...],
turn_admission: "ResponsesWsTurnAdmission | None",
opened_with: Mapping[str, object],
) -> _ClientSocket:
import litellm
monkeypatch.setattr(litellm, "custom_provider_map", [{"provider": "ws-turn-llm", "custom_handler": provider}])
return await _relay_turns_to(monkeypatch, "ws-turn-llm/turns", rate_limits, frames, turn_admission, opened_with)
async def _relay_turns_to(
monkeypatch: pytest.MonkeyPatch,
model: str,
rate_limits: "ModelRateLimitingCheck",
frames: tuple[str, ...],
turn_admission: "ResponsesWsTurnAdmission | None",
opened_with: Mapping[str, object],
**connection: object,
) -> _ClientSocket:
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.responses.streaming_iterator import ManagedResponsesWebSocketHandler, drain_logging_tasks
monkeypatch.setattr(litellm, "callbacks", [rate_limits])
first, *later = frames
websocket: Final = _ClientSocket(*later)
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model=model,
logging_obj=Logging(
model=model,
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
litellm_metadata={"user_api_key_hash": "k1", **opened_with},
first_message=first,
turn_admission=turn_admission,
**connection,
)
await handler.run()
await drain_logging_tasks()
await asyncio.sleep(0)
await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10.0)
return websocket
def _errors(websocket: _ClientSocket) -> list[tuple[object, object]]:
return [(frame.get("status"), frame["error"]) for frame in websocket.sent if frame.get("type") == "error"]
class _BackendSending:
"""A provider socket that sends these events, then closes."""
def __init__(self, *events: Mapping[str, object]) -> None:
self.events: Final = list(events)
async def recv(self, decode: bool = False) -> str:
import websockets.exceptions
if not self.events:
raise websockets.exceptions.ConnectionClosed(None, None)
return json.dumps(self.events.pop(0))
def _turn_logged_on_deployment(deployment_id: str) -> MagicMock:
logging_obj: Final = MagicMock()
logging_obj.litellm_params = {"litellm_metadata": {"model_info": {"id": deployment_id}}}
logging_obj.copy_for_new_call.return_value = logging_obj
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.dispatch_failure_handlers = AsyncMock()
return logging_obj
def _logged_event_types(logging_obj: MagicMock) -> list[list[object]]:
return [[event["type"] for event in call.args[0]] for call in logging_obj.dispatch_success_handlers.call_args_list]
class TestWebSocketTurnAdmission:
"""A turn after the connection's first is admitted by the deployment again before it reaches the provider."""
@pytest.mark.asyncio
@pytest.mark.parametrize(
("terminal_event", "counted_before_it_reaches_the_client"),
[
({"type": "response.completed", "response": {"usage": _TURN_USAGE}}, [("ws-dep", 35)]),
({"type": "response.incomplete", "response": {"usage": _TURN_USAGE}}, [("ws-dep", 35)]),
({"type": "response.failed", "response": {"usage": _TURN_USAGE, "error": {"code": "server_error"}}}, []),
],
)
async def test_native_relay_counts_a_finished_turn_before_forwarding_its_terminal_event(
self, terminal_event: dict[str, object], counted_before_it_reaches_the_client: list[tuple[object, int]]
):
counted: Final[list[tuple[object, int]]] = []
async def record_turn_usage(turn_litellm_params: Mapping[str, object], total_tokens: int) -> None:
await asyncio.sleep(0)
metadata: Final = turn_litellm_params["litellm_metadata"]
assert isinstance(metadata, dict)
counted.append((metadata["model_info"]["id"], total_tokens))
class Client:
def __init__(self) -> None:
self.seen: Final[list[tuple[object, list[tuple[object, int]]]]] = []
async def send_text(self, data: str) -> None:
self.seen.append((json.loads(data)["type"], list(counted)))
client: Final = Client()
handler: Final = _make_streaming(
websocket=client,
backend_ws=_BackendSending({"type": "response.created", "response": {}}, terminal_event),
logging_obj=_turn_logged_on_deployment("ws-dep"),
turn_usage_recorder=record_turn_usage,
)
await handler.backend_to_client()
assert client.seen == [
("response.created", []),
(terminal_event["type"], counted_before_it_reaches_the_client),
]
@pytest.mark.asyncio
async def test_native_relay_forwards_and_logs_a_finished_turn_whose_usage_it_cannot_read(self):
recorded: Final[list[int]] = []
async def record_turn_usage(turn_litellm_params: Mapping[str, object], total_tokens: int) -> None:
recorded.append(total_tokens)
unreadable_usage: Final = {"input_tokens": None, "output_tokens": 3, "total_tokens": 3}
client: Final = _ClientSocket()
logging_obj: Final = _turn_logged_on_deployment("ws-dep")
handler: Final = _make_streaming(
websocket=client,
backend_ws=_BackendSending(
{"type": "response.created", "response": {}},
{"type": "response.completed", "response": {"usage": unreadable_usage}},
),
logging_obj=logging_obj,
turn_usage_recorder=record_turn_usage,
)
await handler.backend_to_client()
assert [event["type"] for event in client.sent] == ["response.created", "response.completed"]
assert _logged_event_types(logging_obj) == [["response.created", "response.completed"]]
assert recorded == []
@pytest.mark.asyncio
async def test_native_relay_finishes_counting_a_turn_before_logging_it_when_the_client_leaves(self):
counting: Final = asyncio.Event()
count_written: Final = asyncio.Event()
counted: Final[list[int]] = []
async def record_turn_usage_slowly(turn_litellm_params: Mapping[str, object], total_tokens: int) -> None:
counting.set()
await count_written.wait()
counted.append(total_tokens)
logging_obj: Final = _turn_logged_on_deployment("ws-dep")
handler: Final = _make_streaming(
websocket=_ClientSocket(),
backend_ws=_BackendSending(
{"type": "response.created", "response": {}},
{"type": "response.completed", "response": {"usage": _TURN_USAGE}},
),
logging_obj=logging_obj,
turn_usage_recorder=record_turn_usage_slowly,
)
relay: Final = asyncio.create_task(handler.backend_to_client())
await asyncio.wait_for(counting.wait(), timeout=5)
relay.cancel()
_ = await asyncio.wait((relay,), timeout=0.1)
logged_while_counting: Final = _logged_event_types(logging_obj)
count_written.set()
with pytest.raises(asyncio.CancelledError):
await relay
assert logged_while_counting == []
assert counted == [35]
assert _logged_event_types(logging_obj) == [["response.created", "response.completed"]]
@pytest.mark.asyncio
async def test_native_relay_drops_a_later_turn_the_deployment_refuses(self):
from unittest.mock import AsyncMock
first, second, third = _turn_frames()
cancel: Final = json.dumps({"type": "response.cancel"})
turn_admission: Final = _admission_refusing_the_next_turn()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
websocket.receive_text = AsyncMock(side_effect=[second, cancel, third, Exception("stop")])
handler: Final = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
request_data={},
first_message=first,
turn_admission=turn_admission,
)
await handler.client_to_backend()
assert [json.loads(call.args[0]) for call in backend_ws.send.await_args_list] == [
json.loads(first),
json.loads(cancel),
json.loads(third),
]
assert turn_admission.await_count == 2
refusal: Final = json.loads(websocket.send_text.await_args.args[0])
assert refusal["status"] == 429
assert refusal["error"]["type"] == "rate_limit_exceeded"
assert "crossed budget" in refusal["error"]["message"]
@pytest.mark.asyncio
async def test_native_relay_reports_a_refused_turn_as_the_socket_failure(self):
from unittest.mock import AsyncMock
from litellm.exceptions import RateLimitError
first, second, _ = _turn_frames()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
backend_ws.close = AsyncMock()
backend_ws.recv = AsyncMock(side_effect=Exception("stop"))
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
websocket.receive_text = AsyncMock(side_effect=[second, Exception("client gone")])
handler: Final = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
request_data={},
first_message=first,
turn_admission=_admission_refusing_the_next_turn(),
)
failure: Final = await handler.bidirectional_forward()
assert isinstance(failure, RateLimitError)
assert "crossed budget" in str(failure)
@pytest.mark.asyncio
@pytest.mark.parametrize(
("first_turn_end", "first_turn_tokens"),
[
pytest.param(_turn_completed(), _OUTPUT_TOKENS_PER_TURN, id="first_turn_completed"),
pytest.param(_UPSTREAM_ERROR, 0, id="first_turn_failed"),
],
)
async def test_native_relay_counts_every_turn_on_the_minute_it_finishes(
self, first_turn_end: str, first_turn_tokens: int, monkeypatch: pytest.MonkeyPatch
) -> None:
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
from litellm.responses.streaming_iterator import drain_logging_tasks
_turns_finish_at(monkeypatch, _TURNED_AT)
usage: Final = _memory_usage()
opened_with: Final = await _socket_opened_on(usage)
first, second, third = _turn_frames()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
backend_ws.recv = AsyncMock(
side_effect=[first_turn_end, _turn_completed(), _turn_completed(), Exception("stop")]
)
handler: Final = _make_streaming(
websocket=_ClientSocket(second, third),
backend_ws=backend_ws,
request_data={},
logging_obj=_connection_logged_through(_rate_limit_check(usage), opened_with),
first_message=first,
turn_admission=_later_turns_admitted_through(usage),
)
await handler.client_to_backend()
await handler.backend_to_client()
await drain_logging_tasks()
assert usage.get_local(_OPENED_ON) == _OTHER_USAGE
assert (
usage.get_local(_TURNED_ON)
== _OTHER_USAGE + first_turn_tokens + 2 * _OUTPUT_TOKENS_PER_TURN
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
("cached_tokens", "counted_input_tokens"),
[
pytest.param(800, _TURN_INPUT_TOKENS - 800, id="cached_input"),
pytest.param(0, _TURN_INPUT_TOKENS, id="uncached_input"),
],
)
async def test_native_relay_leaves_a_turn_s_cached_input_out_of_the_deployment_s_itpm(
self, cached_tokens: int, counted_input_tokens: int, monkeypatch: pytest.MonkeyPatch
) -> None:
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
from litellm.responses.streaming_iterator import drain_logging_tasks
from litellm.router_utils.pre_call_checks.io_token_rate_limit_check import async_admit_io_token_turn
_turns_finish_at(monkeypatch, _OPENED_AT)
usage: Final = _memory_usage()
opened_with: Final = await async_admit_io_token_turn(usage, _ITPM_DEPLOYMENT, _OPENED_AT)
first, _, _ = _turn_frames()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
backend_ws.recv = AsyncMock(side_effect=[_turn_completed_reading_cache(cached_tokens), Exception("stop")])
handler: Final = _make_streaming(
websocket=_ClientSocket(),
backend_ws=backend_ws,
request_data={},
logging_obj=_connection_logged_through(_rate_limit_check(usage), opened_with),
first_message=first,
)
await handler.client_to_backend()
await handler.backend_to_client()
await drain_logging_tasks()
assert usage.get_local(_ITPM_OPENED_ON) == counted_input_tokens
@pytest.mark.asyncio
@pytest.mark.parametrize(
("failing_turns", "first_turn_tokens"),
[
pytest.param(frozenset(), _OUTPUT_TOKENS_PER_TURN, id="first_turn_completed"),
pytest.param(frozenset({1}), 0, id="first_turn_failed"),
],
)
async def test_managed_relay_counts_every_turn_on_the_minute_it_finishes(
self, monkeypatch: pytest.MonkeyPatch, failing_turns: frozenset[int], first_turn_tokens: int
) -> None:
_turns_finish_at(monkeypatch, _TURNED_AT)
usage: Final = _memory_usage()
opened_with: Final = await _socket_opened_on(usage)
await _run_managed_relay(
monkeypatch,
_TwoOutputTokenTurns(failing_turns),
_rate_limit_check(usage),
_turn_frames(),
_later_turns_admitted_through(usage),
opened_with,
)
assert usage.get_local(_OPENED_ON) == _OTHER_USAGE
assert (
usage.get_local(_TURNED_ON)
== _OTHER_USAGE + first_turn_tokens + 2 * _OUTPUT_TOKENS_PER_TURN
)
@pytest.mark.asyncio
async def test_managed_relay_sends_the_provider_only_the_metadata_each_turn_carries(
self, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter
) -> None:
import litellm
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
litellm.in_memory_llm_clients_cache.flush_cache()
_turns_finish_at(monkeypatch, _TURNED_AT)
provider: Final = respx_mock.post("https://api.openai.com/v1/responses").mock(side_effect=_provider_turn_stream)
client_metadata: Final = {"session": "abc", "team": "search"}
usage: Final = _memory_usage()
await _relay_turns_to(
monkeypatch,
"openai/gpt-5-mini",
_rate_limit_check(usage),
tuple(
json.dumps({"type": "response.create", "input": word, "metadata": client_metadata})
for word in ("one", "two")
),
_later_turns_admitted_through(usage),
await _socket_opened_on(usage),
api_key="sk-fake",
)
assert [json.loads(call.request.read()).get("metadata") for call in provider.calls] == [
client_metadata,
client_metadata,
]
assert usage.get_local(_TURNED_ON) == _OTHER_USAGE + 2 * _OUTPUT_TOKENS_PER_TURN
@pytest.mark.asyncio
async def test_native_relay_sends_the_provider_only_the_metadata_the_socket_opened_with(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
from unittest.mock import patch
from litellm import Router
monkeypatch.setenv("LITELLM_RUST", "false")
provider: Final = _ProviderResponsesSocket()
client_metadata: Final = {"session": "abc", "team": "search"}
first, second, _ = _turn_frames()
router: Final = Router(
model_list=[
{
"model_name": "ws-io",
"litellm_params": {
"model": "openai/gpt-5-mini",
"api_key": "sk-fake",
"itpm": 40_000,
"otpm": 4096,
},
"model_info": {"id": "ws-dep"},
}
],
optional_pre_call_checks=["enforce_model_rate_limits"],
)
with patch("websockets.connect", provider.connect):
await router._aresponses_websocket(
model="ws-io",
websocket=_ClientSocket(second),
first_message=first,
metadata=dict(client_metadata),
)
assert [frame.get("metadata") for frame in provider.sent] == [client_metadata, client_metadata]
@pytest.mark.asyncio
async def test_managed_relay_skips_a_later_turn_the_deployment_refuses(self, monkeypatch: pytest.MonkeyPatch):
from unittest.mock import AsyncMock
import litellm
from litellm.exceptions import RateLimitError
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import ManagedResponsesWebSocketHandler
answered: Final[list[object]] = []
async def fake_aresponses(*args: object, **kwargs: object):
answered.append(kwargs.get("input"))
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
first, second, third = _turn_frames()
turn_admission: Final = _admission_refusing_the_next_turn()
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
websocket.receive_text = AsyncMock(side_effect=[second, third, Exception("stop")])
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model="test-model",
logging_obj=Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
first_message=first,
turn_admission=turn_admission,
)
failure: Final = await handler.run()
assert len(answered) == 2
assert "two" not in json.dumps(answered)
assert turn_admission.await_count == 2
assert isinstance(failure, RateLimitError)
assert "crossed budget" in str(failure)
refusals: Final = [
json.loads(call.args[0])
for call in websocket.send_text.await_args_list
if json.loads(call.args[0]).get("type") == "error"
]
assert [(refusal["status"], refusal["error"]["type"]) for refusal in refusals] == [(429, "rate_limit_exceeded")]
@pytest.mark.asyncio
@_TURN_REFUSALS
async def test_managed_socket_checks_token_limits_before_every_later_turn_and_marks_each_turn(
self, monkeypatch: pytest.MonkeyPatch, refusal: Exception, refusal_frame: tuple[int, str]
) -> None:
import litellm
from litellm.constants import RESPONSES_WEBSOCKET_CALL_ID_METADATA_KEY
from litellm.litellm_core_utils.core_helpers import as_str_mapping
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.proxy._types import UserAPIKeyAuth
answered: Final[list[tuple[str, object]]] = []
async def fake_aresponses(*args: object, **kwargs: object):
turn_metadata: Final = as_str_mapping(kwargs.get("litellm_metadata"))
answered.append(
(
json.dumps(kwargs.get("input")),
None if turn_metadata is None else turn_metadata.get(RESPONSES_WEBSOCKET_CALL_ID_METADATA_KEY),
)
)
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
token_limits: Final = _TokenLimits(refusal, None)
monkeypatch.setattr(litellm, "callbacks", [token_limits])
deployment_admission: Final = AsyncMock(return_value={})
user_api_key_dict: Final = UserAPIKeyAuth(api_key="hashed-key", tpm_limit=1000)
first, second, third = _turn_frames()
websocket: Final = _ClientSocket(second, third)
await BaseLLMHTTPHandler().async_responses_websocket(
model="anthropic/claude-sonnet-4-5",
websocket=websocket,
logging_obj=Logging(
model="anthropic/claude-sonnet-4-5",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="socket-open",
function_id="test-func",
),
responses_api_provider_config=None,
user_api_key_dict=user_api_key_dict,
litellm_metadata={"model_group": "claude-ws"},
first_message=first,
turn_admission=deployment_admission,
)
assert [("two" in turn_input, "three" in turn_input) for turn_input, _ in answered] == [
(False, False),
(False, True),
]
assert [socket_call_id for _, socket_call_id in answered] == ["socket-open", "socket-open"]
assert token_limits.checked == [(user_api_key_dict, "claude-ws"), (user_api_key_dict, "claude-ws")]
assert deployment_admission.await_count == 1
assert [(status, error["type"]) for status, error in _errors(websocket)] == [refusal_frame]
@pytest.mark.asyncio
@_TURN_REFUSALS
@pytest.mark.parametrize(
"keyed, forwarded, refused",
[(True, ["one", "three"], True), (False, ["one", "two", "three"], False)],
ids=["keyed", "keyless"],
)
async def test_native_socket_checks_token_limits_before_every_later_turn_of_a_keyed_socket(
self,
monkeypatch: pytest.MonkeyPatch,
keyed: bool,
forwarded: list[str],
refused: bool,
refusal: Exception,
refusal_frame: tuple[int, str],
) -> None:
from unittest.mock import patch
import litellm
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.proxy._types import UserAPIKeyAuth
token_limits: Final = _TokenLimits(refusal, None)
monkeypatch.setattr(litellm, "callbacks", [token_limits])
provider: Final = _ProviderResponsesSocket()
config: Final = MagicMock(spec=OpenAIResponsesAPIConfig)
config.supports_native_websocket.return_value = True
config.model_in_websocket_url.return_value = True
config.get_websocket_url.return_value = "wss://api.openai.com/v1/responses"
config.validate_environment.return_value = {}
logging_obj: Final = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
user_api_key_dict: Final = UserAPIKeyAuth(api_key="hashed-key", tpm_limit=1000) if keyed else None
first, second, third = _turn_frames()
websocket: Final = _ClientSocket(second, third)
with patch("websockets.connect", provider.connect):
await BaseLLMHTTPHandler().async_responses_websocket(
model="gpt-5.4",
websocket=websocket,
logging_obj=logging_obj,
responses_api_provider_config=config,
api_key="sk-test",
user_api_key_dict=user_api_key_dict,
first_message=first,
)
assert [frame["input"] for frame in provider.sent] == forwarded
assert token_limits.checked == ([(user_api_key_dict, "gpt-5.4")] * 2 if keyed else [])
assert [(status, error["type"]) for status, error in _errors(websocket)] == ([refusal_frame] if refused else [])
@pytest.mark.asyncio
async def test_native_relay_runs_the_guardrail_before_the_deployment_counts_a_turn(self):
from unittest.mock import AsyncMock
first, second, third = _turn_frames()
turn_admission: Final = _admission_refusing_the_next_turn()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
websocket: Final = _ClientSocket(second, third)
handler: Final = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
request_data={},
first_message=first,
frame_guard=_guard_blocking("two"),
turn_admission=turn_admission,
)
await handler.client_to_backend()
assert [json.loads(call.args[0]) for call in backend_ws.send.await_args_list] == [json.loads(first)]
assert turn_admission.await_count == 1
assert [(status, error["type"]) for status, error in _errors(websocket)] == [
(None, "invalid_request_error"),
(429, "rate_limit_exceeded"),
]
@pytest.mark.asyncio
async def test_managed_relay_runs_the_guardrail_before_the_deployment_counts_a_turn(
self, monkeypatch: pytest.MonkeyPatch
):
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import ManagedResponsesWebSocketHandler
answered: Final[list[object]] = []
async def fake_aresponses(*args: object, **kwargs: object):
answered.append(kwargs.get("input"))
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
first, second, third = _turn_frames()
turn_admission: Final = _admission_refusing_the_next_turn()
websocket: Final = _ClientSocket(second, third)
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model="test-model",
logging_obj=Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
first_message=first,
frame_guard=_guard_blocking("two"),
turn_admission=turn_admission,
)
await handler.run()
assert answered == ["one"]
assert turn_admission.await_count == 1
assert [(status, error["type"]) for status, error in _errors(websocket)] == [
(None, "invalid_request_error"),
(429, "rate_limit_exceeded"),
]
@pytest.mark.asyncio
async def test_native_relay_bills_a_refused_turn_and_returns_it_as_the_close_time_failure(self):
from unittest.mock import AsyncMock
from litellm.exceptions import RateLimitError
first, second, third = _turn_frames()
refusal: Final = RateLimitError(message="crossed budget", llm_provider="", model="")
bill_refusal: Final = AsyncMock()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
backend_ws.close = AsyncMock()
backend_ws.recv = AsyncMock(side_effect=asyncio.Event().wait)
handler: Final = _make_streaming(
websocket=_ClientSocket(second, third),
backend_ws=backend_ws,
request_data={},
first_message=first,
frame_guard=_guard_recording(bill_refusal),
turn_admission=AsyncMock(side_effect=[refusal, {}]),
)
close_time_failure: Final = await handler.bidirectional_forward()
assert [json.loads(sent.args[0])["input"] for sent in backend_ws.send.await_args_list] == ["one", "three"]
bill_refusal.assert_awaited_once_with(refusal)
assert close_time_failure is refusal
@pytest.mark.asyncio
async def test_native_relay_forwards_no_later_turn_until_the_refused_turn_is_billed(self):
from unittest.mock import AsyncMock
from litellm.exceptions import RateLimitError
first, second, third = _turn_frames()
events: Final[list[str]] = []
async def bill_refusal(rejection: Exception) -> None:
await asyncio.sleep(0.01)
events.append("billed")
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock(side_effect=lambda frame: events.append(json.loads(frame)["input"]))
backend_ws.close = AsyncMock()
backend_ws.recv = AsyncMock(side_effect=asyncio.Event().wait)
handler: Final = _make_streaming(
websocket=_ClientSocket(second, third),
backend_ws=backend_ws,
request_data={},
first_message=first,
frame_guard=_guard_recording(AsyncMock(side_effect=bill_refusal)),
turn_admission=AsyncMock(
side_effect=[RateLimitError(message="crossed budget", llm_provider="", model=""), {}]
),
)
_ = await handler.bidirectional_forward()
assert events == ["one", "billed", "three"]
@pytest.mark.asyncio
async def test_a_refused_turn_is_recorded_even_when_the_relay_is_cancelled_while_answering_it(self):
from unittest.mock import AsyncMock
from litellm.exceptions import RateLimitError
first, second, third = _turn_frames()
refusal: Final = RateLimitError(message="crossed budget", llm_provider="", model="")
bill_refusal: Final = AsyncMock()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
backend_ws.close = AsyncMock()
backend_ws.recv = AsyncMock(side_effect=asyncio.Event().wait)
client: Final = _StalledClientSocket(second, third)
handler: Final = _make_streaming(
websocket=client,
backend_ws=backend_ws,
request_data={},
first_message=first,
frame_guard=_guard_recording(bill_refusal),
turn_admission=AsyncMock(side_effect=[refusal, {}]),
)
relay: Final = asyncio.ensure_future(handler.bidirectional_forward())
await asyncio.wait_for(client.send_started.wait(), timeout=1)
relay.cancel()
with pytest.raises(asyncio.CancelledError):
await relay
bill_refusal.assert_awaited_once_with(refusal)
@pytest.mark.asyncio
async def test_managed_relay_bills_a_refused_turn_and_returns_it_as_the_close_time_failure(
self, monkeypatch: pytest.MonkeyPatch
):
from unittest.mock import AsyncMock
import litellm
from litellm.exceptions import RateLimitError
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import ManagedResponsesWebSocketHandler
answered: Final[list[object]] = []
async def fake_aresponses(*args: object, **kwargs: object):
answered.append(kwargs.get("input"))
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
first, second, third = _turn_frames()
refusal: Final = RateLimitError(message="crossed budget", llm_provider="", model="")
bill_refusal: Final = AsyncMock()
handler: Final = ManagedResponsesWebSocketHandler(
websocket=_ClientSocket(second, third),
model="test-model",
logging_obj=Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
first_message=first,
frame_guard=_guard_recording(bill_refusal),
turn_admission=AsyncMock(side_effect=[refusal, {}]),
)
close_time_failure: Final = await handler.run()
assert answered == ["one", "three"]
bill_refusal.assert_awaited_once_with(refusal)
assert close_time_failure is refusal
@pytest.mark.asyncio
async def test_native_relay_answers_a_crashed_turn_check_with_a_500_and_keeps_serving(self):
from unittest.mock import AsyncMock
first, second, third = _turn_frames()
backend_ws: Final = MagicMock()
backend_ws.send = AsyncMock()
backend_ws.close = AsyncMock()
backend_ws.recv = AsyncMock(side_effect=asyncio.Event().wait)
websocket: Final = _ClientSocket(second, third)
handler: Final = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
request_data={},
first_message=first,
turn_admission=_admission_crashing_the_next_turn(),
)
failure: Final = await handler.bidirectional_forward()
assert isinstance(failure, ValueError)
assert [json.loads(call.args[0]) for call in backend_ws.send.await_args_list] == [
json.loads(first),
json.loads(third),
]
assert _errors(websocket) == [(500, {"type": "server_error", "message": "custom check failed"})]
assert websocket.close_code is None
@pytest.mark.asyncio
async def test_managed_relay_answers_a_crashed_turn_check_with_a_500_and_keeps_serving(
self, monkeypatch: pytest.MonkeyPatch
):
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.responses.streaming_iterator import ManagedResponsesWebSocketHandler
answered: Final[list[object]] = []
async def fake_aresponses(*args: object, **kwargs: object):
answered.append(kwargs.get("input"))
async def _empty():
return
yield
return _empty()
monkeypatch.setattr(litellm, "aresponses", fake_aresponses)
first, second, third = _turn_frames()
websocket: Final = _ClientSocket(second, third)
handler: Final = ManagedResponsesWebSocketHandler(
websocket=websocket,
model="test-model",
logging_obj=Logging(
model="test-model",
messages=[],
stream=True,
call_type="aresponses",
start_time=0,
litellm_call_id="test-id",
function_id="test-func",
),
first_message=first,
turn_admission=_admission_crashing_the_next_turn(),
)
failure: Final = await handler.run()
assert isinstance(failure, ValueError)
assert answered == ["one", "three"]
assert _errors(websocket) == [(500, {"type": "server_error", "message": "custom check failed"})]
assert websocket.close_code is None
def _deployment_defaults():
from types import MappingProxyType
from litellm.types.responses.streaming_websocket import ResponsesWebSocketRequestDefaults
return ResponsesWebSocketRequestDefaults(
fill_missing=MappingProxyType({"reasoning": {"effort": "high"}, "service_tier": "priority"}),
overrides=MappingProxyType({"provider_default": "configured"}),
)
class TestNativeWebSocketDeploymentDefaults:
"""The native relay merges deployment litellm_params into every response.create like HTTP does."""
def test_builder_maps_router_kwargs_like_the_http_path(self):
from litellm.responses.main import _build_responses_websocket_request_defaults
defaults = _build_responses_websocket_request_defaults(
{
"model": "gpt-5-pro",
"reasoning_effort": "high",
"service_tier": "priority",
"extra_body": {"provider_default": "configured"},
"temperature": None,
"timeout": 600,
"max_retries": 2,
"caching": False,
"custom_llm_provider": "openai",
"litellm_metadata": {"user_api_key": "hashed"},
"user_api_key_dict": MagicMock(),
"litellm_logging_obj": MagicMock(),
"websocket": MagicMock(),
}
)
assert dict(defaults.fill_missing) == {"reasoning": {"effort": "high"}, "service_tier": "priority"}
assert dict(defaults.overrides) == {"provider_default": "configured"}
def test_builder_keeps_explicit_reasoning_over_reasoning_effort(self):
from litellm.responses.main import _build_responses_websocket_request_defaults
defaults = _build_responses_websocket_request_defaults(
{"model": "gpt-5-pro", "reasoning": {"effort": "low"}, "reasoning_effort": "high"}
)
assert dict(defaults.fill_missing) == {"reasoning": {"effort": "low"}}
assert dict(defaults.overrides) == {}
def test_builder_copies_dict_valued_reasoning_effort_like_the_http_path(self):
from litellm.responses.main import _build_responses_websocket_request_defaults
defaults = _build_responses_websocket_request_defaults(
{"model": "gpt-5-pro", "reasoning_effort": {"effort": "xhigh", "summary": "auto"}}
)
assert dict(defaults.fill_missing) == {"reasoning": {"effort": "xhigh", "summary": "auto"}}
@pytest.mark.parametrize("reasoning_effort", [5, ["low"], "hgih"])
def test_builder_forwards_non_enum_reasoning_effort_like_the_http_path(
self, reasoning_effort: int | list[str] | str
):
from litellm.responses.main import _build_responses_websocket_request_defaults
defaults = _build_responses_websocket_request_defaults({"model": "gpt-5-pro", "reasoning_effort": reasoning_effort})
assert dict(defaults.fill_missing) == {"reasoning": {"effort": reasoning_effort}}
@pytest.mark.asyncio
async def test_extra_body_type_key_never_replaces_the_frame_type(self):
from types import MappingProxyType
from litellm.types.responses.streaming_websocket import ResponsesWebSocketRequestDefaults
handler = _make_streaming(
authorized_model="gpt-5-pro",
request_defaults=ResponsesWebSocketRequestDefaults(
fill_missing=MappingProxyType({}),
overrides=MappingProxyType({"type": "session.update", "provider_default": "configured"}),
),
)
forwarded = json.loads(
await handler._mask_response_create(
json.dumps({"type": "response.create", "model": "gpt-5-pro", "input": "hi"})
)
)
assert forwarded == {
"type": "response.create",
"model": "gpt-5-pro",
"input": "hi",
"provider_default": "configured",
}
@pytest.mark.asyncio
async def test_flat_frame_gets_defaults_client_keys_win_extra_body_overrides(self):
handler = _make_streaming(authorized_model="gpt-5-pro", request_defaults=_deployment_defaults())
forwarded = json.loads(
await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"model": "gpt-5-pro",
"input": "Say hello",
"service_tier": "default",
"provider_default": "client",
}
)
)
)
assert forwarded == {
"type": "response.create",
"model": "gpt-5-pro",
"input": "Say hello",
"service_tier": "default",
"provider_default": "configured",
"reasoning": {"effort": "high"},
}
@pytest.mark.asyncio
async def test_nested_response_frame_gets_defaults_inside_response(self):
handler = _make_streaming(authorized_model="gpt-5-pro", request_defaults=_deployment_defaults())
forwarded = json.loads(
await handler._mask_response_create(
json.dumps({"type": "response.create", "response": {"model": "gpt-5-pro", "input": "hi"}})
)
)
assert forwarded == {
"type": "response.create",
"response": {
"model": "gpt-5-pro",
"input": "hi",
"reasoning": {"effort": "high"},
"service_tier": "priority",
"provider_default": "configured",
},
}
@pytest.mark.asyncio
async def test_frames_that_need_nothing_pass_through_untouched(self):
handler = _make_streaming(authorized_model="gpt-5-pro", request_defaults=_deployment_defaults())
cancel_frame = json.dumps({"type": "response.cancel"})
complete_frame = json.dumps(
{
"type": "response.create",
"model": "gpt-5-pro",
"input": "hi",
"reasoning": {"effort": "high"},
"service_tier": "priority",
"provider_default": "configured",
}
)
assert await handler._mask_response_create(cancel_frame) is cancel_frame
assert await handler._mask_response_create(complete_frame) is complete_frame
@pytest.mark.asyncio
@pytest.mark.parametrize("nested", (False, True), ids=("flat", "nested"))
async def test_saved_output_item_with_a_null_created_by_is_forwarded_without_it(self, nested: bool):
handler: Final = _make_streaming(authorized_model="gpt-5-pro")
compaction: Final = {"id": "cmp_1", "type": "compaction", "encrypted_content": "gAAAA"}
user_turn: Final = {"role": "user", "content": "hi"}
request: Final = {"model": "gpt-5-pro", "input": [{**compaction, "created_by": None}, user_turn]}
frame: Final = (
{"type": "response.create", "response": request} if nested else {"type": "response.create", **request}
)
forwarded: Final = json.loads(await handler._mask_response_create(json.dumps(frame)))
assert (forwarded["response"] if nested else forwarded)["input"] == [compaction, user_turn]
@pytest.mark.asyncio
async def test_saved_reasoning_item_is_forwarded_without_its_null_fields(self):
handler: Final = _make_streaming(authorized_model="gpt-5-pro")
reasoning: Final = {"id": "rs_1", "type": "reasoning", "summary": []}
frame: Final = {
"type": "response.create",
"model": "gpt-5-pro",
"input": [{**reasoning, "status": None, "content": None, "encrypted_content": None}],
}
forwarded: Final = json.loads(await handler._mask_response_create(json.dumps(frame)))
assert forwarded["input"] == [reasoning]
@pytest.mark.asyncio
async def test_input_items_with_nothing_to_drop_pass_through_untouched(self):
handler: Final = _make_streaming(authorized_model="gpt-5-pro")
frame: Final = json.dumps(
{
"type": "response.create",
"model": "gpt-5-pro",
"input": [{"id": "cmp_1", "type": "compaction", "encrypted_content": "gAAAA", "created_by": "user_1"}],
}
)
assert await handler._mask_response_create(frame) is frame
@pytest.mark.asyncio
async def test_handler_applies_defaults_to_the_first_frame_sent_upstream(self):
import asyncio
from unittest.mock import AsyncMock, patch
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
class FakeBackend:
def __init__(self):
self.sent = []
async def send(self, message):
self.sent.append(message)
async def recv(self, decode=False):
raise RuntimeError("backend closed")
async def close(self):
pass
backend = FakeBackend()
class FakeConnect:
def __init__(self, url, **kwargs):
pass
async def __aenter__(self):
return backend
async def __aexit__(self, *args):
pass
mock_config = MagicMock(spec=OpenAIResponsesAPIConfig)
mock_config.supports_native_websocket.return_value = True
mock_config.model_in_websocket_url.return_value = True
mock_config.get_websocket_url.return_value = "wss://api.openai.com/v1/responses"
mock_config.validate_environment.return_value = {}
mock_logging = MagicMock()
mock_logging.pre_call = MagicMock()
mock_logging.dispatch_success_handlers = AsyncMock()
mock_logging.copy_for_new_call.return_value = mock_logging
client_ws = MagicMock()
client_ws.receive_text = AsyncMock(side_effect=RuntimeError("client closed"))
client_ws.send_text = AsyncMock()
client_ws.close = AsyncMock()
with patch("websockets.connect", FakeConnect):
await BaseLLMHTTPHandler().async_responses_websocket(
model="gpt-5-pro",
websocket=client_ws,
logging_obj=mock_logging,
responses_api_provider_config=mock_config,
api_key="sk-test",
first_message=json.dumps({"type": "response.create", "model": "gpt-5-pro", "input": "Say hello"}),
request_defaults=_deployment_defaults(),
)
await asyncio.sleep(0)
assert [json.loads(frame) for frame in backend.sent] == [
{
"type": "response.create",
"model": "gpt-5-pro",
"input": "Say hello",
"reasoning": {"effort": "high"},
"service_tier": "priority",
"provider_default": "configured",
}
]
@pytest.mark.asyncio
async def test_aresponses_websocket_builds_defaults_from_deployment_kwargs(self, monkeypatch):
import importlib
from unittest.mock import AsyncMock
responses_main = importlib.import_module("litellm.responses.main")
stub = MagicMock()
stub.async_responses_websocket = AsyncMock()
monkeypatch.setattr(responses_main, "base_llm_http_handler", stub)
await responses_main._aresponses_websocket.__wrapped__(
model="openai/gpt-5-pro",
websocket=MagicMock(),
api_key="sk-test",
litellm_logging_obj=MagicMock(),
reasoning_effort="high",
service_tier="priority",
extra_body={"provider_default": "configured"},
)
request_defaults = stub.async_responses_websocket.call_args.kwargs["request_defaults"]
assert dict(request_defaults.fill_missing) == {"reasoning": {"effort": "high"}, "service_tier": "priority"}
assert dict(request_defaults.overrides) == {"provider_default": "configured"}
@pytest.mark.asyncio
async def test_aresponses_websocket_keeps_first_frame_routing_hints_out_of_the_defaults(
self, monkeypatch: pytest.MonkeyPatch
):
import importlib
from unittest.mock import AsyncMock
responses_main = importlib.import_module("litellm.responses.main")
stub = MagicMock()
stub.async_responses_websocket = AsyncMock()
monkeypatch.setattr(responses_main, "base_llm_http_handler", stub)
await responses_main._aresponses_websocket.__wrapped__(
model="openai/gpt-5-pro",
websocket=MagicMock(),
api_key="sk-test",
litellm_logging_obj=MagicMock(),
reasoning_effort="high",
input=[{"id": "encitem_abc", "type": "reasoning", "encrypted_content": "litellm_enc:abc"}],
previous_response_id="resp_first_turn",
)
call_kwargs = stub.async_responses_websocket.call_args.kwargs
assert dict(call_kwargs["request_defaults"].fill_missing) == {"reasoning": {"effort": "high"}}
assert "input" not in call_kwargs
assert "previous_response_id" not in call_kwargs
class TestNativeWebSocketGuardrails:
@pytest.mark.asyncio
async def test_response_create_injects_authorized_model(self):
import json
from unittest.mock import MagicMock
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
handler = ResponsesWebSocketStreaming(
websocket=MagicMock(),
backend_ws=MagicMock(),
logging_obj=MagicMock(),
authorized_model="authorized-deployment",
)
flat_message = await handler._mask_response_create(
json.dumps({"type": "response.create", "input": "hi"})
)
nested_message = await handler._mask_response_create(
json.dumps({"type": "response.create", "response": {"input": "hi"}})
)
assert json.loads(flat_message)["model"] == "authorized-deployment"
assert (
json.loads(nested_message)["response"]["model"] == "authorized-deployment"
)
@pytest.mark.asyncio
async def test_completed_event_with_null_response_passes_through(self):
from unittest.mock import MagicMock
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
class Guardrail:
def get_presidio_settings_from_request_data(self, request_data):
return None
def _unmask_pii_text(self, text, pii_tokens):
return text
event = '{"type":"response.completed","response":null}'
guardrail = Guardrail()
handler = ResponsesWebSocketStreaming(
websocket=MagicMock(),
backend_ws=MagicMock(),
logging_obj=MagicMock(),
request_data={"metadata": {"pii_tokens": {"<TOKEN_1>": "secret"}}},
guardrail_callbacks=[guardrail],
output_guardrail_callbacks=[guardrail],
)
assert handler._unmask_response_event(event) == event
assert await handler._mask_response_completed(event) == event
@pytest.mark.asyncio
async def test_output_masking_suppresses_delta_without_calling_presidio(self):
import json
from unittest.mock import AsyncMock, MagicMock
import websockets.exceptions
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
class RecordingGuardrail:
def __init__(self):
self.check_pii_calls = []
def get_presidio_settings_from_request_data(self, request_data):
return None
def _unmask_pii_text(self, text, pii_tokens):
return text
async def check_pii(
self, text, output_parse_pii, presidio_config, request_data
):
self.check_pii_calls.append(text)
return text
class FakeBackendWS:
def __init__(self, events):
self._events = list(events)
async def recv(self, decode=False):
if self._events:
return self._events.pop(0)
raise websockets.exceptions.ConnectionClosed(None, None)
guardrail = RecordingGuardrail()
client_ws = MagicMock()
client_ws.send_text = AsyncMock()
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
delta_event = json.dumps(
{"type": "response.output_text.delta", "delta": "alice@example.com"}
)
completed_event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"content": [
{"type": "output_text", "text": "alice@example.com"}
]
}
]
},
}
)
handler = ResponsesWebSocketStreaming(
websocket=client_ws,
backend_ws=FakeBackendWS([delta_event, completed_event]),
logging_obj=logging_obj,
output_guardrail_callbacks=[guardrail],
)
await handler.backend_to_client()
# The delta event must be suppressed without ever invoking Presidio,
# so check_pii is called exactly once (for the completed event only).
assert guardrail.check_pii_calls == ["alice@example.com"]
client_ws.send_text.assert_called_once()
sent_payload = client_ws.send_text.call_args[0][0]
assert json.loads(sent_payload)["type"] == "response.completed"
@pytest.mark.asyncio
async def test_output_masking_suppresses_text_bearing_done_events(self):
import json
from unittest.mock import AsyncMock, MagicMock
import websockets.exceptions
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
class MaskingGuardrail:
def __init__(self):
self.check_pii_calls = []
def get_presidio_settings_from_request_data(self, request_data):
return None
def _unmask_pii_text(self, text, pii_tokens):
return text
async def check_pii(
self, text, output_parse_pii, presidio_config, request_data
):
self.check_pii_calls.append(text)
return text.replace("alice@example.com", "<EMAIL_ADDRESS>")
class FakeBackendWS:
def __init__(self, events):
self._events = list(events)
async def recv(self, decode=False):
if self._events:
return self._events.pop(0)
raise websockets.exceptions.ConnectionClosed(None, None)
guardrail = MaskingGuardrail()
client_ws = MagicMock()
client_ws.send_text = AsyncMock()
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
done_events = [
json.dumps(
{"type": "response.output_text.done", "text": "alice@example.com"}
),
json.dumps(
{
"type": "response.content_part.done",
"part": {"type": "output_text", "text": "alice@example.com"},
}
),
json.dumps(
{
"type": "response.output_item.done",
"item": {
"type": "message",
"content": [
{"type": "output_text", "text": "alice@example.com"}
],
},
}
),
]
completed_event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"content": [
{"type": "output_text", "text": "alice@example.com"}
]
}
]
},
}
)
handler = ResponsesWebSocketStreaming(
websocket=client_ws,
backend_ws=FakeBackendWS(done_events + [completed_event]),
logging_obj=logging_obj,
output_guardrail_callbacks=[guardrail],
)
await handler.backend_to_client()
# Text-bearing done events carry the full output before response.completed
# arrives; they must be suppressed so unmasked PII never reaches the
# client, and Presidio is only invoked for response.completed.
assert guardrail.check_pii_calls == ["alice@example.com"]
client_ws.send_text.assert_called_once()
sent_payload = client_ws.send_text.call_args[0][0]
assert json.loads(sent_payload)["type"] == "response.completed"
assert "alice@example.com" not in sent_payload
assert "<EMAIL_ADDRESS>" in sent_payload
class _FakeWSGuardrail:
"""Presidio-like guardrail double for the WebSocket masking hooks.
``check_pii`` replaces each known PII string with its token. When
``output_parse_pii`` is True (input masking) the token->original map is
persisted into ``request_data["metadata"]["pii_tokens"]`` so the response
path can reverse it. ``_unmask_pii_text`` performs that reversal.
"""
def __init__(self, mask_map=None):
self.mask_map = mask_map or {"alice@example.com": "<EMAIL_ADDRESS_1>"}
self.output_parse_pii = True
self.apply_to_output = True
def get_presidio_settings_from_request_data(self, request_data):
return None
async def check_pii(self, text, output_parse_pii, presidio_config, request_data):
masked = text
tokens = {}
for original, token in self.mask_map.items():
if original in masked:
masked = masked.replace(original, token)
tokens[token] = original
if output_parse_pii and tokens:
metadata = request_data.setdefault("metadata", {})
metadata.setdefault("pii_tokens", {}).update(tokens)
return masked
def _unmask_pii_text(self, text, pii_tokens):
for token, original in pii_tokens.items():
text = text.replace(token, original)
return text
def _make_streaming(**kwargs):
from unittest.mock import MagicMock
from litellm.responses.streaming_iterator import ResponsesWebSocketStreaming
kwargs.setdefault("websocket", MagicMock())
kwargs.setdefault("backend_ws", MagicMock())
kwargs.setdefault("logging_obj", MagicMock())
return ResponsesWebSocketStreaming(**kwargs)
class TestNativeWebSocketGuardrailMasking:
"""Exercises the input/output PII masking hooks on ResponsesWebSocketStreaming."""
@pytest.mark.asyncio
async def test_a_reply_to_a_frame_the_guard_masked_is_unmasked_with_the_guard_s_tokens(self):
from unittest.mock import AsyncMock, MagicMock
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame
guardrail = _FakeWSGuardrail()
async def guard(frame: str) -> GuardedResponsesWsFrame:
masked = await guardrail.check_pii(json.loads(frame)["input"], True, None, walk := {})
return GuardedResponsesWsFrame(
frame=json.dumps({"type": "response.create", "input": masked}),
pii_tokens=walk["metadata"]["pii_tokens"],
)
backend_ws = MagicMock()
backend_ws.send = AsyncMock()
handler = _make_streaming(
backend_ws=backend_ws, request_data={}, guardrail_callbacks=[guardrail], frame_guard=guard
)
handler.logging_obj.copy_for_new_call.return_value = handler.logging_obj
await handler._forward_guarded_frame(json.dumps({"type": "response.create", "input": "email alice@example.com"}))
assert json.loads(backend_ws.send.await_args.args[0])["input"] == "email <EMAIL_ADDRESS_1>"
reply = json.dumps({"type": "response.output_text.delta", "delta": "Sent to <EMAIL_ADDRESS_1>"})
assert json.loads(handler._unmask_response_event(reply))["delta"] == "Sent to alice@example.com"
@pytest.mark.asyncio
async def test_mask_response_create_flat_string_input(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={},
guardrail_callbacks=[guardrail],
authorized_model="auth-model",
)
masked = await handler._mask_response_create(
json.dumps(
{"type": "response.create", "input": "email alice@example.com now"}
)
)
obj = json.loads(masked)
assert obj["model"] == "auth-model"
assert obj["input"] == "email <EMAIL_ADDRESS_1> now"
assert handler.request_data["metadata"]["pii_tokens"] == {
"<EMAIL_ADDRESS_1>": "alice@example.com"
}
@pytest.mark.asyncio
async def test_mask_response_create_list_content_string(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"input": [
{
"type": "message",
"role": "user",
"content": "ping alice@example.com",
}
],
}
)
)
obj = json.loads(masked)
assert obj["input"][0]["content"] == "ping <EMAIL_ADDRESS_1>"
@pytest.mark.asyncio
async def test_mask_response_create_input_text_blocks(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"input": [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "alice@example.com"},
{"type": "input_image", "image_url": "http://x"},
],
}
],
}
)
)
obj = json.loads(masked)
blocks = obj["input"][0]["content"]
assert blocks[0]["text"] == "<EMAIL_ADDRESS_1>"
assert blocks[1]["image_url"] == "http://x"
@pytest.mark.asyncio
async def test_mask_response_create_function_call_output_string(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"input": [
{
"type": "function_call_output",
"call_id": "call_1",
"output": "tool returned alice@example.com",
}
],
}
)
)
obj = json.loads(masked)
assert obj["input"][0]["output"] == "tool returned <EMAIL_ADDRESS_1>"
assert handler.request_data["metadata"]["pii_tokens"] == {
"<EMAIL_ADDRESS_1>": "alice@example.com"
}
@pytest.mark.asyncio
async def test_mask_response_create_function_call_output_blocks(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"input": [
{
"type": "function_call_output",
"call_id": "call_1",
"output": [
{"type": "output_text", "text": "alice@example.com"},
{"type": "input_image", "image_url": "http://x"},
],
}
],
}
)
)
obj = json.loads(masked)
blocks = obj["input"][0]["output"]
assert blocks[0]["text"] == "<EMAIL_ADDRESS_1>"
assert blocks[1]["image_url"] == "http://x"
@pytest.mark.asyncio
async def test_mask_response_create_nested_shape(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={},
guardrail_callbacks=[guardrail],
authorized_model="auth-model",
)
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"response": {"input": "alice@example.com", "model": "spoofed"},
}
)
)
obj = json.loads(masked)
assert obj["response"]["model"] == "auth-model"
assert obj["response"]["input"] == "<EMAIL_ADDRESS_1>"
@pytest.mark.asyncio
async def test_mask_response_create_flat_instructions(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"input": "hi",
"instructions": "reply to alice@example.com",
}
)
)
obj = json.loads(masked)
assert obj["instructions"] == "reply to <EMAIL_ADDRESS_1>"
assert handler.request_data["metadata"]["pii_tokens"] == {
"<EMAIL_ADDRESS_1>": "alice@example.com"
}
@pytest.mark.asyncio
async def test_mask_response_create_nested_instructions(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"response": {
"input": "hi",
"instructions": "email alice@example.com",
},
}
)
)
obj = json.loads(masked)
assert obj["response"]["instructions"] == "email <EMAIL_ADDRESS_1>"
assert handler.request_data["metadata"]["pii_tokens"] == {
"<EMAIL_ADDRESS_1>": "alice@example.com"
}
@pytest.mark.asyncio
async def test_mask_response_create_non_create_unchanged(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={},
guardrail_callbacks=[guardrail],
authorized_model="auth-model",
)
message = json.dumps({"type": "response.cancel", "input": "alice@example.com"})
assert await handler._mask_response_create(message) == message
@pytest.mark.asyncio
async def test_mask_response_create_invalid_json_unchanged(self):
handler = _make_streaming(
request_data={}, guardrail_callbacks=[_FakeWSGuardrail()]
)
assert await handler._mask_response_create("not json {{{") == "not json {{{"
@pytest.mark.asyncio
async def test_mask_response_create_model_only_without_guardrails(self):
handler = _make_streaming(request_data={}, authorized_model="auth-model")
masked = await handler._mask_response_create(
json.dumps({"type": "response.create", "input": "alice@example.com"})
)
obj = json.loads(masked)
assert obj["model"] == "auth-model"
assert obj["input"] == "alice@example.com"
@pytest.mark.asyncio
async def test_mask_response_create_no_op_without_model_or_guardrails(self):
handler = _make_streaming(request_data={})
message = json.dumps({"type": "response.create", "input": "alice@example.com"})
assert await handler._mask_response_create(message) == message
@pytest.mark.asyncio
async def test_mask_response_create_list_with_non_dict_item(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
masked = await handler._mask_response_create(
json.dumps(
{
"type": "response.create",
"input": [
"not-a-dict",
{
"type": "message",
"role": "user",
"content": "alice@example.com",
},
],
}
)
)
obj = json.loads(masked)
assert obj["input"][0] == "not-a-dict"
assert obj["input"][1]["content"] == "<EMAIL_ADDRESS_1>"
def test_enforce_authorized_model_no_authorized_model(self):
handler = _make_streaming(request_data={})
assert handler._enforce_authorized_model({"model": "anything"}) is False
def test_enforce_authorized_model_nested_with_top_level_model(self):
handler = _make_streaming(request_data={}, authorized_model="auth-model")
msg = {"response": {"model": "spoofed"}, "model": "also-spoofed"}
assert handler._enforce_authorized_model(msg) is True
assert msg["response"]["model"] == "auth-model"
assert msg["model"] == "auth-model"
@pytest.mark.asyncio
async def test_unmask_response_event_completed(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={
"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "alice@example.com"}}
},
guardrail_callbacks=[guardrail],
)
event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"content": [
{"type": "output_text", "text": "to <EMAIL_ADDRESS_1>"}
]
}
]
},
}
)
unmasked = json.loads(handler._unmask_response_event(event))
assert (
unmasked["response"]["output"][0]["content"][0]["text"]
== "to alice@example.com"
)
@pytest.mark.asyncio
async def test_unmask_response_event_delta(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={
"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "alice@example.com"}}
},
guardrail_callbacks=[guardrail],
)
event = json.dumps(
{"type": "response.output_text.delta", "delta": "<EMAIL_ADDRESS_1>"}
)
unmasked = json.loads(handler._unmask_response_event(event))
assert unmasked["delta"] == "alice@example.com"
def test_unmask_response_event_no_tokens_unchanged(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(request_data={}, guardrail_callbacks=[guardrail])
event = json.dumps(
{"type": "response.output_text.delta", "delta": "<EMAIL_ADDRESS_1>"}
)
assert handler._unmask_response_event(event) == event
def test_unmask_response_event_no_guardrails_unchanged(self):
handler = _make_streaming(
request_data={"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "x"}}}
)
event = json.dumps({"type": "response.completed", "response": {}})
assert handler._unmask_response_event(event) == event
def test_unmask_response_event_invalid_json_unchanged(self):
handler = _make_streaming(
request_data={"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "x"}}},
guardrail_callbacks=[_FakeWSGuardrail()],
)
assert handler._unmask_response_event("not json {{{") == "not json {{{"
def test_unmask_response_event_non_dict_response_unchanged(self):
handler = _make_streaming(
request_data={"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "x"}}},
guardrail_callbacks=[_FakeWSGuardrail()],
)
event = json.dumps({"type": "response.completed", "response": ["bad-shape"]})
assert handler._unmask_response_event(event) == event
def test_unmask_response_event_malformed_output_items_unchanged(self):
handler = _make_streaming(
request_data={
"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "alice@example.com"}}
},
guardrail_callbacks=[_FakeWSGuardrail()],
)
event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
"not-a-dict",
{"content": "not-a-list"},
{"content": ["not-a-dict-block"]},
]
},
}
)
assert handler._unmask_response_event(event) == event
def test_unmask_response_event_other_event_type_unchanged(self):
handler = _make_streaming(
request_data={"metadata": {"pii_tokens": {"<EMAIL_ADDRESS_1>": "x"}}},
guardrail_callbacks=[_FakeWSGuardrail()],
)
event = json.dumps(
{"type": "response.in_progress", "delta": "<EMAIL_ADDRESS_1>"}
)
assert handler._unmask_response_event(event) == event
@pytest.mark.asyncio
async def test_mask_response_completed_event(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[guardrail]
)
event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"content": [
{
"type": "output_text",
"text": "contact alice@example.com",
}
]
}
]
},
}
)
masked = json.loads(await handler._mask_response_completed(event))
assert (
masked["response"]["output"][0]["content"][0]["text"]
== "contact <EMAIL_ADDRESS_1>"
)
@pytest.mark.asyncio
async def test_mask_response_completed_masks_function_call_arguments(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[guardrail]
)
event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"type": "function_call",
"name": "send_email",
"arguments": '{"to": "alice@example.com"}',
}
]
},
}
)
masked = json.loads(await handler._mask_response_completed(event))
assert (
masked["response"]["output"][0]["arguments"]
== '{"to": "<EMAIL_ADDRESS_1>"}'
)
@pytest.mark.asyncio
async def test_mask_response_completed_masks_reasoning_summary(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[guardrail]
)
event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"type": "reasoning",
"summary": [
{
"type": "summary_text",
"text": "user is alice@example.com",
}
],
}
]
},
}
)
masked = json.loads(await handler._mask_response_completed(event))
assert (
masked["response"]["output"][0]["summary"][0]["text"]
== "user is <EMAIL_ADDRESS_1>"
)
@pytest.mark.asyncio
async def test_mask_response_completed_delta_unchanged(self):
guardrail = _FakeWSGuardrail()
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[guardrail]
)
event = json.dumps(
{"type": "response.output_text.delta", "delta": "alice@example.com"}
)
assert await handler._mask_response_completed(event) == event
@pytest.mark.asyncio
async def test_mask_response_completed_no_guardrails_unchanged(self):
handler = _make_streaming(request_data={})
event = json.dumps(
{"type": "response.output_text.delta", "delta": "alice@example.com"}
)
assert await handler._mask_response_completed(event) == event
@pytest.mark.asyncio
async def test_mask_response_completed_invalid_json_unchanged(self):
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[_FakeWSGuardrail()]
)
assert await handler._mask_response_completed("not json {{{") == "not json {{{"
@pytest.mark.asyncio
async def test_mask_response_completed_malformed_unchanged(self):
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[_FakeWSGuardrail()]
)
event = json.dumps(
{
"type": "response.completed",
"response": {
"output": [
"not-a-dict",
{"content": "not-a-list"},
{"content": ["not-a-dict-block"]},
]
},
}
)
assert await handler._mask_response_completed(event) == event
@pytest.mark.asyncio
async def test_mask_response_completed_non_dict_response_unchanged(self):
handler = _make_streaming(
request_data={}, output_guardrail_callbacks=[_FakeWSGuardrail()]
)
event = json.dumps({"type": "response.completed", "response": ["bad"]})
assert await handler._mask_response_completed(event) == event
@pytest.mark.asyncio
async def test_client_to_backend_masks_and_enforces_model(self):
from unittest.mock import AsyncMock
guardrail = _FakeWSGuardrail()
backend_ws = MagicMock()
backend_ws.send = AsyncMock()
websocket = MagicMock()
websocket.receive_text = AsyncMock(
side_effect=[
json.dumps(
{"type": "response.create", "input": "ping alice@example.com"}
),
Exception("stop"),
]
)
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
request_data={},
first_message=json.dumps(
{"type": "response.create", "input": "alice@example.com"}
),
guardrail_callbacks=[guardrail],
authorized_model="auth-model",
)
await handler.client_to_backend()
assert backend_ws.send.await_count == 2
first_sent = json.loads(backend_ws.send.await_args_list[0][0][0])
assert first_sent["model"] == "auth-model"
assert first_sent["input"] == "<EMAIL_ADDRESS_1>"
second_sent = json.loads(backend_ws.send.await_args_list[1][0][0])
assert second_sent["model"] == "auth-model"
assert second_sent["input"] == "ping <EMAIL_ADDRESS_1>"
assert handler.request_data["metadata"]["pii_tokens"] == {
"<EMAIL_ADDRESS_1>": "alice@example.com"
}
@pytest.mark.asyncio
async def test_backend_to_client_suppresses_deltas_and_masks_completed(self):
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
guardrail = _FakeWSGuardrail()
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps(
{"type": "response.output_text.delta", "delta": "alice@example.com"}
),
json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"content": [
{
"type": "output_text",
"text": "contact alice@example.com",
}
]
}
]
},
}
),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
output_guardrail_callbacks=[guardrail],
)
await handler.backend_to_client()
websocket.send_text.assert_awaited_once()
forwarded = json.loads(websocket.send_text.await_args[0][0])
assert forwarded["type"] == "response.completed"
assert (
forwarded["response"]["output"][0]["content"][0]["text"]
== "contact <EMAIL_ADDRESS_1>"
)
@pytest.mark.asyncio
async def test_backend_to_client_suppresses_function_call_arguments_done(self):
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
guardrail = _FakeWSGuardrail()
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps(
{
"type": "response.function_call_arguments.done",
"arguments": '{"to": "alice@example.com"}',
}
),
json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"type": "function_call",
"name": "send_email",
"arguments": '{"to": "alice@example.com"}',
}
]
},
}
),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
output_guardrail_callbacks=[guardrail],
)
await handler.backend_to_client()
# The unmasked function-call arguments must never reach the client; only
# the masked response.completed is forwarded.
websocket.send_text.assert_awaited_once()
sent_payload = websocket.send_text.await_args[0][0]
forwarded = json.loads(sent_payload)
assert forwarded["type"] == "response.completed"
assert (
forwarded["response"]["output"][0]["arguments"]
== '{"to": "<EMAIL_ADDRESS_1>"}'
)
assert "alice@example.com" not in sent_payload
@pytest.mark.asyncio
async def test_backend_to_client_suppresses_reasoning_summary_text_done(self):
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
guardrail = _FakeWSGuardrail()
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps(
{
"type": "response.reasoning_summary_text.done",
"text": "contact alice@example.com",
}
),
json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"content": [
{
"type": "output_text",
"text": "done",
}
]
}
]
},
}
),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
output_guardrail_callbacks=[guardrail],
)
await handler.backend_to_client()
# The reasoning-summary done event carries the full reasoning text before
# response.completed arrives; it must be suppressed so unmasked PII never
# reaches the client.
websocket.send_text.assert_awaited_once()
sent_payload = websocket.send_text.await_args[0][0]
assert json.loads(sent_payload)["type"] == "response.completed"
assert "alice@example.com" not in sent_payload
@pytest.mark.asyncio
async def test_backend_to_client_suppresses_reasoning_summary_part_done(self):
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
guardrail = _FakeWSGuardrail()
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps(
{
"type": "response.reasoning_summary_part.done",
"part": {
"type": "summary_text",
"text": "user is alice@example.com",
},
}
),
json.dumps(
{
"type": "response.completed",
"response": {
"output": [
{
"type": "reasoning",
"summary": [
{
"type": "summary_text",
"text": "user is alice@example.com",
}
],
}
]
},
}
),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
output_guardrail_callbacks=[guardrail],
)
await handler.backend_to_client()
# The reasoning-summary part-done event carries the full reasoning text
# before response.completed arrives; it must be suppressed, and the
# reasoning summary in response.completed must itself be masked.
websocket.send_text.assert_awaited_once()
sent_payload = websocket.send_text.await_args[0][0]
forwarded = json.loads(sent_payload)
assert forwarded["type"] == "response.completed"
assert (
forwarded["response"]["output"][0]["summary"][0]["text"]
== "user is <EMAIL_ADDRESS_1>"
)
assert "alice@example.com" not in sent_payload
class TestWebSocketChunkTypes:
"""Test handling of different chunk types from streaming responses"""
def test_serialize_function_call_chunk(self):
"""Test serialization of function call chunks"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.function_call.added",
"response_id": "resp_123",
"item_id": "call_456",
"output_index": 0,
"call_id": "call_456",
"name": "get_weather",
"arguments": "",
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.function_call.added" in serialized
assert "get_weather" in serialized
def test_serialize_function_call_arguments_delta(self):
"""Test serialization of function call arguments delta"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.function_call_arguments.delta",
"response_id": "resp_123",
"item_id": "call_456",
"output_index": 0,
"call_id": "call_456",
"delta": '{"location"',
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.function_call_arguments.delta" in serialized
assert "location" in serialized
def test_serialize_function_call_arguments_done(self):
"""Test serialization of function call arguments done"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.function_call_arguments.done",
"response_id": "resp_123",
"item_id": "call_456",
"output_index": 0,
"call_id": "call_456",
"arguments": '{"location": "Paris"}',
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.function_call_arguments.done" in serialized
assert "Paris" in serialized
def test_serialize_reasoning_content_delta(self):
"""Test serialization of reasoning content delta"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.reasoning_content.delta",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"content_index": 0,
"delta": "Thinking step 1...",
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.reasoning_content.delta" in serialized
assert "Thinking step 1" in serialized
def test_serialize_reasoning_content_done(self):
"""Test serialization of reasoning content done"""
from litellm.responses.streaming_iterator import (
ManagedResponsesWebSocketHandler,
)
chunk = {
"type": "response.reasoning_content.done",
"response_id": "resp_123",
"item_id": "msg_456",
"output_index": 0,
"content_index": 0,
"reasoning_content": "Complete reasoning...",
}
serialized = ManagedResponsesWebSocketHandler._serialize_chunk(chunk)
assert serialized is not None
assert "response.reasoning_content.done" in serialized
assert "Complete reasoning" in serialized
class TestResponsesWebSocketCredentials:
@staticmethod
async def _upstream_handshake_headers(**call_kwargs: object) -> Mapping[str, str]:
from asyncio import Future, get_running_loop
from types import TracebackType
from unittest.mock import AsyncMock, patch
from litellm.responses import main as responses_main
captured_headers: Final[Future[Mapping[str, str]]] = get_running_loop().create_future()
class FakeConnect:
def __init__(
self,
_url: str,
*,
additional_headers: Mapping[str, str],
**_kwargs: object,
) -> None:
captured_headers.set_result(dict(additional_headers))
async def __aenter__(self) -> None:
raise RuntimeError("stop at upstream handshake")
async def __aexit__(
self,
_exc_type: type[BaseException] | None,
_exc: BaseException | None,
_tb: TracebackType | None,
) -> None:
return None
websocket: Final = MagicMock()
websocket.close = AsyncMock()
with patch("websockets.connect", FakeConnect):
await responses_main._aresponses_websocket.__wrapped__(
websocket=websocket,
litellm_logging_obj=MagicMock(),
**call_kwargs,
)
assert captured_headers.done(), "the request never reached the native upstream websocket"
return captured_headers.result()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"api_base,explicit_key,global_key,expected_key",
[
("https://upstream.invalid/v1", "deployment-key", None, "deployment-key"),
("https://upstream.invalid/v1", "deployment-key", "global-key", "deployment-key"),
("https://upstream.invalid/v1", None, "global-key", "global-key"),
],
)
async def test_openai_websocket_authorization(
self,
monkeypatch: pytest.MonkeyPatch,
api_base: str,
explicit_key: str | None,
global_key: str | None,
expected_key: str,
) -> None:
import litellm
monkeypatch.setattr(litellm, "api_key", global_key)
monkeypatch.setattr(litellm, "openai_key", None)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setenv("LITELLM_RUST", "false")
headers: Final = await self._upstream_handshake_headers(
model="gpt-6-astra",
custom_llm_provider="openai",
api_key=explicit_key,
api_base=api_base,
)
assert headers["Authorization"] == f"Bearer {expected_key}"
@pytest.mark.asyncio
async def test_azure_websocket_without_its_own_key_never_gets_the_openai_key(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
import litellm
monkeypatch.setattr(litellm, "api_key", None)
monkeypatch.setattr(litellm, "openai_key", None)
monkeypatch.setattr(litellm, "azure_key", None)
monkeypatch.setenv("OPENAI_API_KEY", "openai-global-key")
monkeypatch.setenv("AZURE_API_KEY", "azure-env-key")
monkeypatch.delenv("AZURE_OPENAI_API_KEY", raising=False)
monkeypatch.setenv("LITELLM_RUST", "false")
headers: Final = await self._upstream_handshake_headers(
model="gpt-6-astra",
custom_llm_provider="azure",
api_base="https://resource.openai.azure.com",
)
assert headers["api-key"] == "azure-env-key"
assert "openai-global-key" not in " ".join(headers.values())
@pytest.mark.asyncio
@pytest.mark.parametrize(
"custom_llm_provider,api_base,deployment_key,expected_key",
[
(None, "https://api.deepseek.com/v1", "deployment-key", "deployment-key"),
("openai", "https://api.deepseek.com/v1", "deployment-key", "deployment-key"),
("openai", "https://api.deepseek.com/v1", None, "deepseek-env-key"),
("openai", "https://api.mistral.ai/v1", "deployment-key", "deployment-key"),
],
)
async def test_deployment_on_a_known_provider_host_completes_through_that_provider(
self,
monkeypatch: pytest.MonkeyPatch,
custom_llm_provider: str | None,
api_base: str,
deployment_key: str | None,
expected_key: str,
) -> None:
from unittest.mock import AsyncMock, patch
import httpx
import respx
import litellm
from litellm.responses import main as responses_main
chunks: Final = (
{"choices": [{"index": 0, "delta": {"role": "assistant", "content": "OK"}, "finish_reason": None}]},
{"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
)
stream: Final = "".join(
f"data: {json.dumps({'id': 'chatcmpl-1', 'object': 'chat.completion.chunk', 'created': 1, 'model': 'astra-chat', **chunk})}\n\n"
for chunk in chunks
)
def refuse_native_socket(*_args: object, **_kwargs: object) -> None:
raise ConnectionRefusedError("this host has no Responses WebSocket")
monkeypatch.setattr(litellm, "api_key", None)
monkeypatch.setattr(litellm, "openai_key", None)
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setenv("OPENAI_API_KEY", "openai-env-key")
monkeypatch.setenv("DEEPSEEK_API_KEY", "deepseek-env-key")
monkeypatch.setenv("MISTRAL_API_KEY", "mistral-env-key")
monkeypatch.setenv("LITELLM_RUST", "false")
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
websocket.close = AsyncMock()
websocket.receive_text = AsyncMock(side_effect=RuntimeError("client closed"))
with respx.mock(assert_all_called=False) as upstream, patch("websockets.connect", refuse_native_socket):
chat_completions: Final = upstream.post(f"{api_base}/chat/completions").mock(
return_value=httpx.Response(
200, text=stream + "data: [DONE]\n\n", headers={"content-type": "text/event-stream"}
)
)
await responses_main._aresponses_websocket.__wrapped__(
model="astra-chat",
custom_llm_provider=custom_llm_provider,
api_base=api_base,
api_key=deployment_key,
first_message=json.dumps({"type": "response.create", "model": "astra-chat", "input": "Reply OK"}),
websocket=websocket,
litellm_logging_obj=MagicMock(),
)
sent_types: Final = [json.loads(call.args[0]).get("type") for call in websocket.send_text.await_args_list]
assert chat_completions.called, f"the request never reached {api_base}/chat/completions, client saw {sent_types}"
assert chat_completions.calls.last.request.headers["Authorization"] == f"Bearer {expected_key}"
assert "response.completed" in sent_types
class TestNativeWebSocketUrlConstruction:
"""Test that native WebSocket URLs include the model query parameter.
These tests mock websockets.connect so they exercise the actual URL-building
code inside BaseLLMHTTPHandler.async_responses_websocket rather than
reimplementing the logic themselves.
"""
@pytest.mark.asyncio
async def test_openai_ws_url_includes_model(self):
"""Handler must pass ?model= in the URL to the backend WebSocket."""
from unittest.mock import AsyncMock, MagicMock, patch
captured_urls = []
class FakeConnect:
def __init__(self, url, **kwargs):
captured_urls.append(url)
async def __aenter__(self):
raise Exception("stop")
async def __aexit__(self, *args):
pass
mock_config = MagicMock(spec=OpenAIResponsesAPIConfig)
mock_config.supports_native_websocket.return_value = True
mock_config.get_websocket_url.return_value = "wss://api.openai.com/v1/responses"
mock_config.validate_environment.return_value = {}
mock_logging = MagicMock()
mock_logging.pre_call = MagicMock()
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
handler = BaseLLMHTTPHandler()
mock_ws = MagicMock()
mock_ws.close = AsyncMock()
with patch("websockets.connect", FakeConnect):
await handler.async_responses_websocket(
model="gpt-4o-mini",
websocket=mock_ws,
logging_obj=mock_logging,
responses_api_provider_config=mock_config,
api_key="sk-test",
)
assert len(captured_urls) == 1
from urllib.parse import parse_qs, urlparse
qs = parse_qs(urlparse(captured_urls[0]).query)
assert qs.get("model") == [
"gpt-4o-mini"
], f"Expected model in URL, got: {captured_urls[0]}"
@pytest.mark.asyncio
async def test_ws_url_preserves_existing_params_and_adds_model(self):
"""When api_base already has query params, model is added alongside them."""
from unittest.mock import AsyncMock, MagicMock, patch
captured_urls = []
class FakeConnect:
def __init__(self, url, **kwargs):
captured_urls.append(url)
async def __aenter__(self):
raise Exception("stop")
async def __aexit__(self, *args):
pass
mock_config = MagicMock(spec=OpenAIResponsesAPIConfig)
mock_config.supports_native_websocket.return_value = True
mock_config.get_websocket_url.return_value = (
"wss://custom.example.com/v1/responses?api-version=2024-05-01"
)
mock_config.validate_environment.return_value = {}
mock_logging = MagicMock()
mock_logging.pre_call = MagicMock()
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
handler = BaseLLMHTTPHandler()
mock_ws = MagicMock()
mock_ws.close = AsyncMock()
with patch("websockets.connect", FakeConnect):
await handler.async_responses_websocket(
model="gpt-4o",
websocket=mock_ws,
logging_obj=mock_logging,
responses_api_provider_config=mock_config,
api_key="sk-test",
)
assert len(captured_urls) == 1
from urllib.parse import parse_qs, urlparse
qs = parse_qs(urlparse(captured_urls[0]).query)
assert qs.get("model") == [
"gpt-4o"
], f"model missing from URL: {captured_urls[0]}"
assert qs.get("api-version") == [
"2024-05-01"
], f"existing param lost: {captured_urls[0]}"
@pytest.mark.asyncio
async def test_ws_passes_litellm_params_to_get_websocket_url(self):
"""Deployment api_version must reach get_websocket_url (Azure WS URL)."""
from unittest.mock import AsyncMock, MagicMock, patch
mock_config = MagicMock(spec=OpenAIResponsesAPIConfig)
mock_config.supports_native_websocket.return_value = True
mock_config.get_websocket_url.return_value = (
"wss://example.openai.azure.com/openai/v1/responses"
)
mock_config.validate_environment.return_value = {}
mock_logging = MagicMock()
mock_logging.pre_call = MagicMock()
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
handler = BaseLLMHTTPHandler()
mock_ws = MagicMock()
mock_ws.close = AsyncMock()
class FakeConnect:
def __init__(self, url, **kwargs):
pass
async def __aenter__(self):
raise Exception("stop")
async def __aexit__(self, *args):
pass
with patch("websockets.connect", FakeConnect):
await handler.async_responses_websocket(
model="gpt-5.3-codex",
websocket=mock_ws,
logging_obj=mock_logging,
responses_api_provider_config=mock_config,
api_key="sk-test",
api_base="https://example.openai.azure.com",
api_version="2025-04-01-preview",
)
mock_config.get_websocket_url.assert_called_once()
_, call_kwargs = mock_config.get_websocket_url.call_args
assert call_kwargs["litellm_params"]["api_version"] == "2025-04-01-preview"
_AFFINITY_METADATA = {
"model_info": {"id": "dep-1"},
"encrypted_content_affinity_enabled": True,
}
def _wrapped_reasoning_item():
from litellm.responses.utils import ResponsesAPIRequestUtils
return {
"type": "reasoning",
"id": ResponsesAPIRequestUtils._build_encrypted_item_id("dep-1", "rs_orig"),
"encrypted_content": ResponsesAPIRequestUtils.wrap_encrypted_content_with_model_id("gAAAA-blob", "dep-1"),
"summary": [],
}
class TestNativeWebSocketEncryptedContentAffinity:
@pytest.mark.asyncio
@pytest.mark.parametrize("nested", [False, True])
async def test_client_to_backend_restores_wrapped_ids(self, nested: bool):
from unittest.mock import AsyncMock
from litellm.responses.utils import ResponsesAPIRequestUtils
wrapped_previous = ResponsesAPIRequestUtils._build_responses_api_response_id(
custom_llm_provider="openai", model_id="dep-1", response_id="resp_orig"
)
payload = {
"input": [_wrapped_reasoning_item(), {"type": "message", "role": "user", "content": "hi"}],
"previous_response_id": wrapped_previous,
}
frame = {"type": "response.create", "response": payload} if nested else {"type": "response.create", **payload}
backend_ws = MagicMock()
backend_ws.send = AsyncMock()
websocket = MagicMock()
websocket.receive_text = AsyncMock(side_effect=[json.dumps(frame), Exception("stop")])
handler = _make_streaming(websocket=websocket, backend_ws=backend_ws, request_data={})
await handler.client_to_backend()
sent = json.loads(backend_ws.send.await_args_list[0][0][0])
body = sent["response"] if nested else sent
assert body["input"][0]["id"] == "rs_orig"
assert body["input"][0]["encrypted_content"] == "gAAAA-blob"
assert body["input"][1] == {"type": "message", "role": "user", "content": "hi"}
assert body["previous_response_id"] == "resp_orig"
@pytest.mark.asyncio
async def test_client_to_backend_leaves_unwrapped_frames_untouched(self):
from unittest.mock import AsyncMock
frame = json.dumps({"type": "response.create", "input": "hello", "previous_response_id": "resp_raw"})
backend_ws = MagicMock()
backend_ws.send = AsyncMock()
websocket = MagicMock()
websocket.receive_text = AsyncMock(side_effect=[frame, Exception("stop")])
handler = _make_streaming(websocket=websocket, backend_ws=backend_ws, request_data={})
await handler.client_to_backend()
assert backend_ws.send.await_args_list[0][0][0] == frame
@pytest.mark.asyncio
async def test_backend_to_client_wraps_ids_when_affinity_is_enabled(self):
import asyncio
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
from litellm.responses.utils import ResponsesAPIRequestUtils
reasoning_item = {"type": "reasoning", "id": "rs_1", "encrypted_content": "gAAAA-blob", "summary": []}
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps(
{
"type": "response.output_item.added",
"output_index": 0,
"item": {"type": "reasoning", "id": "rs_1", "summary": []},
}
),
json.dumps(
{
"type": "response.reasoning_summary_text.delta",
"item_id": "rs_1",
"output_index": 0,
"summary_index": 0,
"delta": "thinking",
}
),
json.dumps({"type": "response.output_item.done", "output_index": 0, "item": dict(reasoning_item)}),
json.dumps(
{
"type": "response.completed",
"response": {"id": "resp_1", "output": [dict(reasoning_item)], "usage": {"total_tokens": 3}},
}
),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={"litellm_metadata": dict(_AFFINITY_METADATA)},
custom_llm_provider="openai",
)
await handler.backend_to_client()
wrapped_content = ResponsesAPIRequestUtils.wrap_encrypted_content_with_model_id("gAAAA-blob", "dep-1")
added, summary_delta, item_done, completed = (
json.loads(call[0][0]) for call in websocket.send_text.await_args_list[:4]
)
assert item_done["item"]["encrypted_content"] == wrapped_content
assert completed["response"]["id"] == ResponsesAPIRequestUtils._build_responses_api_response_id(
custom_llm_provider="openai", model_id="dep-1", response_id="resp_1"
)
assert {
added["item"]["id"],
summary_delta["item_id"],
item_done["item"]["id"],
completed["response"]["output"][0]["id"],
} == {ResponsesAPIRequestUtils._build_encrypted_item_id("dep-1", "rs_1")}
assert completed["response"]["output"][0]["encrypted_content"] == wrapped_content
await asyncio.sleep(0)
logged = logging_obj.dispatch_success_handlers.await_args[0][0]
assert logged[0]["response"]["id"] == completed["response"]["id"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"frame",
[
{"note": "a frame without a type"},
{"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 1, "delta": "ok"},
{
"type": "response.content_part.added",
"item_id": "msg_1",
"output_index": 1,
"content_index": 0,
"part": {"type": "output_text", "text": ""},
},
{"type": "response.output_item.done", "output_index": 1, "item": {"type": "message", "id": "msg_1"}},
{
"type": "response.output_item.done",
"output_index": 0,
"item": {"type": "reasoning", "id": "encitem_bGl0ZWxsbTptb2RlbF9pZDpkZXAtMTtpdGVtX2lkOnJzXzE="},
},
],
ids=["no-type", "message-delta", "message-content-part", "message-item", "already-encoded-reasoning"],
)
async def test_backend_to_client_forwards_events_affinity_does_not_own_unchanged(self, frame: dict[str, object]):
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
raw_frame: Final = json.dumps(frame)
websocket: Final = MagicMock()
websocket.send_text = AsyncMock()
backend_ws: Final = MagicMock()
backend_ws.recv = AsyncMock(side_effect=[raw_frame, Exception("stop")])
handler: Final = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
request_data={"litellm_metadata": dict(_AFFINITY_METADATA)},
custom_llm_provider="openai",
)
await handler.backend_to_client()
assert websocket.send_text.await_args_list[0][0][0] == raw_frame
@pytest.mark.asyncio
async def test_backend_to_client_wraps_only_response_id_without_affinity(self):
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
from litellm.responses.utils import ResponsesAPIRequestUtils
reasoning_item = {"type": "reasoning", "id": "rs_1", "encrypted_content": "gAAAA-blob", "summary": []}
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps({"type": "response.output_item.done", "output_index": 0, "item": dict(reasoning_item)}),
json.dumps({"type": "response.completed", "response": {"id": "resp_1", "output": [dict(reasoning_item)]}}),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={"litellm_metadata": {"model_info": {"id": "dep-1"}}},
custom_llm_provider="openai",
)
await handler.backend_to_client()
item_done = json.loads(websocket.send_text.await_args_list[0][0][0])
assert item_done["item"] == reasoning_item
completed = json.loads(websocket.send_text.await_args_list[1][0][0])
assert completed["response"]["id"] == ResponsesAPIRequestUtils._build_responses_api_response_id(
custom_llm_provider="openai", model_id="dep-1", response_id="resp_1"
)
assert completed["response"]["output"][0] == reasoning_item
@pytest.mark.asyncio
@pytest.mark.parametrize(
"failure_frame, expected_status, expected_message",
[
(
{
"type": "error",
"error": {
"type": "invalid_request_error",
"code": "invalid_encrypted_content",
"message": "The encrypted content for item rs_1 could not be verified.",
},
},
400,
"The encrypted content for item rs_1 could not be verified.",
),
(
{
"type": "response.failed",
"response": {
"id": "resp_1",
"status": "failed",
"error": {"code": "server_error", "message": "upstream blew up"},
},
},
500,
"upstream blew up",
),
(
{"type": "error", "code": "rate_limit_exceeded", "message": "Rate limit reached for gpt-5.6"},
429,
"Rate limit reached for gpt-5.6",
),
],
)
async def test_backend_to_client_books_failure_frames_as_failures(
self, failure_frame: dict[str, object], expected_status: int, expected_message: str
):
import asyncio
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps({"type": "response.created", "response": {"id": "resp_1", "status": "in_progress"}}),
json.dumps(failure_frame),
Exception("stop"),
]
)
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
logging_obj.dispatch_failure_handlers = AsyncMock()
logging_obj.response_cost_calculator = MagicMock(return_value=0.0)
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
authorized_model="gpt-5.6",
custom_llm_provider="openai",
)
await handler.backend_to_client()
await asyncio.sleep(0)
logging_obj.dispatch_success_handlers.assert_not_awaited()
logging_obj.dispatch_failure_handlers.assert_awaited_once()
exception = logging_obj.dispatch_failure_handlers.await_args[0][0]
assert exception.status_code == expected_status
assert expected_message in str(exception)
@pytest.mark.asyncio
async def test_backend_to_client_logs_each_turn_as_its_own_call(self, monkeypatch):
import asyncio
import time
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.utils import CallTypes
pre_calls: list[tuple[str, object]] = []
successes: list[tuple[str, list[object]]] = []
failures: list[tuple[str, Exception]] = []
partial_usage: list[tuple[str, int, float]] = []
def record_pre_call(self, input, api_key, model=None, additional_args=None):
pre_calls.append((self.litellm_call_id, self.model_call_details["messages"]))
reservations: dict[str, tuple[object, object]] = {}
def record_reservation(self):
metadata = self.litellm_params["metadata"]
reservations[self.litellm_call_id] = (
metadata.get("user_api_key_budget_reservation"),
metadata["user_api_key_auth"].budget_reservation,
)
async def record_success(self, result, **kwargs):
record_reservation(self)
successes.append((self.litellm_call_id, [event["type"] for event in result]))
async def record_failure(self, exception, traceback_exception, **kwargs):
record_reservation(self)
failures.append((self.litellm_call_id, exception))
def record_partial(self, usage, response_cost):
partial_usage.append((self.litellm_call_id, usage.total_tokens, response_cost))
monkeypatch.setattr(Logging, "pre_call", record_pre_call)
monkeypatch.setattr(Logging, "dispatch_success_handlers", record_success)
monkeypatch.setattr(Logging, "dispatch_failure_handlers", record_failure)
monkeypatch.setattr(Logging, "record_partial_usage_for_failure", record_partial)
monkeypatch.setattr(Logging, "response_cost_calculator", lambda self, result: 0.01)
connection_logging = Logging(
model="gpt-5.4",
messages=[],
stream=False,
call_type=CallTypes.aresponses_websocket.value,
start_time=time.time(),
litellm_call_id="connection-call",
function_id="connection-call",
)
reservation = {"reserved_cost": 0.5, "entries": [], "finalized": False}
connection_logging.litellm_params = {
"metadata": {
"user_api_key_budget_reservation": reservation,
"user_api_key_auth": UserAPIKeyAuth(api_key="sk-hashed", budget_reservation=reservation),
}
}
websocket = MagicMock()
websocket.send_text = AsyncMock()
backend_ws = MagicMock()
backend_ws.recv = AsyncMock(
side_effect=[
json.dumps({"type": "response.created", "response": {"id": "resp_1", "status": "in_progress"}}),
json.dumps(
{
"type": "response.completed",
"response": {
"id": "resp_1",
"status": "completed",
"output": [],
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
},
}
),
json.dumps({"type": "error", "error": {"type": "invalid_request_error", "message": "bad turn"}}),
Exception("stop"),
]
)
handler = _make_streaming(
websocket=websocket, backend_ws=backend_ws, logging_obj=connection_logging, request_data={}
)
handler._record_client_frame(json.dumps({"type": "response.create", "input": "first question"}))
handler._record_client_frame(json.dumps({"type": "response.create", "input": "second question"}))
await handler.backend_to_client()
await asyncio.sleep(0)
(first_turn, first_messages), (second_turn, second_messages) = pre_calls
assert len({first_turn, second_turn, "connection-call"}) == 3
assert first_messages == [{"role": "user", "content": "first question"}]
assert second_messages == [{"role": "user", "content": "second question"}]
assert successes == [(first_turn, ["response.created", "response.completed"])]
((failed_turn, exception),) = failures
assert failed_turn == second_turn
assert "bad turn" in str(exception)
assert partial_usage == [(second_turn, 0, 0.01)]
assert connection_logging.litellm_call_id == "connection-call"
assert reservations[first_turn] == (reservation, reservation)
assert reservations[second_turn] == (None, None)
@pytest.mark.asyncio
async def test_bidirectional_forward_returns_the_provider_failure(self):
import asyncio
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
backend_drained = asyncio.Event()
backend_events = [
json.dumps({"type": "response.created", "response": {"id": "resp_1", "status": "in_progress"}}),
json.dumps(
{
"type": "error",
"status": 400,
"error": {
"type": "invalid_request_error",
"code": "invalid_encrypted_content",
"message": "could not be verified",
},
}
),
]
async def recv(decode=False):
if backend_events:
return backend_events.pop(0)
backend_drained.set()
raise Exception("stop")
async def receive_text():
await backend_drained.wait()
raise Exception("client gone")
websocket = MagicMock()
websocket.send_text = AsyncMock()
websocket.receive_text = receive_text
backend_ws = MagicMock()
backend_ws.recv = recv
backend_ws.send = AsyncMock()
backend_ws.close = AsyncMock()
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
logging_obj.dispatch_failure_handlers = AsyncMock()
logging_obj.response_cost_calculator = MagicMock(return_value=0.0)
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
authorized_model="gpt-5.6",
custom_llm_provider="openai",
)
failure = await handler.bidirectional_forward()
assert isinstance(failure, Exception)
assert failure.status_code == 400
assert "could not be verified" in str(failure)
@pytest.mark.asyncio
async def test_bidirectional_forward_returns_none_after_a_completed_turn(self):
import asyncio
from unittest.mock import AsyncMock
import websockets.exceptions # noqa: F401 (lazy submodule must be importable)
backend_drained = asyncio.Event()
backend_events = [
json.dumps(
{
"type": "response.completed",
"response": {
"id": "resp_1",
"status": "completed",
"output": [],
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
},
}
),
]
async def recv(decode=False):
if backend_events:
return backend_events.pop(0)
backend_drained.set()
raise Exception("stop")
async def receive_text():
await backend_drained.wait()
raise Exception("client gone")
websocket = MagicMock()
websocket.send_text = AsyncMock()
websocket.receive_text = receive_text
backend_ws = MagicMock()
backend_ws.recv = recv
backend_ws.send = AsyncMock()
backend_ws.close = AsyncMock()
logging_obj = MagicMock()
logging_obj.dispatch_success_handlers = AsyncMock()
logging_obj.copy_for_new_call.return_value = logging_obj
logging_obj.dispatch_failure_handlers = AsyncMock()
handler = _make_streaming(
websocket=websocket,
backend_ws=backend_ws,
logging_obj=logging_obj,
request_data={},
authorized_model="gpt-5.6",
custom_llm_provider="openai",
)
assert await handler.bidirectional_forward() is None