Skip to content

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

fix(responses): open faked stream items empty so tool arguments and text arrive once (#46533)

Mateo Wang2c4ec9c6faa8
diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py
index 456e8634e64..435c11c0602 100644
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@ -1754,6 +1754,8 @@ class OpenAIResponsesHandler(BaseTranslation):
def _block_continuation_events(
exc: "ModifyResponseException", responses_so_far: Sequence[object]
) -> Sequence[ResponsesAPIStreamingResponse]:
+ from litellm.responses.streaming_iterator import opening_item_payload, opening_part_payload
+
response_id, model, output_index = _continuation_identity(exc, responses_so_far)
item: Final = _blocked_output_item(exc)
item_id: Final = item.id
@@ -1769,14 +1771,14 @@ class OpenAIResponsesHandler(BaseTranslation):
OutputItemAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
output_index=output_index,
- item=item,
+ item=BaseLiteLLMOpenAIResponseObject.model_validate(opening_item_payload(item.model_dump())),
),
ContentPartAddedEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,
item_id=item_id,
output_index=output_index,
content_index=0,
- part=BaseLiteLLMOpenAIResponseObject.model_validate(part),
+ part=BaseLiteLLMOpenAIResponseObject.model_validate(opening_part_payload(part)),
),
OutputTextDeltaEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,
diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.py
index 59b50ead83c..4ea114c1726 100644
--- a/litellm/responses/mcp/mcp_streaming_iterator.py
+++ b/litellm/responses/mcp/mcp_streaming_iterator.py
@@ -775,7 +775,7 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):
"id": item_id,
"type": "mcp_call",
"status": "in_progress",
- "arguments": tool_arguments or "{}",
+ "arguments": "",
"name": tool_name,
"server_label": "litellm",
},
diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.py
index 6ea73970aaa..7532a528248 100644
--- a/litellm/responses/streaming_iterator.py
+++ b/litellm/responses/streaming_iterator.py
@@ -1617,6 +1617,30 @@ def _stamp_responses_usage_cost(
setattr(usage_obj, "cost", cost)
+def opening_item_payload(payload: Mapping[str, object]) -> Mapping[str, object]:
+ match payload.get("type"):
+ case "message":
+ return {**payload, "content": [], "status": "in_progress"}
+ case "function_call":
+ return {**payload, "arguments": "", "status": "in_progress"}
+ case "custom_tool_call":
+ return {**payload, "input": ""}
+ case "reasoning":
+ return {**payload, "summary": []}
+ case _:
+ return payload
+
+
+def opening_part_payload(payload: Mapping[str, object]) -> Mapping[str, object]:
+ match payload.get("type"):
+ case "output_text":
+ return {**payload, "text": ""}
+ case "refusal":
+ return {**payload, "refusal": ""}
+ case _:
+ return payload
+
+
def build_synthetic_response_events(
*,
transformed: ResponsesAPIResponse,
@@ -1642,7 +1666,7 @@ def build_synthetic_response_events(
openai_types.OutputItemAddedEvent(
type=openai_types.ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
output_index=output_index,
- item=openai_types.BaseLiteLLMOpenAIResponseObject(**output_item_payload),
+ item=openai_types.BaseLiteLLMOpenAIResponseObject(**opening_item_payload(output_item_payload)),
)
)
@@ -1656,7 +1680,7 @@ def build_synthetic_response_events(
item_id=item_id,
output_index=output_index,
content_index=content_index,
- part=openai_types.BaseLiteLLMOpenAIResponseObject(**part_payload),
+ part=openai_types.BaseLiteLLMOpenAIResponseObject(**opening_part_payload(part_payload)),
)
)
_add_text_like_part_events(
@@ -1694,11 +1718,43 @@ def build_synthetic_response_events(
arguments=arguments,
)
)
+ elif item_type == "custom_tool_call":
+ tool_input = str(output_item_payload.get("input") or "")
+ for i in range(0, len(tool_input), chunk_size):
+ events.append(
+ openai_types.GenericEvent.model_validate(
+ {
+ "type": openai_types.ResponsesAPIStreamEvents.CUSTOM_TOOL_CALL_INPUT_DELTA.value,
+ "item_id": item_id,
+ "output_index": output_index,
+ "delta": tool_input[i : i + chunk_size],
+ }
+ )
+ )
+ events.append(
+ openai_types.GenericEvent.model_validate(
+ {
+ "type": openai_types.ResponsesAPIStreamEvents.CUSTOM_TOOL_CALL_INPUT_DONE.value,
+ "item_id": item_id,
+ "output_index": output_index,
+ "input": tool_input,
+ }
+ )
+ )
elif item_type == "reasoning":
summaries: Sequence[object] = _json_array_or_empty(output_item_payload.get("summary"))
for summary_index, summary in enumerate(summaries):
summary_payload = _dump_response_object(summary)
summary_text = str(summary_payload.get("text") or "")
+ events.append(
+ openai_types.ResponsePartAddedEvent(
+ type=openai_types.ResponsesAPIStreamEvents.RESPONSE_PART_ADDED,
+ item_id=item_id,
+ output_index=output_index,
+ summary_index=summary_index,
+ part={**summary_payload, "text": ""},
+ )
+ )
for i in range(0, len(summary_text), chunk_size):
events.append(
openai_types.ReasoningSummaryTextDeltaEvent(
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index b40726a443d..1e4f78b2204 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -1697,6 +1697,7 @@ class ResponsePartAddedEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_PART_ADDED]
item_id: str
output_index: int
+ summary_index: int = 0
part: dict
diff --git a/tests/integration/mcp/test_mcp_llm_endpoints.py b/tests/integration/mcp/test_mcp_llm_endpoints.py
index cd5670bcea9..c3bccec1f8e 100644
--- a/tests/integration/mcp/test_mcp_llm_endpoints.py
+++ b/tests/integration/mcp/test_mcp_llm_endpoints.py
@@ -12,7 +12,14 @@ from typing import Final, Literal, TypeVar
import httpx
import pytest
import yaml
-from integration._support.client import Gateway, Scenario, eventually, gateway_from_environment, object_value
+from integration._support.client import (
+ Gateway,
+ Scenario,
+ eventually,
+ gateway_from_environment,
+ object_value,
+ string_value,
+)
from integration._support.database import read_rows
from integration._support.mcp import (
McpPeer,
@@ -479,6 +486,45 @@ def test_streaming_chat_executes_the_tool_once_and_streams_the_follow_up(gateway
assert len(rig.upstream_tools()) == 2
+def _mcp_call_items(
+ events: Sequence[Mapping[str, JsonValue]], kind: str
+) -> tuple[tuple[JsonValue, dict[str, JsonValue]], ...]:
+ announced: Final = tuple(
+ (event["output_index"], object_value(event["item"])) for event in events if event["type"] == kind
+ )
+ return tuple((index, item) for index, item in announced if item.get("type") == "mcp_call")
+
+
+def _add_call_arguments(call: dict[str, object]) -> JsonValue:
+ return object_value(JSON_OBJECT.validate_python(call["body"])["params"])["arguments"]
+
+
+def test_streaming_responses_opens_the_gateway_tool_call_empty_and_streams_its_arguments_once(gateway: Gateway) -> None:
+ with _rig(gateway, "responses") as rig:
+ key: Final = _granted_key(rig)
+ response: Final = rig.send(key, [AUTO], stream=True)
+ assert response.status_code == 200, response.text
+ events: Final = tuple(
+ JSON_OBJECT.validate_json(line.removeprefix("data: "))
+ for line in response.text.splitlines()
+ if line.startswith("data: ") and line != "data: [DONE]"
+ )
+ opened: Final = _mcp_call_items(events, "response.output_item.added")
+ closed: Final = _mcp_call_items(events, "response.output_item.done")
+ assert [(index, item["arguments"], item["status"]) for index, item in opened] == [
+ (closed[0][0], "", "in_progress")
+ ], opened
+ streamed: Final = "".join(
+ string_value(event["delta"])
+ for event in events
+ if event["type"] == "response.mcp_call_arguments.delta" and event["output_index"] == opened[0][0]
+ )
+ assert json.loads(streamed) == ADD, streamed
+ assert string_value(opened[0][1]["arguments"]) + streamed == closed[0][1]["arguments"], (opened, closed)
+ assert [_add_call_arguments(call) for call in _peer_add_calls(rig.peer)] == [ADD]
+ assert len(rig.upstream_tools()) == 2
+
+
def test_streaming_chat_through_a_toolset_gateway_url_serves_a_team_key_without_its_own_grant(
gateway: Gateway,
) -> None:
diff --git a/tests/integration/streaming/faked_responses_case.py b/tests/integration/streaming/faked_responses_case.py
new file mode 100644
index 00000000000..db071b57717
--- /dev/null
+++ b/tests/integration/streaming/faked_responses_case.py
@@ -0,0 +1,332 @@
+import json
+import uuid
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from typing import Final
+
+import httpx
+from anthropic.types import ToolParam as AnthropicToolParam
+from integration._support.client import Gateway, Scenario, eventually, list_value, object_value, string_value
+from integration._support.database import read_rows
+from integration._support.wire import Reply, Request, Wire
+from openai.types.chat import ChatCompletionFunctionToolParam
+from openai.types.responses import FunctionToolParam
+from pydantic import JsonValue, TypeAdapter
+
+API_KEY: Final = "synthetic-faked-stream-key"
+AZURE_API_VERSION: Final = "2025-03-01-preview"
+CALL_ID: Final = "x-litellm-call-id"
+NO_CACHE: Final[dict[str, JsonValue]] = {"no-cache": True}
+FAKED_STREAM: Final[dict[str, JsonValue]] = {"supports_native_streaming": False}
+JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+QUESTION: Final = "What is the weather in Paris?"
+ANSWER: Final = "Paris is 22 degrees Celsius with clear skies."
+ARGUMENTS: Final = json.dumps({"city": "Paris", "unit": "celsius"})
+SECOND_ARGUMENTS: Final = json.dumps({"city": "Lyon", "days": 3})
+SQL: Final = "SELECT city FROM weather WHERE celsius > 20"
+REFUSAL: Final = "I cannot share the forecast for that place."
+SUMMARIES: Final = ("First, find the city.", "Then, look up its weather.")
+RESPONSES_TOOLS: Final[list[JsonValue]] = [
+ {"type": "function", "name": "get_weather", "parameters": {"type": "object", "properties": {}}},
+ {"type": "function", "name": "get_forecast", "parameters": {"type": "object", "properties": {}}},
+]
+CHAT_TOOLS: Final[list[JsonValue]] = [
+ {"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {}}}},
+ {"type": "function", "function": {"name": "get_forecast", "parameters": {"type": "object", "properties": {}}}},
+]
+ANTHROPIC_TOOLS: Final[list[JsonValue]] = [
+ {"name": "get_weather", "input_schema": {"type": "object", "properties": {}}},
+ {"name": "get_forecast", "input_schema": {"type": "object", "properties": {}}},
+]
+
+_TOOL_NAMES: Final = ("get_weather", "get_forecast")
+RESPONSES_TOOL_PARAMS: Final[list[FunctionToolParam]] = [
+ {"type": "function", "name": name, "parameters": {"type": "object", "properties": {}}, "strict": False}
+ for name in _TOOL_NAMES
+]
+CHAT_TOOL_PARAMS: Final[list[ChatCompletionFunctionToolParam]] = [
+ {"type": "function", "function": {"name": name, "parameters": {"type": "object", "properties": {}}}}
+ for name in _TOOL_NAMES
+]
+ANTHROPIC_TOOL_PARAMS: Final[list[AnthropicToolParam]] = [
+ {"name": name, "input_schema": {"type": "object", "properties": {}}} for name in _TOOL_NAMES
+]
+
+
+def reasoning_item(identity: str, summaries: Sequence[str] = SUMMARIES) -> dict[str, JsonValue]:
+ return {
+ "type": "reasoning",
+ "id": f"rs_{identity}",
+ "summary": [{"type": "summary_text", "text": text} for text in summaries],
+ }
+
+
+def message_item(identity: str, text: str = ANSWER) -> dict[str, JsonValue]:
+ return {
+ "type": "message",
+ "id": f"msg_{identity}",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": text, "annotations": []}],
+ }
+
+
+def refusal_item(identity: str, refusal: str = REFUSAL) -> dict[str, JsonValue]:
+ return {
+ "type": "message",
+ "id": f"msg_refusal_{identity}",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "refusal", "refusal": refusal}],
+ }
+
+
+def function_call_item(
+ identity: str, arguments: JsonValue = ARGUMENTS, name: str = "get_weather"
+) -> dict[str, JsonValue]:
+ return {
+ "type": "function_call",
+ "id": f"fc_{name}_{identity}",
+ "call_id": f"call_{name}_{identity}",
+ "name": name,
+ "arguments": arguments,
+ "status": "completed",
+ }
+
+
+def custom_tool_call_item(identity: str, tool_input: str = SQL) -> dict[str, JsonValue]:
+ return {
+ "type": "custom_tool_call",
+ "id": f"ctc_{identity}",
+ "call_id": f"call_sql_{identity}",
+ "name": "run_sql",
+ "input": tool_input,
+ }
+
+
+def every_item_kind(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (
+ reasoning_item(identity),
+ message_item(identity),
+ function_call_item(identity),
+ custom_tool_call_item(identity),
+ refusal_item(identity),
+ )
+
+
+def response_body(identity: str, output: Sequence[Mapping[str, JsonValue]]) -> dict[str, JsonValue]:
+ return {
+ "id": f"resp_{identity}",
+ "object": "response",
+ "created_at": 1,
+ "status": "completed",
+ "model": "faked-stream-backend",
+ "output": [dict(item) for item in output],
+ "usage": {"input_tokens": 12, "output_tokens": 30, "total_tokens": 42},
+ }
+
+
+def answering(output: Callable[[str], Sequence[Mapping[str, JsonValue]]]) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ identity: Final = uuid.uuid4().hex[:16]
+ return Reply(body=json.dumps(response_body(identity, output(identity))).encode())
+
+ return respond
+
+
+def faked_model(scenario: Scenario, wire: Wire, model: str = "openai/faked-stream-backend") -> str:
+ return scenario.model(model=model, api_base=wire.url + "/v1", api_key=API_KEY, model_info=FAKED_STREAM)
+
+
+def faked_azure_model(scenario: Scenario, wire: Wire) -> str:
+ return scenario.model(
+ model="azure/responses/faked-stream-deployment",
+ api_base=wire.url,
+ api_key=API_KEY,
+ api_version=AZURE_API_VERSION,
+ model_info=FAKED_STREAM,
+ )
+
+
+def posted_bodies(wire: Wire) -> tuple[dict[str, JsonValue], ...]:
+ return tuple(JSON_OBJECT.validate_json(request.body) for request in wire.drain() if request.method == "POST")
+
+
+def assert_one_unstreamed_upstream_call(wire: Wire, target: str) -> dict[str, JsonValue]:
+ received: Final = tuple(request for request in wire.drain() if request.method == "POST")
+ assert [request.target for request in received] == [target], [request.target for request in received]
+ body: Final = JSON_OBJECT.validate_json(received[0].body)
+ assert body.get("stream") is not True, body
+ return body
+
+
+def data_events(lines: Iterator[str]) -> tuple[dict[str, JsonValue], ...]:
+ return tuple(JSON_OBJECT.validate_json(line.removeprefix("data: ")) for line in lines if line.startswith("data: {"))
+
+
+def streamed(
+ gateway: Gateway, path: str, body: Mapping[str, JsonValue], key: str | None = None
+) -> tuple[httpx.Headers, tuple[dict[str, JsonValue], ...]]:
+ with gateway.client.stream(
+ "POST",
+ path,
+ json={**body, "stream": True},
+ headers={"Authorization": f"Bearer {gateway.key if key is None else key}", "anthropic-version": "2023-06-01"},
+ timeout=120,
+ ) as response:
+ assert response.status_code == 200, response.read()
+ return response.headers, data_events(response.iter_lines())
+
+
+def stream_events(
+ gateway: Gateway, path: str, body: Mapping[str, JsonValue], key: str | None = None
+) -> tuple[str, tuple[dict[str, JsonValue], ...]]:
+ headers, events = streamed(gateway, path, body, key)
+ return headers[CALL_ID], events
+
+
+def responses_request(model: str, **extra: JsonValue) -> dict[str, JsonValue]:
+ return {"model": model, "input": f"{QUESTION} {uuid.uuid4().hex}", "tools": RESPONSES_TOOLS, **extra}
+
+
+def joined(events: Sequence[Mapping[str, JsonValue]], kind: str, output_index: int, **match: JsonValue) -> str:
+ return "".join(string_value(event["delta"]) for event in events if _matches(event, kind, output_index, match))
+
+
+def _matches(event: Mapping[str, JsonValue], kind: str, output_index: int, match: Mapping[str, JsonValue]) -> bool:
+ return (
+ event["type"] == kind
+ and event.get("output_index") == output_index
+ and all(event.get(name) == value for name, value in match.items())
+ )
+
+
+def _of_kind(events: Sequence[Mapping[str, JsonValue]], kind: str) -> Iterator[dict[str, JsonValue]]:
+ for event in events:
+ if event["type"] == kind:
+ yield dict(event)
+
+
+def items_by_index(events: Sequence[Mapping[str, JsonValue]], kind: str) -> dict[int, dict[str, JsonValue]]:
+ return {int(str(event["output_index"])): object_value(event["item"]) for event in _of_kind(events, kind)}
+
+
+def _announced_parts(
+ events: Sequence[Mapping[str, JsonValue]], kind: str, output_index: int
+) -> tuple[dict[str, JsonValue], ...]:
+ return tuple(
+ object_value(event["part"]) for event in _of_kind(events, kind) if event["output_index"] == output_index
+ )
+
+
+def _rebuilt_part(
+ events: Sequence[Mapping[str, JsonValue]], output_index: int, content_index: int, part: Mapping[str, JsonValue]
+) -> dict[str, JsonValue]:
+ match part.get("type"):
+ case "output_text":
+ text: Final = joined(events, "response.output_text.delta", output_index, content_index=content_index)
+ return {**part, "text": string_value(part["text"]) + text}
+ case "refusal":
+ refusal: Final = joined(events, "response.refusal.delta", output_index, content_index=content_index)
+ return {**part, "refusal": string_value(part["refusal"]) + refusal}
+ case _:
+ return dict(part)
+
+
+def _rebuilt_summary(
+ events: Sequence[Mapping[str, JsonValue]], output_index: int, summary_index: int, part: Mapping[str, JsonValue]
+) -> dict[str, JsonValue]:
+ text: Final = joined(events, "response.reasoning_summary_text.delta", output_index, summary_index=summary_index)
+ return {**part, "text": string_value(part["text"]) + text}
+
+
+def _rebuilt_item(
+ events: Sequence[Mapping[str, JsonValue]], output_index: int, added: Mapping[str, JsonValue]
+) -> dict[str, JsonValue]:
+ match added.get("type"):
+ case "message":
+ parts: Final = (
+ *map(object_value, list_value(added["content"])),
+ *_announced_parts(events, "response.content_part.added", output_index),
+ )
+ return {
+ **added,
+ "content": [_rebuilt_part(events, output_index, index, part) for index, part in enumerate(parts)],
+ }
+ case "reasoning":
+ summaries: Final = (
+ *map(object_value, list_value(added["summary"])),
+ *_announced_parts(events, "response.reasoning_summary_part.added", output_index),
+ )
+ return {
+ **added,
+ "summary": [
+ _rebuilt_summary(events, output_index, index, part) for index, part in enumerate(summaries)
+ ],
+ }
+ case "function_call":
+ arguments: Final = joined(events, "response.function_call_arguments.delta", output_index)
+ return {**added, "arguments": string_value(added["arguments"]) + arguments}
+ case "custom_tool_call":
+ tool_input: Final = joined(events, "response.custom_tool_call_input.delta", output_index)
+ return {**added, "input": string_value(added["input"]) + tool_input}
+ case "mcp_call":
+ mcp_arguments: Final = joined(events, "response.mcp_call_arguments.delta", output_index)
+ return {**added, "arguments": string_value(added["arguments"]) + mcp_arguments}
+ case _:
+ return dict(added)
+
+
+def rebuilt(events: Sequence[Mapping[str, JsonValue]]) -> dict[int, dict[str, JsonValue]]:
+ return {
+ index: _rebuilt_item(events, index, added)
+ for index, added in items_by_index(events, "response.output_item.added").items()
+ }
+
+
+def values(item: Mapping[str, JsonValue]) -> JsonValue:
+ match item.get("type"):
+ case "message":
+ return [
+ [string_value(part["type"]), part.get("text", part.get("refusal"))]
+ for part in map(object_value, list_value(item["content"]))
+ ]
+ case "reasoning":
+ return [part["text"] for part in map(object_value, list_value(item["summary"]))]
+ case "function_call" | "mcp_call":
+ return [item["name"], item["arguments"]]
+ case "custom_tool_call":
+ return [item["name"], item["input"]]
+ case _:
+ return json.dumps(item, sort_keys=True)
+
+
+def completed_output(events: Sequence[Mapping[str, JsonValue]]) -> tuple[dict[str, JsonValue], ...]:
+ completed: Final = tuple(_of_kind(events, "response.completed"))
+ assert len(completed) == 1, [event["type"] for event in events]
+ return tuple(map(object_value, list_value(object_value(completed[0]["response"])["output"])))
+
+
+def assert_each_value_arrives_once(
+ events: Sequence[Mapping[str, JsonValue]], expected: Sequence[Mapping[str, JsonValue]]
+) -> None:
+ wanted: Final = [values(item) for item in expected]
+ seen_by_client: Final = rebuilt(events)
+ done: Final = items_by_index(events, "response.output_item.done")
+ assert [values(seen_by_client[index]) for index in sorted(seen_by_client)] == wanted, [
+ event["type"] for event in events
+ ]
+ assert [values(done[index]) for index in sorted(done)] == wanted
+ assert [values(item) for item in completed_output(events)] == wanted
+
+
+def spend_statuses(call_id: str) -> list[JsonValue]:
+ rows: Final = eventually(
+ lambda: read_rows('SELECT status FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s', (call_id,)),
+ lambda found: len(found) >= 1,
+ seconds=70,
+ )
+ return [row["status"] for row in rows]
+
+
+def http_client(gateway: Gateway) -> httpx.AsyncClient:
+ return httpx.AsyncClient(base_url=str(gateway.client.base_url), timeout=120, trust_env=False)
diff --git a/tests/integration/streaming/test_faked_responses_stream_bridges.py b/tests/integration/streaming/test_faked_responses_stream_bridges.py
new file mode 100644
index 00000000000..dc6de497ba8
--- /dev/null
+++ b/tests/integration/streaming/test_faked_responses_stream_bridges.py
@@ -0,0 +1,253 @@
+import json
+import uuid
+from collections.abc import Iterator, Sequence
+from typing import Final
+
+import anthropic
+import openai
+from integration._support.client import JSON_OBJECT, Gateway, list_value, object_value, string_value
+from integration._support.wire import wire_server
+from integration.streaming.faked_responses_case import (
+ ANSWER,
+ ANTHROPIC_TOOL_PARAMS,
+ ANTHROPIC_TOOLS,
+ ARGUMENTS,
+ AZURE_API_VERSION,
+ CALL_ID,
+ CHAT_TOOL_PARAMS,
+ CHAT_TOOLS,
+ NO_CACHE,
+ QUESTION,
+ SECOND_ARGUMENTS,
+ SUMMARIES,
+ answering,
+ assert_one_unstreamed_upstream_call,
+ faked_azure_model,
+ faked_model,
+ function_call_item,
+ message_item,
+ reasoning_item,
+ spend_statuses,
+ stream_events,
+)
+from openai.types.chat import ChatCompletionChunk
+from pydantic import JsonValue
+
+_OPENAI_TARGET: Final = "/v1/responses"
+_AZURE_TARGET: Final = f"/openai/responses?api-version={AZURE_API_VERSION}"
+_OPENAI_BRIDGE: Final = "openai/responses/faked-stream-backend"
+
+
+def _two_calls_and_text(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (
+ reasoning_item(identity),
+ message_item(identity),
+ function_call_item(identity),
+ function_call_item(identity, SECOND_ARGUMENTS, "get_forecast"),
+ )
+
+
+def _call_and_text(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (reasoning_item(identity), message_item(identity), function_call_item(identity))
+
+
+def _openai(gateway: Gateway) -> openai.OpenAI:
+ return openai.OpenAI(base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0)
+
+
+def _async_openai(gateway: Gateway) -> openai.AsyncOpenAI:
+ return openai.AsyncOpenAI(base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0)
+
+
+def _anthropic(gateway: Gateway) -> anthropic.Anthropic:
+ return anthropic.Anthropic(base_url=str(gateway.client.base_url), api_key=gateway.key, max_retries=0)
+
+
+def _async_anthropic(gateway: Gateway) -> anthropic.AsyncAnthropic:
+ return anthropic.AsyncAnthropic(base_url=str(gateway.client.base_url), api_key=gateway.key, max_retries=0)
+
+
+def _tool_call_fragments(chunks: Sequence[ChatCompletionChunk]) -> Iterator[tuple[int, str | None, str]]:
+ for chunk in chunks:
+ for choice in chunk.choices:
+ for call in choice.delta.tool_calls or ():
+ yield (
+ call.index,
+ call.function.name if call.function else None,
+ (call.function.arguments or "" if call.function else ""),
+ )
+
+
+def _arguments_by_index(chunks: Sequence[ChatCompletionChunk]) -> dict[int, str]:
+ fragments: Final = tuple(_tool_call_fragments(chunks))
+ return {
+ index: "".join(arguments for fragment_index, _, arguments in fragments if fragment_index == index)
+ for index in sorted({index for index, _, _ in fragments})
+ }
+
+
+def _names_by_index(chunks: Sequence[ChatCompletionChunk]) -> dict[int, str]:
+ return {index: name for index, name, _ in _tool_call_fragments(chunks) if name}
+
+
+def _function_arguments(call: JsonValue) -> JsonValue:
+ return object_value(object_value(call)["function"])["arguments"]
+
+
+def _contents(chunks: Sequence[ChatCompletionChunk]) -> Iterator[str]:
+ for chunk in chunks:
+ for choice in chunk.choices:
+ yield choice.delta.content or ""
+
+
+def _chat_text(chunks: Sequence[ChatCompletionChunk]) -> str:
+ return "".join(_contents(chunks))
+
+
+def test_chat_stream_through_the_openai_responses_bridge_sends_tool_arguments_once(gateway: Gateway) -> None:
+ with wire_server(answering(_two_calls_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire, _OPENAI_BRIDGE)
+ raw: Final = _openai(gateway).chat.completions.with_raw_response.create(
+ model=model,
+ messages=[{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ tools=CHAT_TOOL_PARAMS,
+ stream=True,
+ extra_body={"cache": NO_CACHE},
+ )
+ chunks: Final = list(raw.parse())
+ assert _arguments_by_index(chunks) == {0: ARGUMENTS, 1: SECOND_ARGUMENTS}, _arguments_by_index(chunks)
+ assert _names_by_index(chunks) == {0: "get_weather", 1: "get_forecast"}, _names_by_index(chunks)
+ assert _chat_text(chunks) == ANSWER
+ assert len({chunk.id for chunk in chunks}) == 1, {chunk.id for chunk in chunks}
+ assert_one_unstreamed_upstream_call(wire, _OPENAI_TARGET)
+ assert spend_statuses(raw.headers[CALL_ID]) == ["success"]
+
+
+async def test_async_chat_stream_through_the_azure_responses_bridge_sends_tool_arguments_once(gateway: Gateway) -> None:
+ with wire_server(answering(_call_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_azure_model(scenario, wire)
+ stream: Final = await _async_openai(gateway).chat.completions.create(
+ model=model,
+ messages=[{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ tools=CHAT_TOOL_PARAMS,
+ stream=True,
+ extra_body={"cache": NO_CACHE},
+ )
+ chunks: Final = [chunk async for chunk in stream]
+ assert _arguments_by_index(chunks) == {0: ARGUMENTS}, _arguments_by_index(chunks)
+ assert json.loads(_arguments_by_index(chunks)[0]) == json.loads(ARGUMENTS)
+ assert _chat_text(chunks) == ANSWER
+ assert_one_unstreamed_upstream_call(wire, _AZURE_TARGET)
+
+
+def test_chat_without_stream_through_the_bridge_returns_the_upstream_values(gateway: Gateway) -> None:
+ with wire_server(answering(_two_calls_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire, _OPENAI_BRIDGE)
+ response: Final = gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "messages": [{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ "tools": CHAT_TOOLS,
+ "cache": NO_CACHE,
+ },
+ )
+ assert response.status_code == 200, response.text
+ choice: Final = object_value(list_value(JSON_OBJECT.validate_json(response.content)["choices"])[0])
+ message: Final = object_value(choice["message"])
+ assert message["content"] == ANSWER, message
+ assert [_function_arguments(call) for call in list_value(message["tool_calls"])] == [
+ ARGUMENTS,
+ SECOND_ARGUMENTS,
+ ]
+ assert_one_unstreamed_upstream_call(wire, _OPENAI_TARGET)
+
+
+def test_messages_stream_through_the_azure_chat_bridge_gives_claude_tool_input_once(gateway: Gateway) -> None:
+ with wire_server(answering(_call_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_azure_model(scenario, wire)
+ with _anthropic(gateway).messages.stream(
+ model=model,
+ max_tokens=256,
+ messages=[{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ tools=ANTHROPIC_TOOL_PARAMS,
+ extra_body={"cache": NO_CACHE},
+ ) as stream:
+ partial_json: Final = "".join(
+ event.delta.partial_json
+ for event in stream
+ if event.type == "content_block_delta" and event.delta.type == "input_json_delta"
+ )
+ final: Final = stream.get_final_message()
+ assert partial_json == ARGUMENTS
+ tool_uses: Final = [block for block in final.content if block.type == "tool_use"]
+ assert [(block.name, block.input) for block in tool_uses] == [("get_weather", json.loads(ARGUMENTS))]
+ assert "".join(block.text for block in final.content if block.type == "text") == ANSWER
+ assert_one_unstreamed_upstream_call(wire, _AZURE_TARGET)
+
+
+async def test_async_messages_stream_through_the_openai_responses_bridge_keeps_summaries_apart(
+ gateway: Gateway,
+) -> None:
+ with wire_server(answering(_call_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ async with _async_anthropic(gateway).messages.stream(
+ model=model,
+ max_tokens=256,
+ messages=[{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ tools=ANTHROPIC_TOOL_PARAMS,
+ extra_body={"cache": NO_CACHE},
+ ) as stream:
+ final: Final = await stream.get_final_message()
+ thinking: Final = "".join(block.thinking for block in final.content if block.type == "thinking")
+ first, second = SUMMARIES
+ assert thinking.startswith(first) and thinking.endswith(second), thinking
+ separator: Final = thinking[len(first) : len(thinking) - len(second)]
+ assert separator and separator.strip() == "", repr(thinking)
+ tool_uses: Final = [block for block in final.content if block.type == "tool_use"]
+ assert [(block.name, block.input) for block in tool_uses] == [("get_weather", json.loads(ARGUMENTS))]
+ assert "".join(block.text for block in final.content if block.type == "text") == ANSWER
+ assert_one_unstreamed_upstream_call(wire, _OPENAI_TARGET)
+
+
+def test_raw_messages_stream_through_the_openai_responses_bridge_logs_once(gateway: Gateway) -> None:
+ with wire_server(answering(_call_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ call_id, events = stream_events(
+ gateway,
+ "/v1/messages",
+ {
+ "model": model,
+ "max_tokens": 256,
+ "messages": [{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ "tools": ANTHROPIC_TOOLS,
+ "cache": NO_CACHE,
+ },
+ )
+ deltas: Final = [object_value(event["delta"]) for event in events if event["type"] == "content_block_delta"]
+ assert "".join(string_value(delta.get("partial_json", "")) for delta in deltas) == ARGUMENTS
+ assert "".join(string_value(delta.get("text", "")) for delta in deltas) == ANSWER
+ assert_one_unstreamed_upstream_call(wire, _OPENAI_TARGET)
+ assert spend_statuses(call_id) == ["success"]
+
+
+def test_messages_without_stream_through_the_bridge_return_the_upstream_values(gateway: Gateway) -> None:
+ with wire_server(answering(_call_and_text)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ response: Final = gateway.request(
+ "POST",
+ "/v1/messages",
+ {
+ "model": model,
+ "max_tokens": 256,
+ "messages": [{"role": "user", "content": f"{QUESTION} {uuid.uuid4().hex}"}],
+ "tools": ANTHROPIC_TOOLS,
+ "cache": NO_CACHE,
+ },
+ )
+ assert response.status_code == 200, response.text
+ content: Final = tuple(map(object_value, list_value(JSON_OBJECT.validate_json(response.content)["content"])))
+ assert [block["input"] for block in content if block["type"] == "tool_use"] == [json.loads(ARGUMENTS)]
+ assert "".join(string_value(block["text"]) for block in content if block["type"] == "text") == ANSWER
+ assert_one_unstreamed_upstream_call(wire, _OPENAI_TARGET)
diff --git a/tests/integration/streaming/test_faked_responses_stream_cache_replay.py b/tests/integration/streaming/test_faked_responses_stream_cache_replay.py
new file mode 100644
index 00000000000..0c8c435db6e
--- /dev/null
+++ b/tests/integration/streaming/test_faked_responses_stream_cache_replay.py
@@ -0,0 +1,106 @@
+import os
+import uuid
+from dataclasses import dataclass
+from typing import Final
+
+import openai
+from integration._support.client import Gateway, eventually, string_value
+from integration._support.wire import Wire, wire_server
+from integration.streaming.faked_responses_case import (
+ ANSWER,
+ ARGUMENTS,
+ RESPONSES_TOOL_PARAMS,
+ RESPONSES_TOOLS,
+ answering,
+ assert_each_value_arrives_once,
+ every_item_kind,
+ faked_model,
+ function_call_item,
+ items_by_index,
+ message_item,
+ stream_events,
+)
+from openai.lib.streaming.responses import ResponseStreamEvent
+from openai.types.responses import ParsedResponse, ResponseOutputMessage
+from pydantic import JsonValue
+from redis import Redis
+
+_TARGET: Final = "/v1/responses"
+
+
+@dataclass(frozen=True, slots=True)
+class _SdkAnswer:
+ events: "tuple[ResponseStreamEvent[None], ...]"
+ final: ParsedResponse[None]
+ reached_upstream: bool
+
+
+def _cache_holds(needle: str) -> bool:
+ with Redis(host=os.environ["REDIS_HOST"], port=int(os.environ["REDIS_PORT"])) as store:
+ return any(needle.encode() in _bytes(store.get(key)) for key in store.scan_iter(count=1000, _type="STRING"))
+
+
+def _bytes(value: object) -> bytes:
+ return value if isinstance(value, bytes) else b""
+
+
+def _reached_upstream(wire: Wire) -> bool:
+ return bool([request for request in wire.drain() if request.method == "POST"])
+
+
+def _message_id(events: tuple[dict[str, JsonValue], ...], index: int) -> str:
+ return string_value(items_by_index(events, "response.output_item.done")[index]["id"])
+
+
+def test_replayed_stream_opens_every_item_empty_and_each_value_arrives_once(gateway: Gateway) -> None:
+ with wire_server(answering(every_item_kind)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ body: Final = {"model": model, "input": f"cached weather {uuid.uuid4().hex}", "tools": RESPONSES_TOOLS}
+ _, filled = stream_events(gateway, _TARGET, body)
+ message_id: Final = _message_id(filled, 1)
+ assert_each_value_arrives_once(filled, every_item_kind(message_id.removeprefix("msg_")))
+ assert len([request for request in wire.drain() if request.method == "POST"]) == 1
+ eventually(lambda: _cache_holds(message_id), bool, seconds=30)
+ _, replayed = stream_events(gateway, _TARGET, body)
+ assert not _reached_upstream(wire), "the repeated stream reached the upstream instead of the cache"
+ assert _message_id(replayed, 1) == message_id
+ added: Final = items_by_index(replayed, "response.output_item.added")
+ assert (added[1]["content"], added[2]["arguments"], added[0]["summary"]) == ([], "", []), added
+ assert_each_value_arrives_once(replayed, every_item_kind(message_id.removeprefix("msg_")))
+
+
+async def _sdk_attempt(client: openai.AsyncOpenAI, model: str, prompt: str, wire: Wire) -> _SdkAnswer:
+ async with client.responses.stream(model=model, input=prompt, tools=RESPONSES_TOOL_PARAMS) as stream:
+ events: Final = tuple([event async for event in stream])
+ final: Final = await stream.get_final_response()
+ return _SdkAnswer(events, final, _reached_upstream(wire))
+
+
+def _message_ids(response: ParsedResponse[None]) -> list[str]:
+ return [item.id for item in response.output if isinstance(item, ResponseOutputMessage)]
+
+
+async def test_async_openai_sdk_replay_snapshots_hold_each_value_once(gateway: Gateway) -> None:
+ with (
+ wire_server(answering(lambda identity: (message_item(identity), function_call_item(identity)))) as wire,
+ gateway.scenario() as scenario,
+ ):
+ model: Final = faked_model(scenario, wire)
+ prompt: Final = f"cached sdk weather {uuid.uuid4().hex}"
+ client: Final = openai.AsyncOpenAI(
+ base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0
+ )
+ first: Final = await _sdk_attempt(client, model, prompt, wire)
+ assert first.reached_upstream, first.final.id
+ message_ids: Final = _message_ids(first.final)
+ assert len(message_ids) == 1, message_ids
+ eventually(lambda: _cache_holds(message_ids[0]), bool, seconds=30)
+ replay: Final = await _sdk_attempt(client, model, prompt, wire)
+ assert not replay.reached_upstream, "the repeated SDK stream reached the upstream instead of the cache"
+ assert _message_ids(replay.final) == message_ids, (_message_ids(replay.final), message_ids)
+ text: Final = [event.snapshot for event in replay.events if event.type == "response.output_text.delta"]
+ arguments: Final = [
+ event.snapshot for event in replay.events if event.type == "response.function_call_arguments.delta"
+ ]
+ assert text and text[-1] == ANSWER, text[-1:]
+ assert arguments and arguments[-1] == ARGUMENTS, arguments[-1:]
diff --git a/tests/integration/streaming/test_faked_responses_stream_chaos.py b/tests/integration/streaming/test_faked_responses_stream_chaos.py
new file mode 100644
index 00000000000..f96538dfab6
--- /dev/null
+++ b/tests/integration/streaming/test_faked_responses_stream_chaos.py
@@ -0,0 +1,383 @@
+import asyncio
+import json
+import socket
+import threading
+import uuid
+from collections.abc import Iterator, Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from queue import SimpleQueue
+from types import MappingProxyType
+from typing import Final, Literal, TypeAlias
+from urllib.parse import urlsplit
+
+import httpx
+import psutil
+import pytest
+import yaml
+from integration._support.client import (
+ JSON_OBJECT,
+ Gateway,
+ eventually,
+ gateway_from_environment,
+ list_value,
+ object_value,
+ string_value,
+)
+from integration._support.database import read_rows
+from integration._support.process import OwnedProxy, graceful_stop_seconds, owned_proxy_process
+from integration._support.wire import Reply, Request, wire_server
+from integration.streaming.faked_responses_case import (
+ ANTHROPIC_TOOLS,
+ API_KEY,
+ CHAT_TOOLS,
+ FAKED_STREAM,
+ NO_CACHE,
+ RESPONSES_TOOLS,
+ assert_each_value_arrives_once,
+ function_call_item,
+ message_item,
+ response_body,
+)
+from pydantic import JsonValue, TypeAdapter
+
+pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)
+
+_RESPONSES_MODEL: Final = "faked-stream-chaos"
+_BRIDGE_MODEL: Final = "faked-stream-chaos-bridge"
+_MARKER_PREFIX: Final = "marker-"
+_DROP: Final = "drop-now"
+_HEADERS: Final[Mapping[str, str]] = MappingProxyType({"anthropic-version": "2023-06-01"})
+
+Kind: TypeAlias = Literal["responses", "chat", "messages"]
+_KINDS: Final[tuple[Kind, ...]] = ("responses", "chat", "messages")
+
+
+@dataclass(frozen=True, slots=True)
+class _Call:
+ kind: Kind
+ marker: str
+ dropped: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class _Served:
+ call: _Call
+ status: int
+ text: str
+ call_id: str
+
+
+_ADDRESS: Final = TypeAdapter(tuple[str, int])
+
+
+@dataclass(frozen=True, slots=True)
+class _Rig:
+ port: int
+ proxy: OwnedProxy
+
+ @property
+ def gateway(self) -> Gateway:
+ return self.proxy.gateway
+
+
+def _free_port() -> int:
+ with socket.socket() as reserve:
+ reserve.bind(("127.0.0.1", 0))
+ return _ADDRESS.validate_python(reserve.getsockname())[1]
+
+
+def _deployment(name: str, model: str, port: int) -> dict[str, JsonValue]:
+ return {
+ "model_name": name,
+ "litellm_params": {"model": model, "api_base": f"http://127.0.0.1:{port}/v1", "api_key": API_KEY},
+ "model_info": FAKED_STREAM,
+ }
+
+
+def _config(port: int, directory: Path) -> Path:
+ stock: Final = JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ router_settings: Final = object_value(stock.get("router_settings") or {})
+ path: Final = directory / "faked-stream-chaos.yaml"
+ path.write_text(
+ yaml.safe_dump(
+ {
+ **stock,
+ "model_list": [
+ _deployment(_RESPONSES_MODEL, "openai/faked-stream-backend", port),
+ _deployment(_BRIDGE_MODEL, "openai/responses/faked-stream-backend", port),
+ ],
+ "router_settings": {**router_settings, "num_retries": 0},
+ }
+ )
+ )
+ return path
+
+
[email protected](scope="module")
+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rig]:
+ directory: Final = tmp_path_factory.mktemp("faked-stream-chaos")
+ port: Final = _free_port()
+ with (
+ gateway_from_environment() as shared,
+ owned_proxy_process(shared, directory, {}, config=_config(port, directory), workers=2) as owned,
+ ):
+ yield _Rig(port, owned)
+
+
+def _answer(marker: str) -> str:
+ return f"answer marker-{marker}"
+
+
+def _arguments(marker: str) -> str:
+ return json.dumps({"city": "Paris", "marker": marker})
+
+
+def _output(marker: str) -> tuple[dict[str, JsonValue], ...]:
+ return (message_item(marker, _answer(marker)), function_call_item(marker, _arguments(marker)))
+
+
+def _markers(text: str) -> tuple[str, ...]:
+ return tuple(part[:32] for part in text.split(_MARKER_PREFIX)[1:])
+
+
+def _newest_marker(request: Request) -> str:
+ found: Final = _markers(request.body.decode())
+ assert request.method == "POST" and found, (request.target, request.body)
+ return found[-1]
+
+
+def _respond(request: Request) -> Reply:
+ marker: Final = _newest_marker(request)
+ if _DROP.encode() in request.body:
+ return Reply(drop_connection=True)
+ return Reply(body=json.dumps(response_body(marker, _output(marker))).encode())
+
+
+def _body(call: _Call) -> Mapping[str, JsonValue]:
+ prompt: Final = f"{call.kind} marker-{call.marker}" + (f" {_DROP}" if call.dropped else "")
+ common: Final[Mapping[str, JsonValue]] = {"stream": True, "num_retries": 0, "cache": NO_CACHE}
+ match call.kind:
+ case "responses":
+ return {**common, "model": _RESPONSES_MODEL, "input": prompt, "tools": RESPONSES_TOOLS}
+ case "chat":
+ return {
+ **common,
+ "model": _BRIDGE_MODEL,
+ "messages": [{"role": "user", "content": prompt}],
+ "tools": CHAT_TOOLS,
+ }
+ case "messages":
+ return {
+ **common,
+ "model": _RESPONSES_MODEL,
+ "max_tokens": 256,
+ "messages": [{"role": "user", "content": prompt}],
+ "tools": ANTHROPIC_TOOLS,
+ }
+
+
+def _path(kind: Kind) -> str:
+ match kind:
+ case "responses":
+ return "/v1/responses"
+ case "chat":
+ return "/v1/chat/completions"
+ case "messages":
+ return "/v1/messages"
+
+
+def _calls(count: int, drop_every: int = 0) -> tuple[_Call, ...]:
+ return tuple(
+ _Call(_KINDS[index % len(_KINDS)], uuid.uuid4().hex, drop_every > 0 and index % drop_every == drop_every - 1)
+ for index in range(count)
+ )
+
+
+async def _send(client: httpx.AsyncClient, key: str, call: _Call) -> _Served:
+ async with client.stream(
+ "POST", _path(call.kind), json=_body(call), headers={"Authorization": f"Bearer {key}", **_HEADERS}
+ ) as response:
+ raw: Final = await response.aread()
+ return _Served(call, response.status_code, raw.decode(), response.headers["x-litellm-call-id"])
+
+
+async def _burst(
+ gateway: Gateway, calls: tuple[_Call, ...], *, tolerate_transport_errors: bool = False
+) -> tuple[_Served, ...]:
+ async with httpx.AsyncClient(base_url=str(gateway.client.base_url), timeout=90, trust_env=False) as client:
+ results: Final = await asyncio.gather(
+ *(_send(client, gateway.key, call) for call in calls), return_exceptions=tolerate_transport_errors
+ )
+ for result in results:
+ assert not isinstance(result, BaseException) or isinstance(result, httpx.TransportError), repr(result)
+ return tuple(result for result in results if isinstance(result, _Served))
+
+
+def _frames(text: str) -> tuple[dict[str, JsonValue], ...]:
+ return tuple(
+ JSON_OBJECT.validate_json(line.removeprefix("data: "))
+ for line in text.splitlines()
+ if line.startswith("data: {")
+ )
+
+
+def _chat_deltas(frames: Sequence[Mapping[str, JsonValue]]) -> Iterator[dict[str, JsonValue]]:
+ for frame in frames:
+ for choice in list_value(frame.get("choices") or []):
+ yield object_value(object_value(choice)["delta"])
+
+
+def _chat_tool_calls(deltas: Sequence[Mapping[str, JsonValue]]) -> Iterator[JsonValue]:
+ for delta in deltas:
+ yield from list_value(delta.get("tool_calls") or [])
+
+
+def _function_arguments(call: JsonValue) -> str:
+ function: Final = object_value(call).get("function")
+ return string_value(function.get("arguments") or "") if isinstance(function, dict) else ""
+
+
+def _streamed_values(served: _Served) -> tuple[str, str]:
+ frames: Final = _frames(served.text)
+ match served.call.kind:
+ case "responses":
+ assert_each_value_arrives_once(frames, _output(served.call.marker))
+ return _answer(served.call.marker), _arguments(served.call.marker)
+ case "chat":
+ deltas: Final = tuple(_chat_deltas(frames))
+ return "".join(string_value(delta.get("content") or "") for delta in deltas), "".join(
+ map(_function_arguments, _chat_tool_calls(deltas))
+ )
+ case "messages":
+ blocks: Final = tuple(
+ object_value(frame["delta"]) for frame in frames if frame["type"] == "content_block_delta"
+ )
+ return "".join(string_value(block.get("text", "")) for block in blocks), "".join(
+ string_value(block.get("partial_json", "")) for block in blocks
+ )
+
+
+def _assert_each_value_once(served: _Served) -> None:
+ assert served.status == 200, (served.call, served.status, served.text[:500])
+ assert _streamed_values(served) == (_answer(served.call.marker), _arguments(served.call.marker)), (
+ served.call,
+ served.text[:2000],
+ )
+
+
+def _assert_failed_without_a_value(served: _Served) -> None:
+ assert served.status >= 400 or '"error"' in served.text, (served.call, served.status, served.text[:500])
+ assert _arguments(served.call.marker) not in served.text, (served.call, served.text[:500])
+
+
+def _assert_forwarded(received: tuple[Request, ...], calls: Sequence[_Call]) -> None:
+ posts: Final = tuple(request for request in received if request.method == "POST")
+ assert all(JSON_OBJECT.validate_json(request.body).get("stream") is not True for request in posts), posts
+ reached: Final = frozenset(_markers(b"\n".join(request.body for request in posts).decode()))
+ assert reached >= frozenset(call.marker for call in calls), sorted(reached)
+
+
+def _rows(call_ids: Sequence[str]) -> Sequence[Mapping[str, JsonValue]]:
+ return eventually(
+ lambda: read_rows(
+ 'SELECT litellm_call_id, status FROM "LiteLLM_SpendLogs" WHERE litellm_call_id = ANY(string_to_array(%s, %s))',
+ (",".join(call_ids), ","),
+ ),
+ lambda found: len(found) >= len(call_ids),
+ seconds=70,
+ )
+
+
+def _assert_each_logged_once(served: Sequence[_Served]) -> None:
+ rows: Final = _rows(tuple(item.call_id for item in served))
+ assert sorted(string_value(row["litellm_call_id"]) for row in rows) == sorted(item.call_id for item in served), rows
+ assert all(row["status"] == "success" for row in rows), rows
+
+
+def _open_upstream_connections(pid: int, upstream: str) -> int:
+ port: Final = urlsplit(upstream).port
+ return sum(
+ 1
+ for connection in psutil.Process(pid).net_connections(kind="tcp")
+ if connection.status == psutil.CONN_ESTABLISHED and connection.raddr and connection.raddr.port == port
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class _Held:
+ release: threading.Event
+ markers: SimpleQueue[str]
+
+ def respond(self, request: Request) -> Reply:
+ self.markers.put(_newest_marker(request))
+ assert self.release.wait(timeout=60), "The burst was never released"
+ return _respond(request)
+
+
+async def _held_burst(gateway: Gateway, calls: tuple[_Call, ...], held: _Held) -> asyncio.Task[tuple[_Served, ...]]:
+ burst: Final = asyncio.create_task(_burst(gateway, calls, tolerate_transport_errors=True))
+ await asyncio.to_thread(eventually, held.markers.qsize, lambda size: size == len(calls), 60)
+ return burst
+
+
+def _held_by(rig: _Rig, upstream: str) -> Mapping[int, int]:
+ return MappingProxyType({pid: _open_upstream_connections(pid, upstream) for pid in rig.proxy.worker_pids()})
+
+
+async def test_held_mixed_burst_spreads_over_both_workers_and_each_value_arrives_once(rig: _Rig) -> None:
+ calls: Final = _calls(30)
+ held: Final = _Held(threading.Event(), SimpleQueue())
+ with wire_server(held.respond, port=rig.port) as wire:
+ burst: Final = await _held_burst(rig.gateway, calls, held)
+ held_by: Final = _held_by(rig, wire.url)
+ held.release.set()
+ served: Final = await burst
+ assert len(held_by) == 2 and all(held_by.values()) and sum(held_by.values()) == 30, held_by
+ assert len(served) == 30
+ for item in served:
+ _assert_each_value_once(item)
+ _assert_forwarded(wire.drain(), calls)
+ _assert_each_logged_once(served)
+
+
+async def test_upstream_dropping_every_third_connection_fails_only_those_calls(rig: _Rig) -> None:
+ calls: Final = _calls(24, drop_every=3)
+ with wire_server(_respond, port=rig.port) as wire:
+ served: Final = await _burst(rig.gateway, calls)
+ assert len(served) == 24
+ healthy: Final = tuple(item for item in served if not item.call.dropped)
+ for item in healthy:
+ _assert_each_value_once(item)
+ dropped: Final = tuple(item for item in served if item.call.dropped)
+ assert len(dropped) == 8, dropped
+ for item in dropped:
+ _assert_failed_without_a_value(item)
+ follow_up: Final = await _burst(rig.gateway, _calls(3))
+ for item in follow_up:
+ _assert_each_value_once(item)
+ _assert_forwarded(wire.drain(), calls)
+ _assert_each_logged_once((*healthy, *follow_up))
+
+
+async def test_worker_sigkill_mid_burst_leaves_the_sibling_streaming_each_value_once(rig: _Rig) -> None:
+ calls: Final = _calls(21)
+ held: Final = _Held(threading.Event(), SimpleQueue())
+ with wire_server(held.respond, port=rig.port) as wire:
+ burst: Final = await _held_burst(rig.gateway, calls, held)
+ held_by: Final = _held_by(rig, wire.url)
+ assert len(held_by) == 2 and sum(held_by.values()) == 21, held_by
+ victim_pid, survivor_pid = sorted(held_by, key=held_by.__getitem__)
+ with rig.proxy.replacing_worker(victim_pid) as kill:
+ kill.freeze()
+ await asyncio.to_thread(kill)
+ held.release.set()
+ served: Final = await burst
+ assert len(served) == held_by[survivor_pid], (held_by, len(served))
+ for item in served:
+ _assert_each_value_once(item)
+ follow_up: Final = await _burst(rig.gateway, _calls(3))
+ for item in follow_up:
+ _assert_each_value_once(item)
+ _assert_forwarded(wire.drain(), (*calls, *(item.call for item in follow_up)))
+ _assert_each_logged_once((*served, *follow_up))
diff --git a/tests/integration/streaming/test_faked_responses_stream_guardrail_blocks.py b/tests/integration/streaming/test_faked_responses_stream_guardrail_blocks.py
new file mode 100644
index 00000000000..ad3db17eac5
--- /dev/null
+++ b/tests/integration/streaming/test_faked_responses_stream_guardrail_blocks.py
@@ -0,0 +1,173 @@
+import json
+import uuid
+from collections.abc import Iterator
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final
+
+import pytest
+import yaml
+from integration._support.client import JSON_OBJECT, Gateway, gateway_from_environment, object_value
+from integration._support.process import graceful_stop_seconds, owned_proxy
+from integration._support.wire import Reply, Request, wire_server
+from integration.streaming.faked_responses_case import (
+ NO_CACHE,
+ answering,
+ completed_output,
+ faked_model,
+ items_by_index,
+ joined,
+ message_item,
+ rebuilt,
+ responses_request,
+ stream_events,
+ streamed,
+ values,
+)
+from pydantic import JsonValue
+
+pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)
+
+_TARGET: Final = "/v1/responses"
+_PRE_CALL_DENIAL: Final = "This request is not allowed by policy."
+_LARGE_DENIAL: Final = ("Denied by policy, see the handbook. " * 200)[:5000]
+_OUTPUT_DENIAL: Final = "Output withheld by policy."
+_TRIGGER: Final = "FORBIDDEN"
+_LEAKY_ANSWER: Final = f"Safe start. {_TRIGGER} tail text that keeps going for a while."
+_ALLOWED: Final = json.dumps({"action": "NONE", "outputs": [], "assessments": []}).encode()
+_INTERVENED: Final = json.dumps(
+ {
+ "action": "GUARDRAIL_INTERVENED",
+ "outputs": [{"text": _OUTPUT_DENIAL}],
+ "assessments": [{"topicPolicy": {"topics": [{"name": "forbidden", "type": "DENY", "action": "BLOCKED"}]}}],
+ }
+).encode()
+
+
+@dataclass(frozen=True, slots=True)
+class _Rails:
+ gateway: Gateway
+ pre_call: str
+ large_pre_call: str
+ buffered_post_call: str
+ live_post_call: str
+
+
+def _rail(name: str, mode: str, code: str) -> dict[str, JsonValue]:
+ return {
+ "guardrail_name": name,
+ "litellm_params": {"guardrail": "custom_code", "mode": mode, "default_on": False, "custom_code": code},
+ }
+
+
+def _denying(denial: str) -> str:
+ return f"def apply_guardrail(inputs, request_data, input_type):\n return block({denial!r})\n"
+
+
+def _bedrock_policy(request: Request) -> Reply:
+ return Reply(body=_INTERVENED if _TRIGGER in request.body.decode() else _ALLOWED)
+
+
+def _bedrock_rail(name: str, endpoint: str, *, buffer_until_moderated: bool) -> dict[str, JsonValue]:
+ return {
+ "guardrail_name": name,
+ "litellm_params": {
+ "guardrail": "bedrock",
+ "mode": "post_call",
+ "default_on": False,
+ "disable_exception_on_block": True,
+ "streaming_buffer_until_moderated": buffer_until_moderated,
+ "guardrailIdentifier": "synthetic" + uuid.uuid4().hex[:8],
+ "guardrailVersion": "DRAFT",
+ "aws_region_name": "us-east-1",
+ "aws_access_key_id": "AKIASYNTHETICGUARDRAIL",
+ "aws_secret_access_key": "synthetic-secret",
+ "aws_bedrock_runtime_endpoint": endpoint,
+ },
+ }
+
+
[email protected](scope="module")
+def rails(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rails]:
+ directory: Final = tmp_path_factory.mktemp("faked-stream-guardrails")
+ suffix: Final = uuid.uuid4().hex
+ pre_call: Final = f"faked-pre-{suffix}"
+ large_pre_call: Final = f"faked-large-pre-{suffix}"
+ buffered_post_call: Final = f"faked-buffered-post-{suffix}"
+ live_post_call: Final = f"faked-live-post-{suffix}"
+ stock: Final = JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ config: Final = directory / "faked-stream-guardrails.yaml"
+ with wire_server(_bedrock_policy) as policy:
+ config.write_text(
+ yaml.safe_dump(
+ {
+ **stock,
+ "guardrails": [
+ _rail(pre_call, "pre_call", _denying(_PRE_CALL_DENIAL)),
+ _rail(large_pre_call, "pre_call", _denying(_LARGE_DENIAL)),
+ _bedrock_rail(buffered_post_call, policy.url, buffer_until_moderated=True),
+ _bedrock_rail(live_post_call, policy.url, buffer_until_moderated=False),
+ ],
+ }
+ )
+ )
+ with gateway_from_environment() as shared, owned_proxy(shared, directory, {}, config=config) as candidate:
+ yield _Rails(candidate, pre_call, large_pre_call, buffered_post_call, live_post_call)
+
+
+ ("rail", "denial", "forwarded"),
+ (
+ ("pre_call", _PRE_CALL_DENIAL, []),
+ ("large_pre_call", _LARGE_DENIAL, []),
+ ("buffered_post_call", _OUTPUT_DENIAL, [_TARGET]),
+ ),
+ ids=("pre_call", "large_pre_call", "buffered_post_call"),
+)
+def test_block_before_any_output_streams_a_message_that_opens_empty_and_carries_the_denial_once(
+ rails: _Rails, rail: str, denial: str, forwarded: list[str]
+) -> None:
+ with (
+ wire_server(answering(lambda identity: (message_item(identity, _LEAKY_ANSWER),))) as wire,
+ rails.gateway.scenario() as scenario,
+ ):
+ model: Final = faked_model(scenario, wire)
+ _, events = streamed(
+ rails.gateway, _TARGET, responses_request(model, cache=NO_CACHE, guardrails=[getattr(rails, rail)])
+ )
+ added: Final = items_by_index(events, "response.output_item.added")
+ assert list(added) == [0], added
+ assert (added[0]["type"], added[0]["content"], added[0]["status"]) == ("message", [], "in_progress"), added
+ parts: Final = [
+ object_value(event["part"]) for event in events if event["type"] == "response.content_part.added"
+ ]
+ assert [part["text"] for part in parts] == [""], parts
+ assert joined(events, "response.output_text.delta", 0) == denial
+ assert values(rebuilt(events)[0]) == [["output_text", denial]]
+ assert values(items_by_index(events, "response.output_item.done")[0]) == [["output_text", denial]]
+ assert [values(item) for item in completed_output(events)] == [[["output_text", denial]]]
+ assert [request.target for request in wire.drain() if request.method == "POST"] == forwarded
+
+
+def test_mid_stream_block_closes_the_open_message_and_opens_the_denial_empty(rails: _Rails) -> None:
+ with (
+ wire_server(answering(lambda identity: (message_item(identity, _LEAKY_ANSWER),))) as wire,
+ rails.gateway.scenario() as scenario,
+ ):
+ model: Final = faked_model(scenario, wire)
+ _, events = stream_events(
+ rails.gateway, _TARGET, responses_request(model, cache=NO_CACHE, guardrails=[rails.live_post_call])
+ )
+ added: Final = items_by_index(events, "response.output_item.added")
+ done: Final = items_by_index(events, "response.output_item.done")
+ assert sorted(added) == sorted(done) == [0, 1], [event["type"] for event in events]
+ assert (added[1]["type"], added[1]["content"], added[1]["status"]) == ("message", [], "in_progress"), added[1]
+ streamed_before_block: Final = joined(events, "response.output_text.delta", 0)
+ assert _LEAKY_ANSWER.startswith(streamed_before_block), streamed_before_block
+ assert _LEAKY_ANSWER != streamed_before_block
+ assert values(rebuilt(events)[0]) == values(done[0]), (rebuilt(events)[0], done[0])
+ assert joined(events, "response.output_text.delta", 1) == _OUTPUT_DENIAL
+ assert values(rebuilt(events)[1]) == [["output_text", _OUTPUT_DENIAL]]
+ assert values(done[1]) == [["output_text", _OUTPUT_DENIAL]]
+ assert values(completed_output(events)[-1]) == [["output_text", _OUTPUT_DENIAL]]
+ assert [request.target for request in wire.drain() if request.method == "POST"] == [_TARGET]
diff --git a/tests/integration/streaming/test_faked_responses_stream_items.py b/tests/integration/streaming/test_faked_responses_stream_items.py
new file mode 100644
index 00000000000..cb028310e26
--- /dev/null
+++ b/tests/integration/streaming/test_faked_responses_stream_items.py
@@ -0,0 +1,309 @@
+import json
+import uuid
+from typing import Final
+
+import httpx
+import openai
+import pytest
+from integration._support.client import JSON_OBJECT, Gateway, list_value, object_value, string_value
+from integration._support.wire import Reply, Request, wire_server
+from integration.streaming.faked_responses_case import (
+ ANSWER,
+ ARGUMENTS,
+ NO_CACHE,
+ RESPONSES_TOOL_PARAMS,
+ SECOND_ARGUMENTS,
+ SQL,
+ SUMMARIES,
+ answering,
+ assert_each_value_arrives_once,
+ assert_one_unstreamed_upstream_call,
+ completed_output,
+ custom_tool_call_item,
+ data_events,
+ every_item_kind,
+ faked_model,
+ function_call_item,
+ items_by_index,
+ joined,
+ message_item,
+ reasoning_item,
+ responses_request,
+ spend_statuses,
+ stream_events,
+ values,
+)
+from pydantic import JsonValue
+
+_TARGET: Final = "/v1/responses"
+_LARGE: Final = 5000
+
+
+def _openai(gateway: Gateway) -> openai.OpenAI:
+ return openai.OpenAI(base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0)
+
+
+def _async_openai(gateway: Gateway) -> openai.AsyncOpenAI:
+ return openai.AsyncOpenAI(base_url=str(gateway.client.base_url) + "/v1", api_key=gateway.key, max_retries=0)
+
+
+def test_raw_stream_opens_every_item_empty_and_each_value_arrives_once(gateway: Gateway) -> None:
+ with wire_server(answering(every_item_kind)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ call_id, events = stream_events(gateway, _TARGET, responses_request(model, cache=NO_CACHE))
+ assert_one_unstreamed_upstream_call(wire, _TARGET)
+ added: Final = items_by_index(events, "response.output_item.added")
+ assert [added[index]["type"] for index in sorted(added)] == [
+ "reasoning",
+ "message",
+ "function_call",
+ "custom_tool_call",
+ "message",
+ ], added
+ assert added[0]["summary"] == [], added[0]
+ assert (added[1]["content"], added[1]["status"]) == ([], "in_progress"), added[1]
+ assert (added[2]["arguments"], added[2]["status"]) == ("", "in_progress"), added[2]
+ assert added[3]["input"] == "", added[3]
+ assert (added[4]["content"], added[4]["status"]) == ([], "in_progress"), added[4]
+ summary_parts: Final = [
+ (event["summary_index"], object_value(event["part"])["text"])
+ for event in events
+ if event["type"] == "response.reasoning_summary_part.added"
+ ]
+ assert summary_parts == [(0, ""), (1, "")], summary_parts
+ assert [
+ joined(events, "response.reasoning_summary_text.delta", 0, summary_index=index) for index in (0, 1)
+ ] == [*SUMMARIES]
+ assert joined(events, "response.output_text.delta", 1) == ANSWER
+ assert joined(events, "response.function_call_arguments.delta", 2) == ARGUMENTS
+ assert joined(events, "response.custom_tool_call_input.delta", 3) == SQL
+ custom_done: Final = [event for event in events if event["type"] == "response.custom_tool_call_input.done"]
+ assert [(event["output_index"], event["input"]) for event in custom_done] == [(3, SQL)], custom_done
+ identity: Final = string_value(object_value(added[1])["id"]).removeprefix("msg_")
+ assert_each_value_arrives_once(events, every_item_kind(identity))
+ assert spend_statuses(call_id) == ["success"]
+
+
+def test_openai_sdk_stream_snapshots_hold_each_value_once(gateway: Gateway) -> None:
+ with wire_server(answering(lambda identity: (message_item(identity), function_call_item(identity)))) as wire:
+ with gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ with _openai(gateway).responses.stream(
+ model=model,
+ input=f"weather {uuid.uuid4().hex}",
+ tools=RESPONSES_TOOL_PARAMS,
+ extra_body={"cache": NO_CACHE},
+ ) as stream:
+ events: Final = list(stream)
+ final: Final = stream.get_final_response()
+ text_snapshots: Final = [event.snapshot for event in events if event.type == "response.output_text.delta"]
+ argument_snapshots: Final = [
+ event.snapshot for event in events if event.type == "response.function_call_arguments.delta"
+ ]
+ assert text_snapshots and text_snapshots[-1] == ANSWER, text_snapshots[-1:]
+ assert argument_snapshots and argument_snapshots[-1] == ARGUMENTS, argument_snapshots[-1:]
+ assert final.output_text == ANSWER
+ calls: Final = [item for item in final.output if item.type == "function_call"]
+ assert [call.arguments for call in calls] == [ARGUMENTS], final.output
+ assert_one_unstreamed_upstream_call(wire, _TARGET)
+
+
+async def test_async_openai_sdk_stream_snapshots_keep_two_calls_and_a_message_apart(gateway: Gateway) -> None:
+ def output(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (
+ function_call_item(identity),
+ function_call_item(identity, SECOND_ARGUMENTS, "get_forecast"),
+ message_item(identity),
+ )
+
+ with wire_server(answering(output)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ async with _async_openai(gateway).responses.stream(
+ model=model,
+ input=f"weather {uuid.uuid4().hex}",
+ tools=RESPONSES_TOOL_PARAMS,
+ extra_body={"cache": NO_CACHE},
+ ) as stream:
+ events: Final = [event async for event in stream]
+ final: Final = await stream.get_final_response()
+ last_arguments: Final = {
+ event.output_index: event.snapshot
+ for event in events
+ if event.type == "response.function_call_arguments.delta"
+ }
+ assert last_arguments == {0: ARGUMENTS, 1: SECOND_ARGUMENTS}, last_arguments
+ last_text: Final = [event.snapshot for event in events if event.type == "response.output_text.delta"]
+ assert last_text and last_text[-1] == ANSWER, last_text[-1:]
+ assert final.output_text == ANSWER
+ assert_one_unstreamed_upstream_call(wire, _TARGET)
+
+
+def test_non_stream_answer_carries_the_upstream_output_unchanged(gateway: Gateway) -> None:
+ with wire_server(answering(every_item_kind)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ response: Final = gateway.request("POST", _TARGET, responses_request(model, cache=NO_CACHE))
+ assert response.status_code == 200, response.text
+ output: Final = tuple(map(object_value, list_value(JSON_OBJECT.validate_json(response.content)["output"])))
+ identity: Final = string_value(output[1]["id"]).removeprefix("msg_")
+ assert [(item["type"], item["id"], values(item)) for item in output] == [
+ (item["type"], item["id"], values(item)) for item in every_item_kind(identity)
+ ], output
+ assert_one_unstreamed_upstream_call(wire, _TARGET)
+
+
+def test_an_item_type_the_fake_stream_does_not_split_opens_as_its_done_value(gateway: Gateway) -> None:
+ def output(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ search: Final[dict[str, JsonValue]] = {
+ "type": "web_search_call",
+ "id": f"ws_{identity}",
+ "status": "completed",
+ "action": {"type": "search", "query": "paris weather"},
+ }
+ return (search,)
+
+ with wire_server(answering(output)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ _, events = stream_events(gateway, _TARGET, responses_request(model, cache=NO_CACHE))
+ added: Final = items_by_index(events, "response.output_item.added")
+ done: Final = items_by_index(events, "response.output_item.done")
+ assert list(added) == list(done) == [0], (added, done)
+ assert added[0] == done[0], (added[0], done[0])
+ action: Final = object_value(done[0]["action"])
+ assert (action["type"], action["query"]) == ("search", "paris weather"), action
+ assert [item["id"] for item in completed_output(events)] == [done[0]["id"]]
+
+
[email protected]("status", (400, 401, 404))
+def test_upstream_error_reaches_the_caller_and_the_next_stream_is_served(gateway: Gateway, status: int) -> None:
+ message: Final = f"scripted upstream failure {uuid.uuid4().hex}"
+ failure: Final = Reply(
+ status=status,
+ body=json.dumps({"error": {"message": message, "type": "invalid_request_error", "code": None}}).encode(),
+ )
+ healthy: Final = answering(lambda identity: (message_item(identity),))
+
+ def respond(request: Request) -> Reply:
+ return failure if b"fail-now" in request.body else healthy(request)
+
+ with wire_server(respond) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ with gateway.client.stream(
+ "POST",
+ _TARGET,
+ json={**responses_request(model, cache=NO_CACHE), "input": "fail-now", "stream": True},
+ headers={"Authorization": f"Bearer {gateway.key}"},
+ ) as failed:
+ failed.read()
+ assert failed.status_code == status, failed.text
+ assert message in failed.text, failed.text
+ _, events = stream_events(gateway, _TARGET, responses_request(model, cache=NO_CACHE))
+ identity: Final = string_value(items_by_index(events, "response.output_item.done")[0]["id"]).removeprefix(
+ "msg_"
+ )
+ assert_each_value_arrives_once(events, (message_item(identity),))
+ assert [request.target for request in wire.drain() if request.method == "POST"] == [_TARGET, _TARGET]
+
+
+def test_empty_values_open_empty_and_close_empty(gateway: Gateway) -> None:
+ def output(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (
+ reasoning_item(identity, ()),
+ message_item(identity, ""),
+ function_call_item(identity, ""),
+ custom_tool_call_item(identity, ""),
+ )
+
+ with wire_server(answering(output)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ _, events = stream_events(gateway, _TARGET, responses_request(model, cache=NO_CACHE))
+ identity: Final = string_value(items_by_index(events, "response.output_item.done")[1]["id"]).removeprefix(
+ "msg_"
+ )
+ assert_each_value_arrives_once(events, output(identity))
+ assert joined(events, "response.function_call_arguments.delta", 2) == ""
+ assert_one_unstreamed_upstream_call(wire, _TARGET)
+
+
+def test_five_kilobyte_arguments_and_text_arrive_once(gateway: Gateway) -> None:
+ arguments: Final = json.dumps({"notes": ("détail " * _LARGE)[: _LARGE - 13]}, ensure_ascii=False)
+ text: Final = ("Long answer, part " * _LARGE)[:_LARGE]
+
+ def output(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (message_item(identity, text), function_call_item(identity, arguments))
+
+ with wire_server(answering(output)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ call_id, events = stream_events(gateway, _TARGET, responses_request(model, cache=NO_CACHE))
+ assert len(arguments) == _LARGE and len(text) == _LARGE
+ assert joined(events, "response.output_text.delta", 0) == text
+ assert joined(events, "response.function_call_arguments.delta", 1) == arguments
+ identity: Final = string_value(items_by_index(events, "response.output_item.done")[0]["id"]).removeprefix(
+ "msg_"
+ )
+ assert_each_value_arrives_once(events, output(identity))
+ assert_one_unstreamed_upstream_call(wire, _TARGET)
+ assert spend_statuses(call_id) == ["success"]
+
+
+def test_arguments_sent_as_an_object_never_break_the_stream_or_the_next_request(gateway: Gateway) -> None:
+ malformed: Final[dict[str, JsonValue]] = {"city": "Paris"}
+
+ def output(identity: str) -> tuple[dict[str, JsonValue], ...]:
+ return (function_call_item(identity, malformed),)
+
+ with wire_server(answering(output)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ with gateway.client.stream(
+ "POST",
+ _TARGET,
+ json={**responses_request(model, cache=NO_CACHE), "stream": True},
+ headers={"Authorization": f"Bearer {gateway.key}"},
+ ) as response:
+ body: Final = response.read().decode()
+ assert response.status_code in (200, 400, 500), body
+ if response.status_code == 200:
+ events: Final = data_events(iter(body.splitlines()))
+ assert items_by_index(events, "response.output_item.done")[0]["arguments"] == malformed, body
+ healthy: Final = gateway.request("POST", _TARGET, responses_request(model, cache=NO_CACHE))
+ assert healthy.status_code == 200, healthy.text
+ assert healthy.json()["output"][0]["arguments"] == malformed, healthy.text
+ assert len([request for request in wire.drain() if request.method == "POST"]) == 2
+
+
+def test_identical_uncached_streams_each_reach_the_upstream_and_log_once(gateway: Gateway) -> None:
+ with wire_server(answering(lambda identity: (message_item(identity),))) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ body: Final = responses_request(model, cache=NO_CACHE)
+ first_call, first = stream_events(gateway, _TARGET, body)
+ second_call, second = stream_events(gateway, _TARGET, body)
+ assert first_call != second_call
+ first_id: Final = string_value(items_by_index(first, "response.output_item.done")[0]["id"])
+ second_id: Final = string_value(items_by_index(second, "response.output_item.done")[0]["id"])
+ assert first_id != second_id
+ assert_each_value_arrives_once(first, (message_item(first_id.removeprefix("msg_")),))
+ assert_each_value_arrives_once(second, (message_item(second_id.removeprefix("msg_")),))
+ assert [request.target for request in wire.drain() if request.method == "POST"] == [_TARGET, _TARGET]
+ assert spend_statuses(first_call) == ["success"]
+ assert spend_statuses(second_call) == ["success"]
+
+
+def test_client_that_drops_the_stream_after_the_first_event_leaves_the_next_stream_whole(gateway: Gateway) -> None:
+ with wire_server(answering(every_item_kind)) as wire, gateway.scenario() as scenario:
+ model: Final = faked_model(scenario, wire)
+ with httpx.Client(base_url=str(gateway.client.base_url), timeout=60, trust_env=False) as client:
+ with client.stream(
+ "POST",
+ _TARGET,
+ json={**responses_request(model, cache=NO_CACHE), "stream": True},
+ headers={"Authorization": f"Bearer {gateway.key}"},
+ ) as dropped:
+ assert dropped.status_code == 200
+ first: Final = next(line for line in dropped.iter_lines() if line.startswith("data: {"))
+ assert json.loads(first.removeprefix("data: "))["type"] == "response.created", first
+ _, events = stream_events(gateway, _TARGET, responses_request(model, cache=NO_CACHE))
+ identity: Final = string_value(items_by_index(events, "response.output_item.done")[1]["id"]).removeprefix(
+ "msg_"
+ )
+ assert_each_value_arrives_once(events, every_item_kind(identity))
+ assert [request.target for request in wire.drain() if request.method == "POST"] == [_TARGET, _TARGET]
+ assert gateway.client.get("/health/liveliness").status_code == 200
diff --git a/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py b/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py
index fdf3fd62eff..bf871210074 100644
--- a/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py
+++ b/tests/unit/llms/openai/responses/test_openai_responses_guardrail_handler.py
@@ -2147,6 +2147,36 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:
)
assert undeliverable.value.reason == "no stream event carries the rewritten call_id call_999"
+ @pytest.mark.asyncio
+ async def test_masking_guardrail_hides_a_faked_custom_tool_call_input_from_every_event(self):
+ from litellm.responses.streaming_iterator import build_synthetic_response_events
+
+ events: Final = list(
+ build_synthetic_response_events(
+ transformed=ResponsesAPIResponse(
+ id="resp_faked",
+ created_at=0,
+ status="completed",
+ model="gpt-6-luna",
+ object="response",
+ output=[CUSTOM_TOOL_CALL_ITEM],
+ ),
+ logging_obj=None,
+ chunk_size=5,
+ )
+ )
+
+ await OpenAIResponsesHandler().process_output_streaming_response(
+ responses_so_far=events,
+ guardrail_to_apply=PersimmonMaskingGuardrail(guardrail_name="mask"),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ sent: Final = "".join(event.model_dump_json() for event in events)
+ assert "persimmon" not in sent
+ assert "echo [MASKED]" in sent
+
@staticmethod
def _bridged_function_call_stream_events() -> List[dict]:
reasoning = {"type": "reasoning", "id": "rs_1", "summary": []}
@@ -3683,6 +3713,43 @@ class TestBuildBlockSseChunks:
assert completed["model"] == "gpt-5.4-mini"
assert completed["output"][0]["content"][0]["text"] == "Blocked by policy."
+ @pytest.mark.parametrize("stream_started", [False, True])
+ def test_block_message_reaches_an_sdk_reader_once(self, stream_started):
+ import httpx
+ import openai
+
+ created_event = {
+ "type": "response.created",
+ "response": {
+ "id": "resp_live",
+ "object": "response",
+ "created_at": 1,
+ "model": "gpt-5.4-mini",
+ "status": "in_progress",
+ "output": [],
+ },
+ }
+ yielded = [created_event] if stream_started else []
+ already_sent = b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in yielded)
+ block_chunks = OpenAIResponsesHandler().build_block_sse_chunks(
+ self._exc(original_response=yielded), stream_started=stream_started, responses_so_far=yielded
+ )
+ sse_body = already_sent + b"".join(block_chunks)
+ client = openai.OpenAI(
+ api_key="sk-test",
+ base_url="http://guardrail.test/v1",
+ http_client=httpx.Client(
+ transport=httpx.MockTransport(
+ lambda request: httpx.Response(200, headers={"content-type": "text/event-stream"}, content=sse_body)
+ )
+ ),
+ )
+
+ with client.responses.stream(model="gpt-5.4-mini", input="hi") as stream:
+ text_snapshots = [event.snapshot for event in stream if event.type == "response.output_text.delta"]
+
+ assert text_snapshots[-1] == "Blocked by policy."
+
def test_continuation_appends_item_at_next_output_index_with_real_usage(self):
handler = OpenAIResponsesHandler()
yielded = [
diff --git a/tests/unit/responses/mcp/test_mcp_streaming_iterator.py b/tests/unit/responses/mcp/test_mcp_streaming_iterator.py
index 52e2adbe34b..8eb73b7c6e1 100644
--- a/tests/unit/responses/mcp/test_mcp_streaming_iterator.py
+++ b/tests/unit/responses/mcp/test_mcp_streaming_iterator.py
@@ -467,6 +467,31 @@ async def test_final_output_lists_executed_call_as_completed_mcp_call(monkeypatc
assert [item.status for item in done_mcp_items] == ["completed"]
+async def test_executed_mcp_call_arguments_reach_a_snapshot_reader_once(monkeypatch):
+ _mock_mcp_environment(monkeypatch)
+ follow_up = _FakeAsyncStream(_lifecycle_round("resp-final", _text_message("Alpha.")))
+ monkeypatch.setattr(responses_main_module, "aresponses", AsyncMock(side_effect=[follow_up]))
+ arguments = '{"repoName": "berriai/litellm"}'
+ iterator = _make_iterator(
+ [
+ _created_chunk("resp-interim"),
+ _completed_chunk([_function_call("call_1", "read_wiki_contents", arguments)], response_id="resp-interim"),
+ ]
+ )
+
+ chunks = [chunk async for chunk in iterator]
+
+ opened = [
+ c.item.arguments
+ for c in chunks
+ if c.type == ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED and _item_type(c.item) == "mcp_call"
+ ]
+ deltas = [c.delta for c in chunks if c.type == ResponsesAPIStreamEvents.MCP_CALL_ARGUMENTS_DELTA]
+ assert len(opened) == 1
+ assert opened[0] + "".join(deltas) == arguments
+
+
@pytest.mark.asyncio
async def test_stream_without_auto_execute_is_forwarded_unchanged(monkeypatch):
"""With approval required there is one round, and it passes through untouched."""
diff --git a/tests/unit/responses/test_streaming_iterator.py b/tests/unit/responses/test_streaming_iterator.py
index 9e3b4e86f6f..7cdac6c7581 100644
--- a/tests/unit/responses/test_streaming_iterator.py
+++ b/tests/unit/responses/test_streaming_iterator.py
@@ -4,9 +4,10 @@ completion_start_time on the first chunk so downstream TTFT consumers
completion_start_time = end_time."""
import asyncio, importlib
+import functools
import json
import threading
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
from datetime import datetime
from typing import Final, Optional
from unittest.mock import AsyncMock, MagicMock, Mock, patch
@@ -32,6 +33,7 @@ from litellm.types.llms.openai import (
ResponseCompletedEvent,
ResponsesAPIResponse,
ResponsesAPIStreamEvents,
+ ResponsesAPIStreamingResponse,
)
from contextlib import suppress
from litellm.responses import streaming_iterator as streaming_module
@@ -2357,3 +2359,201 @@ def test_cached_responses_stream_sync_hit_triggers_success_callbacks(monkeypatch
litellm.cache.async_add_cache.assert_not_called()
litellm.cache.add_cache.assert_not_called()
litellm.cache = original_cache
+
+
+def _answer_with_text_and_tool_call() -> ResponsesAPIResponse:
+ return ResponsesAPIResponse(
+ id="resp_synthetic",
+ created_at=0,
+ status="completed",
+ model="gpt-6-luna",
+ object="response",
+ output=[
+ {
+ "type": "message",
+ "id": "msg_synthetic",
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "Checking the weather.", "annotations": []}],
+ },
+ {
+ "type": "function_call",
+ "id": "fc_synthetic",
+ "call_id": "call_weather",
+ "name": "get_weather",
+ "arguments": '{"city":"Berlin"}',
+ "status": "completed",
+ },
+ ],
+ usage=ResponseAPIUsage(input_tokens=1, output_tokens=1, total_tokens=2),
+ )
+
+
+def test_faked_stream_bridged_to_chat_sends_tool_arguments_once():
+ from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ OpenAiResponsesToChatCompletionStreamIterator,
+ )
+
+ events: Final = streaming_module.build_synthetic_response_events(
+ transformed=_answer_with_text_and_tool_call(), logging_obj=None, chunk_size=5
+ )
+ chunks: Final = tuple(
+ OpenAiResponsesToChatCompletionStreamIterator(streaming_response=iter(events), sync_stream=True)
+ )
+ tool_call_deltas: Final = tuple(
+ tool_call
+ for chunk in chunks
+ for tool_call in (chunk.choices[0].delta.tool_calls or ()) # comprehension-ok: flattening each chunk's tool calls
+ )
+ joined_arguments: Final = "".join(tool_call.function.arguments or "" for tool_call in tool_call_deltas)
+ joined_text: Final = "".join(chunk.choices[0].delta.content or "" for chunk in chunks)
+
+ assert {tool_call.index for tool_call in tool_call_deltas} == {0}
+ assert json.loads(joined_arguments) == {"city": "Berlin"}
+ assert joined_text == "Checking the weather."
+
+
+def test_faked_stream_read_by_openai_sdk_accumulates_each_value_once():
+ import openai
+
+ events: Final = streaming_module.build_synthetic_response_events(
+ transformed=_answer_with_text_and_tool_call(), logging_obj=None, chunk_size=5
+ )
+ sse_body: Final = b"".join(
+ f"event: {event.type}\ndata: {event.model_dump_json(exclude_none=True)}\n\n".encode() for event in events
+ )
+ client: Final = openai.OpenAI(
+ api_key="sk-test",
+ base_url="http://synthetic.test/v1",
+ http_client=httpx.Client(
+ transport=httpx.MockTransport(
+ lambda request: httpx.Response(200, headers={"content-type": "text/event-stream"}, content=sse_body)
+ )
+ ),
+ )
+
+ with client.responses.stream(model="gpt-6-luna", input="Weather in Berlin?") as stream:
+ streamed: Final = tuple(stream)
+
+ text_snapshots: Final = tuple(event.snapshot for event in streamed if event.type == "response.output_text.delta")
+ argument_snapshots: Final = tuple(
+ event.snapshot for event in streamed if event.type == "response.function_call_arguments.delta"
+ )
+ assert text_snapshots[-1] == "Checking the weather."
+ assert json.loads(argument_snapshots[-1]) == {"city": "Berlin"}
+
+
+def test_faked_stream_opens_items_in_progress_and_empty_like_a_real_stream():
+ events: Final = streaming_module.build_synthetic_response_events(
+ transformed=_answer_with_text_and_tool_call(), logging_obj=None, chunk_size=5
+ )
+ added_items: Final = tuple(event.item for event in events if event.type == "response.output_item.added")
+ added_parts: Final = tuple(event.part for event in events if event.type == "response.content_part.added")
+
+ assert [(item.type, item.status) for item in added_items] == [
+ ("message", "in_progress"),
+ ("function_call", "in_progress"),
+ ]
+ assert added_items[0].content == []
+ assert added_items[1].arguments == ""
+ assert [part.text for part in added_parts] == [""]
+
+
+
+def _answer_with_reasoning_refusal_and_custom_tool_call() -> ResponsesAPIResponse:
+ return ResponsesAPIResponse(
+ id="resp_synthetic",
+ created_at=0,
+ status="completed",
+ model="gpt-6-luna",
+ object="response",
+ output=[
+ {
+ "type": "reasoning",
+ "id": "rs_synthetic",
+ "summary": [
+ {"type": "summary_text", "text": "Weighing the cities."},
+ {"type": "summary_text", "text": "Berlin it is."},
+ ],
+ },
+ {
+ "type": "message",
+ "id": "msg_synthetic",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {"type": "output_text", "text": "Checking the weather.", "annotations": []},
+ {"type": "refusal", "refusal": "No forecasts for Mars."},
+ ],
+ },
+ {
+ "type": "custom_tool_call",
+ "id": "ctc_synthetic",
+ "call_id": "call_shell",
+ "name": "shell",
+ "input": "curl wttr.in/Berlin",
+ },
+ ],
+ usage=ResponseAPIUsage(input_tokens=1, output_tokens=1, total_tokens=2),
+ )
+
+
+StreamedValueKey = tuple[int, str, int]
+
+
+def _opening_values(output_index: int, item: Mapping[str, object]) -> Mapping[StreamedValueKey, str]:
+ summaries: Final = {
+ (output_index, "summary", index): part["text"] for index, part in enumerate(item.get("summary") or ())
+ }
+ parts: Final = {
+ (output_index, "content", index): part.get("text") or part.get("refusal") or ""
+ for index, part in enumerate(item.get("content") or ())
+ }
+ tool_input: Final = {(output_index, "input", 0): item["input"]} if "input" in item else {}
+ return {**summaries, **parts, **tool_input}
+
+
+def _read_event_like_a_snapshot_reader(
+ built: Mapping[StreamedValueKey, str], event: ResponsesAPIStreamingResponse
+) -> Mapping[StreamedValueKey, str]:
+ payload: Final = event.model_dump()
+ match payload["type"]:
+ case "response.output_item.added":
+ return {**built, **_opening_values(payload["output_index"], payload["item"])}
+ case "response.content_part.added":
+ part: Final = payload["part"]
+ return {
+ **built,
+ (payload["output_index"], "content", payload["content_index"]): part.get("text")
+ or part.get("refusal")
+ or "",
+ }
+ case "response.reasoning_summary_part.added":
+ return {**built, (payload["output_index"], "summary", payload["summary_index"]): payload["part"]["text"]}
+ case "response.output_text.delta" | "response.refusal.delta":
+ content_key: Final = (payload["output_index"], "content", payload["content_index"])
+ return {**built, content_key: built[content_key] + payload["delta"]}
+ case "response.reasoning_summary_text.delta":
+ summary_key: Final = (payload["output_index"], "summary", payload["summary_index"])
+ return {**built, summary_key: built[summary_key] + payload["delta"]}
+ case "response.custom_tool_call_input.delta":
+ input_key: Final = (payload["output_index"], "input", 0)
+ return {**built, input_key: built[input_key] + payload["delta"]}
+ case _:
+ return built
+
+
+def test_faked_stream_builds_each_refusal_summary_and_custom_tool_input_once_for_a_snapshot_reader():
+ events: Final = streaming_module.build_synthetic_response_events(
+ transformed=_answer_with_reasoning_refusal_and_custom_tool_call(), logging_obj=None, chunk_size=5
+ )
+
+ built: Final = functools.reduce(_read_event_like_a_snapshot_reader, events, {})
+
+ assert built == {
+ (0, "summary", 0): "Weighing the cities.",
+ (0, "summary", 1): "Berlin it is.",
+ (1, "content", 0): "Checking the weather.",
+ (1, "content", 1): "No forecasts for Mars.",
+ (2, "input", 0): "curl wttr.in/Berlin",
+ }