litellm/tests/integration/observability/test_realtime_guardrail_translation.py
devin-ai-integration[bot] e0398455d0
test: migrate tests/llm_translation into unit, integration and e2e tiers (#45759)
* test: migrate selected llm translation contracts

* test: migrate anthropic completion translation tests

* test: migrate bedrock and cohere translation tests

* test: tighten bedrock translation migration

* test: migrate azure and openai model translation tests

* test: migrate openai and small-provider translation tests

* test: migrate gemini and vertex translation tests

* test: migrate optional params and rerank translation tests

* test: migrate huggingface, json and openrouter translation tests

* test: fix openrouter integration expectations

* test: migrate databricks, xai, cometapi and fireworks translation tests

* test: migrate ovhcloud, prompt and small provider translation tests

* test: split reasoning effort grid into unit and e2e

* test: migrate router and realtime guardrail translation tests

* test: migrate google interactions translation tests

* test: migrate a2a, evals, skills and hosted vllm translation tests

* test: remove remaining llm translation suite

* test: tighten migrated llm translation unit tests and land missing rows

Restores rows the first pass dropped or weakened (bedrock agentcore and openwebui thinking stream, anthropic prefix, citations and tool_choice, azure agents handler, huggingface bare api_base, optional params num_retries, alternating roles, rerank response type), replaces truthiness and call-count checks with whole-value assertions, and moves tests to the mirror file of the code they cover

* test: move cohere, databricks, fireworks and gemini rows to mirror files over mocked HTTP

Restores three TestCohereV2Transform methods the first pass nested out of collection, replaces direct transform calls with respx-backed completion calls, and drops the databricks and fireworks files that sat outside their mirror paths

* test: close lost-intent gaps found in review of the llm translation migration

Points the hosted-mock guard at the triton test's new integration path, restores exact rerank result assertions for infinity, drops the reasoning e2e fallback that passed for any multi-line answer, and adds the mixtral invoke system prompt variants, eval deletion, and async pdf url download that the legacy suite exercised

* test: assert provider acceptance in the reasoning effort e2e

The live half of the split grid proves each route accepts reasoning_effort. claude-fable-5-1 on the direct route answers without surfacing reasoning content, so a reasoning-presence check either fails on head or needs a fallback that passes for any answer. Wire shape stays covered by the unit grid

* test: cover async and stream-end paths the legacy translation suite exercised

Adds async variants for bedrock converse file and thinking content, bedrock embedding timeout and region resolution, interaction stream termination and success logging, xai reasoning token folding, and bytes chunks with a prefix before data:. Also scopes the vertex safety settings global in test_vertex_safety_settings with monkeypatch so it stops leaking into gemini request bodies on the same worker

* test: type the new llm translation e2e calls and mark moved fixture dirs as packages

* test: name the reasoning effort e2e models as module constants

* test: assert reasoning content, register the new gemini coverage ids and give the guardrail config e2e a unique name

* test: block the prompt the shared guardrail denies and drop the reasoning presence check

* test: drop the duplicate litellm import left by the main sync

---------

Co-authored-by: yuneng <yuneng@berri.ai>
2026-10-11 07:58:53 +00:00

149 lines
6.2 KiB
Python

from __future__ import annotations
import asyncio
import json
import uuid
from typing import Final
import websockets
from integration._support.client import Gateway, Scenario, gateway_from_environment
from integration._support.upstream import delete_scenario, register_scenario
from integration.cost_calculation.cost_tracking_case import RealtimeResponse
from pydantic import JsonValue, TypeAdapter
JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
OBSERVATIONS: Final = TypeAdapter(list[dict[str, JsonValue]])
BLOCKED_PHRASE: Final = "realtime-blocked-phrase"
MODEL: Final = "openai/gpt-realtime"
def _register_guardrail(gateway: Gateway, scenario: Scenario, name: str) -> None:
response: Final = gateway.request(
"POST",
"/guardrails",
{
"guardrail": {
"guardrail_name": name,
"litellm_params": {
"guardrail": "litellm_content_filter",
"mode": "pre_call",
"default_on": True,
"realtime_violation_message": "That request was blocked by the content filter.",
"blocked_words": [{"keyword": BLOCKED_PHRASE, "action": "BLOCK"}],
},
}
},
)
assert response.status_code == 200, response.text
guardrail_id: Final = JSON_OBJECT.validate_json(response.content).get("guardrail_id")
assert isinstance(guardrail_id, str), response.text
scenario.cleanups.callback(gateway.request, "DELETE", f"/guardrails/{guardrail_id}")
def _register_model(gateway: Gateway, scenario: Scenario) -> tuple[str, str]:
provider_key: Final = f"realtime-{uuid.uuid4().hex}"
handle: Final = register_scenario(
provider_key,
RealtimeResponse(
content_type="application/x-realtime",
events=(
{
"type": "response.done",
"response": {"id": "resp-scripted", "status": "completed", "output": []},
},
),
),
control_url=gateway.upstream_url,
)
scenario.cleanups.callback(delete_scenario, handle)
model: Final = scenario.model(model=MODEL, api_key=provider_key)
return model, provider_key
async def _exchange(
gateway: Gateway,
model: str,
key: str,
text: str,
) -> tuple[dict[str, JsonValue], ...]:
url: Final = f"{str(gateway.client.base_url).replace('http://', 'ws://').rstrip('/')}/v1/realtime?model={model}"
async with websockets.connect(url, additional_headers={"Authorization": f"Bearer {key}"}) as socket:
created: Final = JSON_OBJECT.validate_json(await socket.recv())
assert created.get("type") == "session.created", created
await socket.send(
json.dumps(
{
"type": "conversation.item.create",
"item": {"role": "user", "content": [{"type": "input_text", "text": text}]},
}
)
)
await socket.send(json.dumps({"type": "response.create"}))
return await _collect(socket, ())
async def _collect(
socket: websockets.ClientConnection,
events: tuple[dict[str, JsonValue], ...],
) -> tuple[dict[str, JsonValue], ...]:
event: Final = JSON_OBJECT.validate_json(await asyncio.wait_for(socket.recv(), timeout=15))
collected: Final = (*events, event)
return (
collected if event.get("type") == "response.done" or len(collected) >= 20 else await _collect(socket, collected)
)
def _provider_frames(gateway: Gateway, provider_key: str) -> tuple[dict[str, JsonValue], ...]:
response: Final = gateway.client.get(f"{gateway.upstream_url}/__observations")
assert response.status_code == 200, response.text
body: Final = JSON_OBJECT.validate_json(response.content)
requests: Final = OBSERVATIONS.validate_python(body.get("requests"))
return tuple(
JSON_OBJECT.validate_python(request["body"])
for request in requests
if isinstance(request, dict)
and request.get("method") == "WEBSOCKET_FRAME"
and request.get("authorization") == f"Bearer {provider_key}"
and isinstance(request.get("body"), dict)
)
def test_blocked_realtime_text_is_replaced_before_forwarding() -> None:
with gateway_from_environment() as gateway, gateway.scenario() as scenario:
guardrail: Final = f"realtime-guardrail-{uuid.uuid4().hex}"
_register_guardrail(gateway, scenario, guardrail)
model, provider_key = _register_model(gateway, scenario)
key: Final = scenario.key(models=[model])
events: Final = asyncio.run(_exchange(gateway, model, key, f"hello {BLOCKED_PHRASE}"))
errors: Final = tuple(
event
for event in events
if event.get("type") == "error"
and isinstance(event.get("error"), dict)
and event["error"].get("type") == "guardrail_violation"
)
assert errors, events
assert any(event.get("type") == "response.done" for event in events), events
frames: Final = _provider_frames(gateway, provider_key)
assert all(BLOCKED_PHRASE not in json.dumps(frame) for frame in frames), frames
frame_types: Final = tuple(frame.get("type") for frame in frames)
assert frame_types.count("conversation.item.create") == 1, frames
assert frame_types.count("response.create") == 1, frames
def test_clean_realtime_text_and_response_create_reach_provider() -> None:
with gateway_from_environment() as gateway, gateway.scenario() as scenario:
guardrail: Final = f"realtime-guardrail-{uuid.uuid4().hex}"
_register_guardrail(gateway, scenario, guardrail)
model, provider_key = _register_model(gateway, scenario)
key: Final = scenario.key(models=[model])
text: Final = f"clean-realtime-{uuid.uuid4().hex}"
events: Final = asyncio.run(_exchange(gateway, model, key, text))
assert any(event.get("type") == "response.done" for event in events), events
frames: Final = _provider_frames(gateway, provider_key)
assert any(frame.get("type") == "conversation.item.create" and text in json.dumps(frame) for frame in frames), (
frames
)
assert any(frame.get("type") == "response.create" for frame in frames), frames