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(proxy)!: end a chat completions stream with an error event when a guardrail blocks mid-stream (#46953)

Mateo Wang68a8b12ab370
diff --git a/litellm/proxy/client/__init__.py b/litellm/proxy/client/__init__.py
index dff3dc226ab..b640f90f1c8 100644
--- a/litellm/proxy/client/__init__.py
+++ b/litellm/proxy/client/__init__.py
@@ -1,6 +1,6 @@
from .chat import ChatClient
from .client import Client
-from .exceptions import UnauthorizedError
+from .exceptions import StreamError, UnauthorizedError
from .health import HealthManagementClient
from .model_groups import ModelGroupsManagementClient
from .models import ModelsManagementClient
@@ -12,6 +12,7 @@ __all__ = [
"HealthManagementClient",
"ModelGroupsManagementClient",
"ModelsManagementClient",
+ "StreamError",
"UnauthorizedError",
"UsersManagementClient",
]
diff --git a/litellm/proxy/client/chat.py b/litellm/proxy/client/chat.py
index cf48bee6958..c027bf2fe98 100644
--- a/litellm/proxy/client/chat.py
+++ b/litellm/proxy/client/chat.py
@@ -5,13 +5,21 @@ from typing import Any, Final
import requests
from pydantic import ConfigDict, TypeAdapter
-from .exceptions import UnauthorizedError
+from .exceptions import StreamError, UnauthorizedError
_SSE_LINE: Final[TypeAdapter[bytes | bytearray]] = TypeAdapter(
bytes | bytearray, config=ConfigDict(arbitrary_types_allowed=True, strict=True, hide_input_in_errors=True)
)
+def _raise_if_error_frame(chunk: object) -> None:
+ match chunk:
+ case {"error": object() as error} if error:
+ raise StreamError(error)
+ case _:
+ return
+
+
class ChatClient:
def __init__(self, base_url: str, api_key: str | None = None, timeout: int = 600):
"""
@@ -143,6 +151,7 @@ class ChatClient:
Raises:
UnauthorizedError: If the request fails with a 401 status code
+ StreamError: If the server ends the stream with an error event
requests.exceptions.RequestException: If the request fails with any other error
"""
url: Final = f"{self._base_url}/chat/completions"
@@ -184,9 +193,10 @@ class ChatClient:
break
try:
chunk = json.loads(data_str)
- yield chunk
except json.JSONDecodeError:
continue
+ _raise_if_error_frame(chunk)
+ yield chunk
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
diff --git a/litellm/proxy/client/cli/commands/chat.py b/litellm/proxy/client/cli/commands/chat.py
index 780695a37bb..0748ebf56fe 100644
--- a/litellm/proxy/client/cli/commands/chat.py
+++ b/litellm/proxy/client/cli/commands/chat.py
@@ -409,10 +409,16 @@ def _stream_response(
console.print(f"\n[red]Error: HTTP {e.response.status_code}[/red]")
try:
error_body: Final[_ErrorBodyView] = {"body": e.response.json()}
- console.print(f"[red]{error_body['body'].get('error', {}).get('message', 'Unknown error')}[/red]")
+ console.print(
+ error_body["body"].get("error", {}).get("message", "Unknown error"),
+ style="red",
+ markup=False,
+ highlight=False,
+ emoji=False,
+ )
except json.JSONDecodeError:
- console.print(f"[red]{e.response.text}[/red]")
+ console.print(e.response.text, style="red", markup=False, highlight=False, emoji=False)
return None
except Exception as e:
- console.print(f"\n[red]Error: {e}[/red]")
+ console.print(f"\nError: {e}", style="red", markup=False, highlight=False, emoji=False)
return None
diff --git a/litellm/proxy/client/exceptions.py b/litellm/proxy/client/exceptions.py
index 27de7031e3c..65bdd736a57 100644
--- a/litellm/proxy/client/exceptions.py
+++ b/litellm/proxy/client/exceptions.py
@@ -25,3 +25,19 @@ class NotFoundError(Exception):
def __init__(self, orig_exception: requests.exceptions.HTTPError | str):
self.orig_exception = _redact_orig_exception(orig_exception)
super().__init__(str(self.orig_exception))
+
+
+def _stream_error_message(error: object) -> str:
+ match error:
+ case {"message": str(message)}:
+ return message
+ case _:
+ return str(error)
+
+
+class StreamError(Exception):
+ """Exception raised when the server ends a stream with an error event."""
+
+ def __init__(self, error: object) -> None:
+ self.error = error
+ super().__init__(redact_string(_stream_error_message(error)))
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index e52f11641b0..b443711752a 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -636,7 +636,7 @@ def serialize_http_exception_detail(
msg: Final = detail.get("message")
if isinstance(msg, str):
return msg, detail
- return json.dumps(detail), detail
+ return json.dumps(detail, default=str), detail
return str(detail), None
@@ -1117,7 +1117,7 @@ def sse_error_payload(exc: BaseException) -> tuple[int, Mapping[str, object]]:
def _sse_error_frames(error_obj: Mapping[str, object]) -> tuple[str, str]:
"""The two frames an SSE stream ends with once it can no longer raise."""
- return f"data: {json.dumps({'error': error_obj})}\n\n", "data: [DONE]\n\n"
+ return f"data: {json.dumps({'error': error_obj}, default=str)}\n\n", "data: [DONE]\n\n"
def _sse_stream_headers(headers: Mapping[str, str]) -> Mapping[str, str]:
diff --git a/litellm/proxy/common_utils/responses_stream_errors.py b/litellm/proxy/common_utils/responses_stream_errors.py
index 723cd88aad0..3409b4b6657 100644
--- a/litellm/proxy/common_utils/responses_stream_errors.py
+++ b/litellm/proxy/common_utils/responses_stream_errors.py
@@ -30,7 +30,7 @@ class _StreamEvent(LiteLLMBaseModel):
class _FailureDetails(LiteLLMBaseModel):
- model_config = ConfigDict(frozen=True, from_attributes=True)
+ model_config = ConfigDict(frozen=True)
message: str | None = None
code: str | int | None = None
@@ -52,6 +52,10 @@ class _FailureDetails(LiteLLMBaseModel):
def normalize_type(cls, value: object) -> str | None:
return value if isinstance(value, str) else None
+ @classmethod
+ def of_exception(cls, exception: Exception) -> "_FailureDetails":
+ return cls.model_validate({field: getattr(exception, field, None) for field in cls.model_fields})
+
def _original_failure(exception: Exception) -> Exception:
current = exception # rebind-ok: the recursion gate requires iterative wrapper traversal
@@ -61,7 +65,7 @@ def _original_failure(exception: Exception) -> Exception:
def _failure_details(original: Exception) -> _FailureDetails:
- mapped: Final = _FailureDetails.model_validate(original)
+ mapped: Final = _FailureDetails.of_exception(original)
body: Final = getattr(original, "body", None)
if not isinstance(body, Mapping):
return mapped
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 0c7840c92fd..e3ea9dabe50 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -453,6 +453,7 @@ from litellm.proxy.common_request_processing import ( # noqa: F401, RUF100 # l
request_litellm_call_id,
resolve_litellm_call_id,
should_return_raw_model_name,
+ sse_error_payload,
ttft_keepalive_interval,
)
from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import (
@@ -10472,6 +10473,7 @@ async def async_data_generator(
stream_completed = False
client_disconnected = False
error_state: Final = ResponsesStreamErrorState() if responses_stream_errors else None
+ ends_with_openai_done: Final = not request_data.get("_litellm_skip_openai_stream_done")
needs_iterator_wrap: Final = proxy_logging_obj.needs_iterator_wrap()
stream_iterator: Final = _object_stream(
proxy_logging_obj.async_post_call_streaming_iterator_hook(
@@ -10483,6 +10485,7 @@ async def async_data_generator(
else response
)
stream_source: AsyncIterator[object] | None = None # rebind-ok: bound once the keepalive policy resolves
+ stream_started: bool = False # rebind-ok: set once a ping or a hook-cleared chunk is sent, then errors go in-band
try:
error_message: str | None = None
requested_model_from_client: Final = _get_client_requested_model_for_streaming(request_data=request_data)
@@ -10539,6 +10542,7 @@ async def async_data_generator(
await asyncio.sleep(0)
loop_released_at = time.monotonic()
if item is _STREAM_KEEPALIVE:
+ stream_started = True
yield ": ping\n\n"
continue
chunk = item
@@ -10550,6 +10554,7 @@ async def async_data_generator(
request_data=request_data,
str_so_far=_str_so_far,
)
+ stream_started = True
# Mid-stream fallbacks surface metadata on individual chunks rather than
# the response wrapper. Keep scanning chunks until a fallback model is
@@ -10655,7 +10660,7 @@ async def async_data_generator(
if error_message is not None:
yield error_message
# OpenAI-compatible streams terminate with data: [DONE]; Google GenAI (?alt=sse) does not.
- if not request_data.get("_litellm_skip_openai_stream_done"):
+ if ends_with_openai_done:
yield _OPENAI_STREAM_DONE_FRAME
except (asyncio.CancelledError, GeneratorExit):
# Client disconnected mid-stream. CancelledError / GeneratorExit are
@@ -10672,13 +10677,14 @@ async def async_data_generator(
if guarded_layer is not response:
await close_guarded_stream(guarded_layer)
raise
- except Exception as e:
+ except Exception as e: # noqa: BLE001 # stream boundary: any failure must end the SSE body as an error event
verbose_proxy_logger.exception("litellm.proxy.proxy_server.async_data_generator(): Exception occured - %s", e)
- await proxy_logging_obj.post_call_failure_hook(
+ replacement: Final = await proxy_logging_obj.post_call_failure_hook(
user_api_key_dict=user_api_key_dict,
original_exception=e,
request_data=request_data,
)
+ client_error: Final[Exception] = e if replacement is None else replacement
verbose_proxy_logger.debug(
"\x1b[1;31mAn error occurred: %s\n\n Debug this by setting `--debug`, e.g. `litellm --model gpt-3.5-turbo --debug`",
e,
@@ -10686,31 +10692,31 @@ async def async_data_generator(
if error_state is not None:
stream_completed = True
- error_frame: Final = error_state.format_failure(e)
+ error_frame: Final = error_state.format_failure(client_error)
if error_frame is not None:
yield error_frame
- if not request_data.get("_litellm_skip_openai_stream_done"):
+ if ends_with_openai_done:
yield _OPENAI_STREAM_DONE_FRAME
return
- if isinstance(e, HTTPException):
- raise e
- elif isinstance(e, StreamingCallbackError):
- error_msg = str(e)
- else:
- # Only include the error message, not the traceback.
- # The traceback is already logged above via verbose_proxy_logger.exception().
- # Including it in the SSE response leaks internal details to clients.
- error_msg = str(e)
-
- proxy_exception: Final = ProxyException(
- message=getattr(e, "message", error_msg),
- type=getattr(e, "type", "None"),
- param=getattr(e, "param", "None"),
- code=getattr(e, "status_code", 500),
+ if isinstance(e, HTTPException) and (not stream_started or not ends_with_openai_done):
+ raise client_error
+ error_returned: Final = json.dumps(
+ {
+ "error": sse_error_payload(client_error)[1]
+ if isinstance(client_error, HTTPException)
+ else ProxyException(
+ message=getattr(client_error, "message", str(client_error)),
+ type=getattr(client_error, "type", "None"),
+ param=getattr(client_error, "param", "None"),
+ code=getattr(client_error, "status_code", 500),
+ ).to_dict()
+ },
+ default=str,
)
- error_returned: Final = json.dumps({"error": proxy_exception.to_dict()})
stream_completed = True
yield f"data: {error_returned}\n\n"
+ if ends_with_openai_done:
+ yield _OPENAI_STREAM_DONE_FRAME
finally:
await ProxyBaseLLMRequestProcessing.finalize_streaming_generator_cleanup(
request=request,
diff --git a/tests/_support/clock_loops.py b/tests/_support/clock_loops.py
new file mode 100644
index 00000000000..6d3f5e17ff8
--- /dev/null
+++ b/tests/_support/clock_loops.py
@@ -0,0 +1,40 @@
+import asyncio
+import selectors
+from collections.abc import Callable
+from typing import Final
+
+
+class ManualClockLoop(asyncio.SelectorEventLoop):
+ """An event loop whose clock moves only when the test advances it, so timeouts fire on test-controlled conditions"""
+
+ def __init__(self, selector: selectors.BaseSelector | None = None) -> None:
+ super().__init__(selector)
+ self._now = 0.0
+
+ def time(self) -> float:
+ return self._now
+
+ def advance(self, seconds: float) -> None:
+ self._now += seconds
+
+
+class _AutojumpSelector(selectors.DefaultSelector):
+ def __init__(self, advance: Callable[[float], None]) -> None:
+ super().__init__()
+ self._advance = advance
+
+ def select(self, timeout: float | None = None) -> list[tuple[selectors.SelectorKey, int]]:
+ ready: Final = super().select(0)
+ if ready or timeout == 0:
+ return ready
+ if timeout is None:
+ return super().select(None)
+ self._advance(timeout)
+ return []
+
+
+class AutojumpClockLoop(ManualClockLoop):
+ """A manual-clock loop that jumps to the next timer only once no callback or I/O event is left to run"""
+
+ def __init__(self) -> None:
+ super().__init__(_AutojumpSelector(self.advance))
diff --git a/tests/integration/streaming/test_chat_stream_guardrail_error_events.py b/tests/integration/streaming/test_chat_stream_guardrail_error_events.py
new file mode 100644
index 00000000000..021ca68ce8e
--- /dev/null
+++ b/tests/integration/streaming/test_chat_stream_guardrail_error_events.py
@@ -0,0 +1,566 @@
+import contextlib
+import json
+import re
+import uuid
+from collections.abc import Iterator, Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final
+
+import httpx
+import openai
+import pytest
+import yaml
+from integration._support.client import JSON_OBJECT, Gateway, eventually, list_value, object_value, string_value
+from integration._support.database import read_rows
+from integration._support.process import OwnedProxy, WorkerHealthcheck, graceful_stop_seconds, owned_proxy_process
+from integration._support.responses_stream import healthy_stream
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue
+
+from litellm.proxy import client as proxy_client
+
+pytestmark: Final = [
+ pytest.mark.timeout(2 * graceful_stop_seconds() + 120),
+ pytest.mark.xdist_group("chat-stream-guardrail-error-events"),
+]
+
+_MODEL: Final = "stream-error-events"
+_FILTER: Final = "keeper-filter"
+_SPAN_POST: Final = "span-post-call"
+_SPAN_PRE: Final = "span-pre-call"
+_BUFFERED: Final = "buffered-post-call"
+_RAISING: Final = "raising-post-call"
+_REPLACE: Final = "replace-client-error"
+_REPLACEMENT_MESSAGE: Final = "Request blocked by policy"
+_CRASH_MESSAGE: Final = "Guardrail service crashed while scanning"
+_RAISED_BLOCK: Final = "Raised block: policy"
+_SPAN: Final = "spanword"
+_LEAD: Final = "The lighthouse on the northern cliff has guided ships for two hundred years, and "
+_TEXTS: Final[Mapping[str, tuple[str, ...]]] = {
+ "clean": ("Hello", " there"),
+ "filter-late": (_LEAD, "the keeper lights the lamp at dusk."),
+ "filter-early": ("The keeper lights the lamp.", " Ships pass."),
+ "span-early": (f"{_SPAN} opens the answer", " and more"),
+ "span-late": ("Hello there, ", f"{_SPAN} follows"),
+ "buffered": ("The lamp is lit by", " the keeper."),
+ "drop": ("Hello", " there"),
+}
+_BUFFERED_PAUSE_SECONDS: Final = 1.5
+_DROP_PAUSE_SECONDS: Final = 0.5
+_SCENARIO: Final = re.compile(rb"scenario-([a-z-]+) marker-([0-9a-f]+)")
+_MODULE: Final = "stream_error_hooks"
+_MODULE_SOURCE: Final = f'''import re
+
+from fastapi import HTTPException
+
+from litellm.integrations.custom_guardrail import CustomGuardrail
+from litellm.integrations.custom_logger import CustomLogger
+
+
+class SpanGuardrail(CustomGuardrail):
+ async def async_post_call_streaming_hook(self, user_api_key_dict, response):
+ match = re.search("{_SPAN}", response)
+ if match is not None:
+ raise HTTPException(status_code=400, detail={{"error": "Content blocked: {_SPAN}", "matched_span": match}})
+ return None
+
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
+ match = re.search("{_SPAN}", str(data["messages"][-1]["content"]))
+ if match is not None:
+ raise HTTPException(status_code=400, detail={{"matched_span": match}})
+ return data
+
+
+class BufferingGuardrail(CustomGuardrail):
+ async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):
+ chunks = [chunk async for chunk in response]
+ text = "".join(choice.delta.content or "" for chunk in chunks for choice in chunk.choices)
+ if "keeper" in text:
+ raise HTTPException(status_code=400, detail={{"error": "Buffered block: keeper"}})
+ for chunk in chunks:
+ yield chunk
+
+
+class RaisingGuardrail(CustomGuardrail):
+ async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):
+ prompt = str(request_data.get("messages") or request_data.get("input"))
+ found = re.search("raise-(builtin|http)-after-([0-9]+)", prompt)
+ sent = 0
+ async for chunk in response:
+ if found is not None and sent == int(found.group(2)):
+ if found.group(1) == "builtin":
+ raise RuntimeError("{_CRASH_MESSAGE}")
+ raise HTTPException(status_code=400, detail={{"error": "{_RAISED_BLOCK}"}})
+ yield chunk
+ sent += 1
+
+
+class ReplacesClientErrors(CustomLogger):
+ async def async_post_call_failure_hook(
+ self, request_data, original_exception, user_api_key_dict, traceback_str=None
+ ):
+ if "{_REPLACE}" in str(request_data.get("messages") or request_data.get("input")):
+ return HTTPException(status_code=403, detail="{_REPLACEMENT_MESSAGE}")
+ return None
+
+
+replacer = ReplacesClientErrors()
+'''
+
+
+def _chunk(identity: str, delta: Mapping[str, JsonValue], finish: str | None = None) -> bytes:
+ body: Final = {
+ "id": identity,
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "gpt-4o-mini",
+ "choices": [{"index": 0, "delta": dict(delta), "finish_reason": finish}],
+ }
+ return b"data: " + json.dumps(body).encode() + b"\n\n"
+
+
+def _stream(identity: str, pieces: Sequence[str]) -> tuple[bytes, ...]:
+ first, *rest = pieces
+ return (
+ _chunk(identity, {"role": "assistant", "content": first}),
+ *(_chunk(identity, {"content": piece}) for piece in rest),
+ _chunk(identity, {}, finish="stop"),
+ b"data: [DONE]\n\n",
+ )
+
+
+def _respond(request: Request) -> Reply:
+ found: Final = _SCENARIO.search(request.body)
+ assert found is not None, request.body
+ name: Final = found.group(1).decode()
+ marker: Final = found.group(2).decode()
+ if request.target.endswith("/responses"):
+ return Reply(content_type="text/event-stream", chunks=healthy_stream(f"resp_{marker}", "".join(_TEXTS[name])))
+ chunks: Final = _stream(f"chatcmpl-{marker}", _TEXTS[name])
+ match name:
+ case "buffered":
+ return Reply(content_type="text/event-stream", chunks=chunks, pause_between_chunks=_BUFFERED_PAUSE_SECONDS)
+ case "drop":
+ return Reply(
+ content_type="text/event-stream",
+ chunks=chunks,
+ abort_after=2,
+ pause_between_chunks=_DROP_PAUSE_SECONDS,
+ )
+ case _:
+ return Reply(content_type="text/event-stream", chunks=chunks)
+
+
+def _config(upstream_url: str) -> dict[str, JsonValue]:
+ base: Final = JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ guardrails: Final[tuple[tuple[str, str, str], ...]] = (
+ (_SPAN_POST, f"{_MODULE}.SpanGuardrail", "post_call"),
+ (_SPAN_PRE, f"{_MODULE}.SpanGuardrail", "pre_call"),
+ (_BUFFERED, f"{_MODULE}.BufferingGuardrail", "post_call"),
+ (_RAISING, f"{_MODULE}.RaisingGuardrail", "post_call"),
+ )
+ return {
+ **base,
+ "litellm_settings": {**object_value(base["litellm_settings"]), "callbacks": [f"{_MODULE}.replacer"]},
+ "guardrails": [
+ {
+ "guardrail_name": _FILTER,
+ "litellm_params": {
+ "guardrail": "litellm_content_filter",
+ "mode": "post_call",
+ "default_on": False,
+ "blocked_words": [{"keyword": "keeper", "action": "BLOCK"}],
+ },
+ },
+ *(
+ {"guardrail_name": name, "litellm_params": {"guardrail": guardrail, "mode": mode, "default_on": False}}
+ for name, guardrail, mode in guardrails
+ ),
+ ],
+ "model_list": [
+ {
+ "model_name": _MODEL,
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_base": f"{upstream_url}/v1",
+ "api_key": "synthetic-stream-key",
+ "allow_client_keepalive_override": True,
+ },
+ }
+ ],
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class Rig:
+ proxy: OwnedProxy
+ upstream: Wire
+
+
[email protected](scope="module")
+def rig(session_gateway: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ with wire_server(_respond) as upstream:
+ directory: Final = tmp_path_factory.mktemp("chat-stream-guardrail-error-events")
+ (directory / f"{_MODULE}.py").write_text(_MODULE_SOURCE)
+ config_path: Final = directory / "chat-stream-guardrail-error-events.yaml"
+ config_path.write_text(yaml.safe_dump(_config(upstream.url)))
+ with owned_proxy_process(
+ session_gateway,
+ directory,
+ {},
+ config=config_path,
+ workers=2,
+ healthcheck=WorkerHealthcheck.LENIENT,
+ ) as proxy:
+ yield Rig(proxy, upstream)
+
+
+def _prompt(scenario: str, marker: str, *directives: str) -> str:
+ return " ".join((f"scenario-{scenario}", f"marker-{marker}", *directives))
+
+
+def _body(
+ scenario: str, marker: str, guardrails: Sequence[str], *directives: str, **extra: JsonValue
+) -> dict[str, JsonValue]:
+ return {
+ "model": _MODEL,
+ "stream": True,
+ "messages": [{"role": "user", "content": _prompt(scenario, marker, *directives)}],
+ "guardrails": list(guardrails),
+ "num_retries": 0,
+ "cache": {"no-cache": True},
+ **extra,
+ }
+
+
+def _marker() -> str:
+ return uuid.uuid4().hex
+
+
+def _calls_with(wire: Wire, marker: str) -> int:
+ return sum(1 for request in wire.drain() if marker.encode() in request.body)
+
+
+def _stream_chat(rig: Rig, body: Mapping[str, JsonValue]) -> httpx.Response:
+ return rig.proxy.gateway.request("POST", "/v1/chat/completions", body)
+
+
+def _data_lines(text: str) -> tuple[str, ...]:
+ return tuple(line.removeprefix("data: ") for line in text.splitlines() if line.startswith("data: "))
+
+
+def _payloads(text: str) -> tuple[dict[str, JsonValue], ...]:
+ return tuple(JSON_OBJECT.validate_json(line) for line in _data_lines(text) if line != "[DONE]")
+
+
+def _choices(payloads: Sequence[Mapping[str, JsonValue]]) -> Iterator[dict[str, JsonValue]]:
+ for payload in payloads:
+ yield from map(object_value, list_value(payload.get("choices") or []))
+
+
+def _content(payloads: Sequence[Mapping[str, JsonValue]]) -> str:
+ return "".join(string_value(object_value(choice["delta"]).get("content") or "") for choice in _choices(payloads))
+
+
+def _finish_reasons(payloads: Sequence[Mapping[str, JsonValue]]) -> tuple[JsonValue, ...]:
+ return tuple(choice.get("finish_reason") for choice in _choices(payloads))
+
+
+@dataclass(frozen=True, slots=True)
+class EndedInBand:
+ content: str
+ error: dict[str, JsonValue]
+
+
+def _ended_in_band(response: httpx.Response, status: int) -> EndedInBand:
+ assert response.status_code == status, response.text
+ assert response.headers["content-type"].startswith("text/event-stream"), response.headers
+ lines: Final = _data_lines(response.text)
+ assert lines[-1] == "[DONE]" and lines.count("[DONE]") == 1, response.text
+ payloads: Final = _payloads(response.text)
+ assert "error" in payloads[-1] and all("error" not in payload for payload in payloads[:-1]), response.text
+ assert "stop" not in _finish_reasons(payloads), response.text
+ return EndedInBand(_content(payloads[:-1]), object_value(payloads[-1]["error"]))
+
+
+def test_mid_stream_content_filter_block_ends_with_an_error_event_and_done(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("filter-late", marker, (_FILTER,)))
+ ended: Final = _ended_in_band(response, 200)
+ assert ended.content and _LEAD.startswith(ended.content), response.text
+ assert ended.error["code"] == "400", ended.error
+ assert "keeper" in string_value(ended.error["message"]), ended.error
+ assert object_value(ended.error["provider_specific_fields"])["keyword"] == "keeper", ended.error
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_mid_stream_content_filter_block_reaches_the_openai_sdk_as_the_block_error(rig: Rig) -> None:
+ marker: Final = _marker()
+ client: Final = openai.OpenAI(
+ base_url=f"{rig.proxy.gateway.client.base_url}/v1", api_key=rig.proxy.gateway.key, max_retries=0
+ )
+ stream: Final = client.chat.completions.create(
+ model=_MODEL,
+ messages=[{"role": "user", "content": f"scenario-filter-late marker-{marker}"}],
+ stream=True,
+ extra_body={"guardrails": [_FILTER], "num_retries": 0, "cache": {"no-cache": True}},
+ )
+ with pytest.raises(openai.APIError) as raised:
+ tuple(stream)
+ assert type(raised.value) is openai.APIError, repr(raised.value)
+ assert "keeper" in raised.value.message, raised.value.message
+
+
+def test_early_content_filter_block_keeps_its_400_event_stream_body(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("filter-early", marker, (_FILTER,)))
+ ended: Final = _ended_in_band(response, 400)
+ assert ended.content == "", response.text
+ assert ended.error["code"] == "400", ended.error
+ assert object_value(ended.error["provider_specific_fields"])["keyword"] == "keeper", ended.error
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+ ("scenario", "status"),
+ [pytest.param("span-early", 400, id="first_chunk"), pytest.param("span-late", 200, id="later_chunk")],
+)
+def test_per_chunk_block_with_an_unencodable_detail_still_sends_the_error_event(
+ rig: Rig, scenario: str, status: int
+) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body(scenario, marker, (_SPAN_POST,)))
+ ended: Final = _ended_in_band(response, status)
+ pieces: Final = _TEXTS[scenario]
+ seen_by_hook: Final = "".join(pieces[: next(i for i, piece in enumerate(pieces) if _SPAN in piece) + 1])
+ assert ended.content == ("" if status == 400 else pieces[0]), response.text
+ assert ended.error["code"] == "400", ended.error
+ assert ended.error["message"] == f"Content blocked: {_SPAN}", ended.error
+ assert object_value(ended.error["provider_specific_fields"])["matched_span"] == str(
+ re.search(_SPAN, seen_by_hook)
+ ), ended.error
+
+
+ ("scenario", "status"),
+ [pytest.param("filter-early", 403, id="before_the_first_chunk"), pytest.param("filter-late", 200, id="mid_stream")],
+)
+def test_failure_hook_replacement_is_the_error_the_stream_ends_with(rig: Rig, scenario: str, status: int) -> None:
+ marker: Final = _marker()
+ body: Final = _body(scenario, marker, (_FILTER,))
+ replaced: Final = {
+ **body,
+ "messages": [{"role": "user", "content": f"scenario-{scenario} marker-{marker} {_REPLACE}"}],
+ }
+ response: Final = _stream_chat(rig, replaced)
+ ended: Final = _ended_in_band(response, status)
+ assert ended.error["code"] == "403", ended.error
+ assert ended.error["message"] == _REPLACEMENT_MESSAGE, ended.error
+ assert "keeper" not in json.dumps(ended.error), ended.error
+
+
+def test_buffered_block_after_keepalive_pings_ends_with_an_error_event_and_done(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("buffered", marker, (_BUFFERED,), keepalive_seconds=1))
+ assert response.text.startswith(": ping\n\n"), response.text
+ ended: Final = _ended_in_band(response, 200)
+ assert ended.content == "", response.text
+ assert ended.error["code"] == "400", ended.error
+ assert ended.error["message"] == "Buffered block: keeper", ended.error
+
+
+def test_clean_stream_with_guardrails_on_ends_with_stop_and_one_done(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("clean", marker, (_FILTER, _SPAN_POST)))
+ assert response.status_code == 200, response.text
+ lines: Final = _data_lines(response.text)
+ assert lines[-1] == "[DONE]" and lines.count("[DONE]") == 1, response.text
+ payloads: Final = _payloads(response.text)
+ assert all("error" not in payload for payload in payloads), response.text
+ assert _content(payloads) == "".join(_TEXTS["clean"]), response.text
+ assert "stop" in _finish_reasons(payloads), response.text
+
+
+def test_gemini_route_provider_failure_mid_stream_sends_an_error_frame_without_done(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = rig.proxy.gateway.request(
+ "POST",
+ f"/v1beta/models/{_MODEL}:streamGenerateContent",
+ {"contents": [{"role": "user", "parts": [{"text": f"scenario-drop marker-{marker}"}]}]},
+ params={"alt": "sse"},
+ )
+ assert response.status_code == 200, response.text
+ assert "[DONE]" not in response.text, response.text
+ payloads: Final = _payloads(response.text)
+ assert "error" in payloads[-1] and all("error" not in payload for payload in payloads[:-1]), response.text
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_mid_stream_block_releases_the_parallel_request_slot_and_logs_one_failure(rig: Rig) -> None:
+ marker: Final = _marker()
+ with rig.proxy.gateway.scenario() as scenario:
+ key: Final = scenario.key(max_parallel_requests=1)
+ with rig.proxy.gateway.client.stream(
+ "POST",
+ "/v1/chat/completions",
+ json=_body("filter-late", marker, (_FILTER,)),
+ headers={"Authorization": f"Bearer {key}"},
+ ) as blocked:
+ call_id: Final = blocked.headers["x-litellm-call-id"]
+ with contextlib.suppress(httpx.RemoteProtocolError):
+ blocked.read()
+ follow_up: Final = rig.proxy.gateway.request(
+ "POST", "/v1/chat/completions", _body("clean", _marker(), ()), key=key
+ )
+ assert follow_up.status_code == 200, follow_up.text
+ assert _content(_payloads(follow_up.text)) == "".join(_TEXTS["clean"]), follow_up.text
+ 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,
+ )
+ assert [row["status"] for row in rows] == ["failure"], rows
+
+
+def test_failure_hook_replacement_hides_a_non_http_failure_mid_stream(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("clean", marker, (_RAISING,), "raise-builtin-after-1", _REPLACE))
+ ended: Final = _ended_in_band(response, 200)
+ assert ended.content == _TEXTS["clean"][0], response.text
+ assert ended.error["code"] == "403", ended.error
+ assert ended.error["message"] == _REPLACEMENT_MESSAGE, ended.error
+ assert _CRASH_MESSAGE not in response.text, response.text
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_failure_hook_replacement_answers_an_early_non_http_failure_as_a_json_error(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("clean", marker, (_RAISING,), "raise-builtin-after-0", _REPLACE))
+ assert response.status_code == 403, response.text
+ assert response.headers["content-type"].startswith("application/json"), response.headers
+ error: Final = object_value(JSON_OBJECT.validate_json(response.content)["error"])
+ assert error["code"] == "403", error
+ assert error["message"] == _REPLACEMENT_MESSAGE, error
+ assert _CRASH_MESSAGE not in response.text, response.text
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_failure_hook_replacement_ends_a_queue_stream_that_fails_before_the_first_chunk(rig: Rig) -> None:
+ marker: Final = _marker()
+ body: Final = _body("clean", marker, (_RAISING,), "raise-builtin-after-0", _REPLACE, priority=0)
+ response: Final = rig.proxy.gateway.request("POST", "/queue/chat/completions", body)
+ ended: Final = _ended_in_band(response, 200)
+ assert ended.content == "", response.text
+ assert ended.error["code"] == "403", ended.error
+ assert ended.error["message"] == _REPLACEMENT_MESSAGE, ended.error
+ assert _CRASH_MESSAGE not in response.text, response.text
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_early_non_http_failure_without_a_replacement_keeps_its_json_error_body(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = _stream_chat(rig, _body("clean", marker, (_RAISING,), "raise-builtin-after-0"))
+ assert response.status_code == 500, response.text
+ assert response.headers["content-type"].startswith("application/json"), response.headers
+ error: Final = object_value(JSON_OBJECT.validate_json(response.content)["error"])
+ assert error["code"] == "500", error
+ assert _CRASH_MESSAGE in string_value(error["message"]), error
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def _responses_body(marker: str, *directives: str) -> dict[str, JsonValue]:
+ return {
+ "model": _MODEL,
+ "stream": True,
+ "input": _prompt("clean", marker, *directives),
+ "guardrails": [_RAISING],
+ "cache": {"no-cache": True},
+ }
+
+
+def _failed_response_error(response: httpx.Response) -> dict[str, JsonValue]:
+ assert response.status_code == 200, response.text
+ lines: Final = _data_lines(response.text)
+ assert lines[-1] == "[DONE]" and lines.count("[DONE]") == 1, response.text
+ events: Final = _payloads(response.text)
+ kinds: Final = tuple(string_value(event["type"]) for event in events)
+ assert kinds[0] == "response.created" and kinds[-1] == "response.failed", response.text
+ assert "response.completed" not in kinds and kinds.count("response.failed") == 1, response.text
+ streamed: Final = "".join(
+ string_value(event.get("delta") or "") for event in events if event["type"] == "response.output_text.delta"
+ )
+ assert streamed == "".join(_TEXTS["clean"]), response.text
+ created: Final = object_value(events[0]["response"])
+ failed: Final = object_value(events[-1]["response"])
+ assert failed["status"] == "failed" and failed["id"] == created["id"], failed
+ return object_value(failed["error"])
+
+
+def test_responses_stream_failing_on_a_builtin_exception_ends_with_response_failed(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = rig.proxy.gateway.request(
+ "POST", "/v1/responses", _responses_body(marker, "raise-builtin-after-2")
+ )
+ error: Final = _failed_response_error(response)
+ assert error == {"code": "server_error", "message": _CRASH_MESSAGE}, error
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_responses_stream_failure_hook_replacement_is_the_failed_response_error(rig: Rig) -> None:
+ marker: Final = _marker()
+ response: Final = rig.proxy.gateway.request(
+ "POST", "/v1/responses", _responses_body(marker, "raise-http-after-2", _REPLACE)
+ )
+ error: Final = _failed_response_error(response)
+ assert error["code"] == "permission_error", error
+ assert _REPLACEMENT_MESSAGE in string_value(error["message"]), error
+ assert _RAISED_BLOCK not in response.text, response.text
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def _until_stream_error(stream: Iterator[Mapping[str, object]]) -> Iterator[Mapping[str, object] | Exception]:
+ try:
+ yield from stream
+ except proxy_client.StreamError as error:
+ yield error
+
+
+def test_python_client_raises_the_block_error_after_the_partial_reply(rig: Rig) -> None:
+ marker: Final = _marker()
+ with rig.proxy.gateway.scenario() as scenario:
+ client: Final = proxy_client.ChatClient(
+ str(rig.proxy.gateway.client.base_url), api_key=scenario.key(metadata={"guardrails": [_FILTER]})
+ )
+ stream: Final = client.completions_stream(
+ model=_MODEL, messages=[{"role": "user", "content": _prompt("filter-late", marker)}]
+ )
+ *chunks, last = tuple(_until_stream_error(stream))
+ assert isinstance(last, proxy_client.StreamError), last
+ payloads: Final = tuple(JSON_OBJECT.validate_python(chunk) for chunk in chunks)
+ assert all("error" not in payload for payload in payloads), payloads
+ content: Final = _content(payloads)
+ assert content and _LEAD.startswith(content), payloads
+ assert "keeper" in str(last), str(last)
+ assert JSON_OBJECT.validate_python(last.error)["code"] == "400", last.error
+ assert _calls_with(rig.upstream, marker) == 1
+
+
+def test_non_streaming_pre_call_block_with_an_unencodable_detail_answers_400(rig: Rig) -> None:
+ pytest.skip("BUG: a non-JSON value in a guardrail HTTPException detail answers 500 on non-streaming chat")
+ marker: Final = _marker()
+ content: Final = f"{_SPAN} in the prompt scenario-clean marker-{marker}"
+ response: Final = rig.proxy.gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": _MODEL,
+ "messages": [{"role": "user", "content": content}],
+ "guardrails": [_SPAN_PRE],
+ "cache": {"no-cache": True},
+ },
+ )
+ assert response.status_code == 400, response.text
+ error: Final = object_value(JSON_OBJECT.validate_json(response.content)["error"])
+ assert error["message"] == json.dumps({"matched_span": str(re.search(_SPAN, content))}), error
+ assert _calls_with(rig.upstream, marker) == 0
diff --git a/tests/integration/streaming/test_responses_bridge_stream_errors.py b/tests/integration/streaming/test_responses_bridge_stream_errors.py
index 9e8f456df49..a3efbd233b9 100644
--- a/tests/integration/streaming/test_responses_bridge_stream_errors.py
+++ b/tests/integration/streaming/test_responses_bridge_stream_errors.py
@@ -347,6 +347,7 @@ def test_bridged_rate_limit_after_output_is_a_provider_typed_error_frame_behind_
)
response, _ = _in_stream_error_status(gateway, stream)
assert response.status_code == 200, response.text
+ assert response.text.rstrip().endswith("data: [DONE]") and response.text.count("data: [DONE]") == 1, response.text
frames: Final = data_frames(response.text)
content: Final = chat_content(frames)
assert content == "Hello there", response.text
diff --git a/tests/unit/experimental_mcp_client/test_mcp_client.py b/tests/unit/experimental_mcp_client/test_mcp_client.py
index 418738a9dca..6ea76a0a8a7 100644
--- a/tests/unit/experimental_mcp_client/test_mcp_client.py
+++ b/tests/unit/experimental_mcp_client/test_mcp_client.py
@@ -3,7 +3,6 @@ import base64
import importlib
import json
import os
-import selectors
import sys
from collections.abc import AsyncIterator, Callable
from contextlib import AbstractAsyncContextManager, asynccontextmanager
@@ -71,6 +70,7 @@ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import StaticHeaderAuth
from litellm.types.mcp import MCPAuth, MCPStdioConfig, MCPTransport
from litellm.types.mcp_server.mcp_server_manager import MCPServer
+from tests._support.clock_loops import AutojumpClockLoop, ManualClockLoop
_JSONRPC_MESSAGE_ADAPTER: Final = TypeAdapter(JSONRPCMessage)
@@ -305,42 +305,6 @@ class _MockTransportClient(MCPClient):
return streamable_http_client(self.server_url, http_client=http_client), http_client
-class _ManualClockLoop(asyncio.SelectorEventLoop):
- """An event loop whose clock moves only when the test advances it, so timeouts fire on test-controlled conditions"""
-
- def __init__(self, selector: selectors.BaseSelector | None = None) -> None:
- super().__init__(selector)
- self._now = 0.0
-
- def time(self) -> float:
- return self._now
-
- def advance(self, seconds: float) -> None:
- self._now += seconds
-
-
-class _AutojumpSelector(selectors.DefaultSelector):
- def __init__(self, advance: Callable[[float], None]) -> None:
- super().__init__()
- self._advance = advance
-
- def select(self, timeout: float | None = None) -> list[tuple[selectors.SelectorKey, int]]:
- ready: Final = super().select(0)
- if ready or timeout == 0:
- return ready
- if timeout is None:
- return super().select(None)
- self._advance(timeout)
- return []
-
-
-class _AutojumpClockLoop(_ManualClockLoop):
- """A manual-clock loop that jumps to the next timer only once no callback or I/O event is left to run"""
-
- def __init__(self) -> None:
- super().__init__(_AutojumpSelector(self.advance))
-
-
class _FakeExceptionGroup(Exception):
"""Duck-typed stand-in for an anyio/builtin ExceptionGroup.
@@ -2140,7 +2104,7 @@ async def test_transport_parsing_failure_is_preserved(transport: MCPTransport, f
def test_sse_read_failure_is_preserved() -> None:
- loop: Final = _AutojumpClockLoop()
+ loop: Final = AutojumpClockLoop()
async def run() -> None:
client: Final = MCPClient(server_url="https://example.com/sse", transport_type=MCPTransport.sse, timeout=0.2)
@@ -2614,7 +2578,7 @@ def test_optional_discovery_rejects_incomplete_walks(
"resources/list": {"name": "first", "uri": "test://first"},
"resources/templates/list": {"name": "first", "uriTemplate": "test://{name}"},
}[method]
- loop: Final = _ManualClockLoop()
+ loop: Final = ManualClockLoop()
async def run() -> None:
cancelled: Final = asyncio.Event()
@@ -3632,7 +3596,7 @@ async def test_modern_call_requires_schema_from_bounded_listing(
def test_modern_call_uses_discovery_deadline_for_multiple_pages() -> None:
from mcp.types import ToolsCapability
- loop: Final = _AutojumpClockLoop()
+ loop: Final = AutojumpClockLoop()
async def respond(request: httpx2.Request) -> httpx2.Response:
payload: Final = _JSONRPC_MESSAGE_ADAPTER.validate_json(request.content)
@@ -3926,7 +3890,7 @@ async def test_optional_discovery_retains_freshness_across_pages(
}
return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": listing_result})
- clock: Final = _ManualClockLoop()
+ clock: Final = ManualClockLoop()
class CleanupTransport(httpx2.AsyncBaseTransport):
def __init__(self) -> None:
@@ -3986,7 +3950,7 @@ def test_prompt_continuation_polling_respects_the_original_deadline() -> None:
)
return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload.id, "result": result})
- loop: Final = _AutojumpClockLoop()
+ loop: Final = AutojumpClockLoop()
client: Final = _MockTransportClient(
respond, server_url="https://example.com/mcp", protocol_version="2026-07-28", timeout=0.12
)
diff --git a/tests/unit/proxy/client/cli/test_chat_commands.py b/tests/unit/proxy/client/cli/test_chat_commands.py
new file mode 100644
index 00000000000..ed3201ce75f
--- /dev/null
+++ b/tests/unit/proxy/client/cli/test_chat_commands.py
@@ -0,0 +1,47 @@
+import io
+from typing import Final
+
+import pytest
+import responses
+from pydantic import JsonValue
+from rich.console import Console
+
+from litellm.proxy.client.chat import ChatClient
+from litellm.proxy.client.cli.commands.chat import _stream_response
+
+BASE_URL: Final = "http://localhost:8000"
+MESSAGE: Final = "blocked [/pii] :warning: content in [prompt_injection] after 42 tokens"
+PARTIAL_THEN_ERROR: Final = (
+ b'data: {"choices": [{"delta": {"content": "Hel"}}]}\n\n'
+ + f'data: {{"error": {{"message": "{MESSAGE}"}}}}\n\n'.encode()
+ + b"data: [DONE]\n\n"
+)
+
+
+ "status, body, json_body",
+ [
+ (200, PARTIAL_THEN_ERROR, None),
+ (400, None, {"error": {"message": MESSAGE}}),
+ (400, MESSAGE.encode(), None),
+ ],
+ ids=["error frame mid-stream", "json error before the stream", "text error before the stream"],
+)
+def test_stream_response_prints_the_error_message_as_plain_text(
+ status: int, body: bytes | None, json_body: JsonValue
+) -> None:
+ responses.add(responses.POST, f"{BASE_URL}/chat/completions", body=body, json=json_body, status=status)
+ output: Final = io.StringIO()
+
+ content: Final = _stream_response(
+ Console(file=output, width=200, force_terminal=True, color_system="truecolor"),
+ ChatClient(base_url=BASE_URL),
+ "gpt-4",
+ [{"role": "user", "content": "hi"}],
+ 0.7,
+ None,
+ )
+
+ assert content is None
+ assert MESSAGE in output.getvalue()
diff --git a/tests/unit/proxy/client/test_chat.py b/tests/unit/proxy/client/test_chat.py
index 9ab7150c288..5068eba7a15 100644
--- a/tests/unit/proxy/client/test_chat.py
+++ b/tests/unit/proxy/client/test_chat.py
@@ -1,15 +1,17 @@
import importlib
import importlib.util
from importlib.machinery import PathFinder
+import json
import time
import site
import sys
+from typing import Final
import pytest
import requests
-from pydantic import ValidationError
+from pydantic import JsonValue, ValidationError
from litellm.proxy.client.chat import ChatClient
-from litellm.proxy.client.exceptions import UnauthorizedError
+from litellm.proxy.client.exceptions import StreamError, UnauthorizedError
def _load_http_mocking_responses():
@@ -283,6 +285,59 @@ def test_completions_stream_yields_parsed_sse_chunks(client, base_url, sample_me
assert list(client.completions_stream(model="gpt-4", messages=sample_messages)) == expected
+ "error_frame, error, message",
+ [
+ (
+ b'data: {"error": {"message": "blocked by guardrail", "type": "None", "code": "400"}}',
+ {"message": "blocked by guardrail", "type": "None", "code": "400"},
+ "blocked by guardrail",
+ ),
+ (b'data: {"error": "upstream cut"}', "upstream cut", "upstream cut"),
+ (b'data: {"error": {"code": "500"}}', {"code": "500"}, "{'code': '500'}"),
+ ],
+)
+def test_completions_stream_raises_on_an_error_frame_after_partial_content(
+ client: ChatClient,
+ base_url: str,
+ sample_messages: list[dict[str, str]],
+ error_frame: bytes,
+ error: JsonValue,
+ message: str,
+) -> None:
+ body: Final = b'data: {"choices": [{"delta": {"content": "Hel"}}]}\n\n' + error_frame + b"\n\ndata: [DONE]\n\n"
+ responses.add(responses.POST, f"{base_url}/chat/completions", body=body, status=200)
+ stream: Final = client.completions_stream(model="gpt-4", messages=sample_messages)
+
+ assert next(stream) == {"choices": [{"delta": {"content": "Hel"}}]}
+ with pytest.raises(StreamError) as raised:
+ next(stream)
+ assert raised.value.error == error
+ assert str(raised.value) == message
+
+
[email protected]("error", [None, False, 0, "", {}])
+def test_completions_stream_yields_a_chunk_whose_error_is_empty(
+ client: ChatClient, base_url: str, sample_messages: list[dict[str, str]], error: JsonValue
+) -> None:
+ chunk: Final = {"choices": [{"delta": {"content": "Hel"}}], "error": error}
+ body: Final = b"data: " + json.dumps(chunk).encode() + b"\n\ndata: [DONE]\n\n"
+ responses.add(responses.POST, f"{base_url}/chat/completions", body=body, status=200)
+
+ assert list(client.completions_stream(model="gpt-4", messages=sample_messages)) == [chunk]
+
+
+def test_stream_error_redacts_a_key_in_its_message() -> None:
+ key: Final = "sk-" + "a1b2c3d4" * 4
+
+ error: Final = StreamError({"message": f"upstream rejected {key}"})
+
+ assert key not in str(error)
+ assert str(error).startswith("upstream rejected ")
+
+
@responses.activate
def test_completions_stream_rejects_bytes_that_are_not_utf8(client, base_url, sample_messages):
responses.add(responses.POST, f"{base_url}/chat/completions", body=b"data: \xff\n\n", status=200)
diff --git a/tests/unit/proxy/proxy_server/test_streaming_helpers.py b/tests/unit/proxy/proxy_server/test_streaming_helpers.py
index f53e1931782..227a099889d 100644
--- a/tests/unit/proxy/proxy_server/test_streaming_helpers.py
+++ b/tests/unit/proxy/proxy_server/test_streaming_helpers.py
@@ -17,21 +17,23 @@ from __future__ import annotations
import asyncio
import json
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Callable
from typing import Final, Literal
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
from fastapi import HTTPException, Response
-from fastapi.responses import StreamingResponse
+from fastapi.responses import JSONResponse, StreamingResponse
from openai import APIError as OpenAIAPIError
from pydantic import BaseModel
import litellm
import litellm.proxy.proxy_server as ps
from litellm.constants import RETURN_RAW_MODEL_NAME_METADATA_KEY
+from litellm.integrations.custom_logger import CustomLogger
from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.common_request_processing import create_response
from litellm.proxy.proxy_server import (
_apply_streaming_chunk_hooks,
_fast_serialize_simple_model_response_stream,
@@ -54,6 +56,7 @@ from litellm.types.llms.openai import (
ResponsesAPIResponse,
)
from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices, Usage
+from tests._support.clock_loops import AutojumpClockLoop
from .conftest import normalize
@@ -905,6 +908,318 @@ async def test_async_data_generator_mid_stream_exception_yields_error_payload(
assert any(isinstance(item, str) and item.startswith('data: {"error":') for item in out)
+_BLOCK_MESSAGE: Final = "Content blocked: keyword 'keeper' detected"
+_BLOCK_ERROR: Final = {
+ "message": _BLOCK_MESSAGE,
+ "type": "invalid_request_error",
+ "param": None,
+ "code": "400",
+ "provider_specific_fields": {"error": _BLOCK_MESSAGE},
+}
+_UNSERIALIZABLE_SPAN: Final = object()
+
+
+async def _blocked_after(chunks: int, detail: dict[str, object]) -> AsyncIterator[ModelResponseStream]:
+ for _ in range(chunks):
+ yield _simple_chunk(content="partial")
+ raise HTTPException(status_code=400, detail=detail)
+
+
+async def _served(
+ upstream: AsyncIterator[ModelResponseStream], request_data: dict[str, object] | None = None
+) -> tuple[int, str | None, tuple[str, ...]]:
+ response: Final = await create_response(
+ generator=async_data_generator(
+ response=upstream, user_api_key_dict=_user_auth(), request_data=dict(request_data or {})
+ ),
+ media_type="text/event-stream",
+ headers={},
+ )
+ assert isinstance(response, StreamingResponse)
+ body: Final = "".join(
+ [part if isinstance(part, str) else bytes(part).decode() async for part in response.body_iterator]
+ )
+ return response.status_code, response.media_type, tuple(frame for frame in body.split("\n\n") if frame)
+
+
+def _error_of(frame: str) -> dict[str, object]:
+ return json.loads(frame.removeprefix("data: "))["error"]
+
+
+ "detail,expected_message,expected_fields",
+ [
+ pytest.param(
+ {"error": _BLOCK_MESSAGE, "guardrail": "block-keeper-word"},
+ _BLOCK_MESSAGE,
+ {"error": _BLOCK_MESSAGE, "guardrail": "block-keeper-word"},
+ id="json_detail",
+ ),
+ pytest.param(
+ {"error": _BLOCK_MESSAGE, "matched_span": _UNSERIALIZABLE_SPAN},
+ _BLOCK_MESSAGE,
+ {"error": _BLOCK_MESSAGE, "matched_span": str(_UNSERIALIZABLE_SPAN)},
+ id="non_json_detail",
+ ),
+ pytest.param(
+ {"matched_span": _UNSERIALIZABLE_SPAN},
+ json.dumps({"matched_span": str(_UNSERIALIZABLE_SPAN)}),
+ {"matched_span": str(_UNSERIALIZABLE_SPAN)},
+ id="non_json_detail_without_message",
+ ),
+ ],
+)
+async def test_guardrail_block_after_the_first_chunk_ends_the_stream_with_an_error_event(
+ detail: dict[str, object], expected_message: str, expected_fields: dict[str, str]
+) -> None:
+ status_code, _, frames = await _served(_blocked_after(1, detail))
+
+ assert status_code == 200
+ assert len(frames) == 3
+ assert json.loads(frames[0].removeprefix("data: "))["choices"][0]["delta"]["content"] == "partial"
+ assert _error_of(frames[1]) == {
+ "message": expected_message,
+ "type": "invalid_request_error",
+ "param": None,
+ "code": "400",
+ "provider_specific_fields": expected_fields,
+ }
+ assert frames[2] == "data: [DONE]"
+
+
+async def test_guardrail_block_mid_stream_on_a_gemini_stream_sends_no_openai_error_event() -> None:
+ response: Final = await create_response(
+ generator=async_data_generator(
+ response=_blocked_after(1, {"error": _BLOCK_MESSAGE}),
+ user_api_key_dict=_user_auth(),
+ request_data={"_litellm_skip_openai_stream_done": True},
+ ),
+ media_type="text/event-stream",
+ headers={},
+ )
+ assert isinstance(response, StreamingResponse)
+ parts: Final = aiter(response.body_iterator)
+ first: Final = await anext(parts)
+
+ with pytest.raises(HTTPException):
+ await anext(parts)
+ assert '"error"' not in (first if isinstance(first, str) else bytes(first).decode())
+
+
+async def _upstream_fails_after(chunks: int) -> AsyncIterator[ModelResponseStream]:
+ for _ in range(chunks):
+ yield _simple_chunk(content="partial")
+ raise RuntimeError("upstream reset")
+
+
+ "request_data,closing_frames",
+ [
+ pytest.param({}, ("data: [DONE]",), id="openai_stream"),
+ pytest.param({"_litellm_skip_openai_stream_done": True}, (), id="gemini_stream"),
+ ],
+)
+async def test_upstream_failure_mid_stream_ends_with_an_error_event(
+ request_data: dict[str, object], closing_frames: tuple[str, ...]
+) -> None:
+ status_code, _, frames = await _served(_upstream_fails_after(1), request_data)
+
+ assert status_code == 200
+ assert _error_of(frames[1])["message"] == "upstream reset"
+ assert frames[2:] == closing_frames
+
+
+class _ReplacesClientErrors(CustomLogger):
+ async def async_post_call_failure_hook(
+ self,
+ request_data: dict,
+ original_exception: Exception,
+ user_api_key_dict: UserAPIKeyAuth,
+ traceback_str: str | None = None,
+ ) -> HTTPException:
+ return HTTPException(status_code=403, detail="Request blocked by policy")
+
+
+ "upstream,original_message,expected_status",
+ [
+ pytest.param(
+ lambda: _blocked_after(0, {"error": _BLOCK_MESSAGE}), _BLOCK_MESSAGE, 403, id="block_before_the_first_chunk"
+ ),
+ pytest.param(lambda: _blocked_after(1, {"error": _BLOCK_MESSAGE}), _BLOCK_MESSAGE, 200, id="block_mid_stream"),
+ pytest.param(lambda: _upstream_fails_after(1), "upstream reset", 200, id="failure_mid_stream"),
+ ],
+)
+async def test_stream_error_sends_the_failure_hook_replacement(
+ monkeypatch: pytest.MonkeyPatch,
+ upstream: Callable[[], AsyncIterator[ModelResponseStream]],
+ original_message: str,
+ expected_status: int,
+) -> None:
+ monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
+
+ status_code, _, frames = await _served(upstream())
+
+ assert status_code == expected_status
+ assert original_message not in "".join(frames)
+ assert _error_of(frames[-2]) == {
+ "message": "Request blocked by policy",
+ "type": "permission_error",
+ "param": None,
+ "code": "403",
+ }
+ assert frames[-1] == "data: [DONE]"
+
+
+async def test_failure_before_the_first_chunk_answers_the_failure_hook_replacement_as_json(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
+
+ response: Final = await create_response(
+ generator=async_data_generator(
+ response=_upstream_fails_after(0), user_api_key_dict=_user_auth(), request_data={}
+ ),
+ media_type="text/event-stream",
+ headers={},
+ )
+
+ assert isinstance(response, JSONResponse)
+ assert response.status_code == 403
+ assert json.loads(bytes(response.body))["error"]["message"] == "Request blocked by policy"
+ assert b"upstream reset" not in bytes(response.body)
+
+
+async def test_failure_before_the_first_chunk_on_a_bare_stream_still_ends_with_the_replacement_event(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
+
+ frames: Final = tuple(
+ [
+ frame
+ async for frame in async_data_generator(
+ response=_upstream_fails_after(0), user_api_key_dict=_user_auth(), request_data={}
+ )
+ ]
+ )
+
+ assert _error_of(frames[0].strip())["message"] == "Request blocked by policy"
+ assert frames[1:] == ("data: [DONE]\n\n",)
+
+
+async def test_responses_stream_failure_sends_the_failure_hook_replacement(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
+ response: Final = ResponsesAPIResponse(id="resp_visible", created_at=1, model="gpt-6-astra", output=[])
+
+ async def upstream() -> AsyncIterator[BaseModel]:
+ yield ResponseCreatedEvent.model_validate({"type": "response.created", "sequence_number": 0, "response": response})
+ raise HTTPException(status_code=400, detail={"error": _BLOCK_MESSAGE})
+
+ frames: Final = tuple(
+ [
+ frame.decode() if isinstance(frame, bytes) else frame
+ async for frame in select_data_generator(
+ response=upstream(), user_api_key_dict=_user_auth(), request_data={}, responses_stream_errors=True
+ )
+ ]
+ )
+ failure: Final = ResponseFailedEvent.model_validate_json(
+ next(line.removeprefix("data: ") for line in frames[-2].splitlines() if line.startswith("data: "))
+ )
+
+ assert _BLOCK_MESSAGE not in "".join(frames)
+ assert failure.response.error is not None
+ assert failure.response.error["code"] == "permission_error"
+ assert "Request blocked by policy" in failure.response.error["message"]
+ assert frames[-1] == "data: [DONE]\n\n"
+
+
+ "detail,expected_fields",
+ [
+ pytest.param({"error": _BLOCK_MESSAGE}, {"error": _BLOCK_MESSAGE}, id="json_detail"),
+ pytest.param(
+ {"error": _BLOCK_MESSAGE, "matched_span": _UNSERIALIZABLE_SPAN},
+ {"error": _BLOCK_MESSAGE, "matched_span": str(_UNSERIALIZABLE_SPAN)},
+ id="non_json_detail",
+ ),
+ ],
+)
+async def test_guardrail_block_before_the_first_chunk_keeps_its_http_status(
+ detail: dict[str, object], expected_fields: dict[str, str]
+) -> None:
+ status_code, media_type, frames = await _served(_blocked_after(0, detail))
+
+ assert (status_code, media_type) == (400, "text/event-stream")
+ assert len(frames) == 2
+ assert _error_of(frames[0]) == {**_BLOCK_ERROR, "provider_specific_fields": expected_fields}
+ assert frames[1] == "data: [DONE]"
+
+
+async def _blocked_after_a_stall() -> AsyncIterator[ModelResponseStream]:
+ await asyncio.sleep(1.5)
+ async for chunk in _blocked_after(0, {"error": _BLOCK_MESSAGE}):
+ yield chunk
+
+
+def test_guardrail_block_after_a_keepalive_ping_ends_the_stream_with_an_error_event(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 1)
+ loop: Final = AutojumpClockLoop()
+
+ try:
+ status_code, _, frames = loop.run_until_complete(_served(_blocked_after_a_stall()))
+ finally:
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ loop.close()
+
+ assert status_code == 200
+ assert frames[0] == ": ping"
+ assert _error_of(frames[-2]) == _BLOCK_ERROR
+ assert frames[-1] == "data: [DONE]"
+
+class _BlocksKeeperPerChunk(CustomLogger):
+ async def async_post_call_streaming_hook(self, user_api_key_dict: UserAPIKeyAuth, response: str) -> None:
+ if "keeper" in response:
+ raise HTTPException(status_code=400, detail={"error": _BLOCK_MESSAGE})
+
+
+async def _chunks(*contents: str) -> AsyncIterator[ModelResponseStream]:
+ for content in contents:
+ yield _simple_chunk(content=content)
+
+
+ "contents,expected_status,expected_frames",
+ [
+ pytest.param(("the keeper",), 400, 2, id="first_chunk"),
+ pytest.param(("partial", "the keeper"), 200, 3, id="second_chunk"),
+ ],
+)
+async def test_per_chunk_guardrail_block_keeps_early_blocks_on_their_status_and_ends_later_ones_in_band(
+ monkeypatch: pytest.MonkeyPatch, contents: tuple[str, ...], expected_status: int, expected_frames: int
+) -> None:
+ monkeypatch.setattr(litellm, "callbacks", [_BlocksKeeperPerChunk()])
+
+ status_code, media_type, frames = await _served(_chunks(*contents))
+
+ assert (status_code, media_type) == (expected_status, "text/event-stream")
+ assert len(frames) == expected_frames
+ assert _error_of(frames[-2]) == _BLOCK_ERROR
+ assert frames[-1] == "data: [DONE]"
+
+
_UPSTREAM_BODY: Final = {
"code": "cyber_policy",
"message": "Upstream rejected request: flagged for possible cybersecurity risk",
@@ -942,6 +1257,9 @@ _UPSTREAM_BODY: Final = {
),
"cyber_policy", id="upstream_body_code_and_message",
),
+ pytest.param(
+ "upstream_failure", RuntimeError("Upstream rejected request"), "server_error", id="builtin_exception"
+ ),
*(
pytest.param(
"upstream_failure", HTTPException(status_code=status, detail="Upstream rejected request"),
@@ -956,7 +1274,7 @@ _UPSTREAM_BODY: Final = {
)
async def test_responses_stream_keeps_tool_deltas_and_only_emits_a_valid_terminal(
terminal: Literal["completed", "serialization_failure", "failure_after_completed", "upstream_failure"],
- upstream_error: HTTPException | OpenAIAPIError | None,
+ upstream_error: Exception | None,
expected_code: str | None,
) -> None:
class ToolDelta(BaseModel):
diff --git a/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py b/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
index fbdd8d4d7fb..0dbf3451c3b 100644
--- a/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
+++ b/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
@@ -4308,7 +4308,7 @@ async def test_async_data_generator_midstream_error():
return chunk
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(side_effect=mock_streaming_hook)
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
# Mock the global proxy_logging_obj
with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
@@ -7333,7 +7333,7 @@ async def test_async_data_generator_cleanup_on_early_exit():
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(
side_effect=lambda **kwargs: kwargs.get("response")
)
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
# Create a mock response with aclose
mock_response = MagicMock()
@@ -7454,7 +7454,7 @@ async def test_async_data_generator_uses_direct_stream_fast_path_without_callbac
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
with patch.object(ProxyLogging, "fire_deferred_stream_logging") as mock_deferred_logging:
@@ -7510,7 +7510,7 @@ async def test_async_data_generator_preserves_non_raw_sse_like_bytes():
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
with patch.object(ProxyLogging, "fire_deferred_stream_logging"):
@@ -7567,7 +7567,7 @@ async def test_async_data_generator_buffers_split_google_native_sse_json_frame()
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
with patch.object(ProxyLogging, "fire_deferred_stream_logging"):
@@ -7614,7 +7614,7 @@ async def test_async_data_generator_flushes_raw_sse_stream_without_trailing_deli
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with (
patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj),
@@ -7663,7 +7663,7 @@ async def test_async_data_generator_errors_when_raw_sse_frame_exceeds_buffer_lim
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with (
patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj),
@@ -7719,7 +7719,7 @@ async def test_async_data_generator_checks_raw_sse_buffer_limit_after_complete_f
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with (
patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj),
@@ -7771,7 +7771,7 @@ async def test_async_data_generator_google_genai_stream_omits_openai_done():
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
with patch.object(ProxyLogging, "fire_deferred_stream_logging"):
@@ -7813,7 +7813,7 @@ async def test_async_data_generator_does_not_mark_completed_stream_as_disconnect
mock_proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
with patch.object(ProxyLogging, "fire_deferred_stream_logging"):
@@ -7947,7 +7947,7 @@ async def test_async_data_generator_cleanup_on_midstream_error():
mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(
side_effect=lambda **kwargs: kwargs.get("response")
)
- mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
mock_response = MagicMock()
mock_response.aclose = AsyncMock()
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.test.tsx
index a5407df172e..29b1cf44464 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.test.tsx
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { toast } from "@/lib/toast";
import { makeInteractionsRequest } from "./interactions_api";
vi.mock("@/components/networking", () => ({
@@ -75,4 +76,24 @@ describe("interactions_api", () => {
expect(mockUpdateUI).toHaveBeenCalledTimes(1);
expect(mockUpdateUI).toHaveBeenCalledWith("Hi", "gpt-5.4");
});
+
+ it("rejects and toasts the message when the stream ends with an error event", async () => {
+ const sse = [
+ 'data: {"event_type":"step.delta","index":0,"delta":{"type":"text","text":"Hi"}}',
+ 'data: {"error":{"message":"blocked by guardrail","type":"None","code":"400"}}',
+ "data: [DONE]",
+ "",
+ "",
+ ].join("\n\n");
+
+ mockFetch.mockResolvedValue({ ok: true, body: sseBody(sse) } as Response);
+
+ await expect(makeInteractionsRequest("hi", mockUpdateUI, "gpt-mini", "token")).rejects.toThrow(
+ "blocked by guardrail",
+ );
+
+ expect(mockUpdateUI).toHaveBeenCalledTimes(1);
+ expect(mockUpdateUI).toHaveBeenCalledWith("Hi", "gpt-mini");
+ expect(toast.fromError).toHaveBeenCalledWith(expect.stringContaining("blocked by guardrail"));
+ });
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.tsx
index d501175429e..095297ae610 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/interactions_api.tsx
@@ -1,6 +1,7 @@
import type { ResponseHeadersListener } from "@/lib/http/observeResponseHeaders";
import { toast } from "@/lib/toast";
import { getGatewayBaseUrl, getGlobalLitellmHeaderName } from "@/components/networking";
+import { streamErrorMessage } from "@/utils/streamErrorMessage";
import {
buildPlaygroundHeaders,
type CustomHeaders,
@@ -95,6 +96,11 @@ export async function makeInteractionsRequest(
continue;
}
+ const errorMessage = streamErrorMessage(event);
+ if (errorMessage !== null) {
+ throw new Error(errorMessage);
+ }
+
const eventType = event.event_type as string | undefined;
if (eventType === "interaction.created" || eventType === "interaction.completed") {
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.test.tsx
new file mode 100644
index 00000000000..8f199271c11
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.test.tsx
@@ -0,0 +1,126 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useConversation } from "./useConversation";
+
+vi.mock("@/components/networking", () => ({
+ getProxyBaseUrl: vi.fn(() => "https://example.com"),
+ getGlobalLitellmHeaderName: vi.fn(() => "Authorization"),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toast: { fromError: vi.fn(), info: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock("../utils", () => ({
+ convertToDotPrompt: vi.fn(() => "---\nmodel: gpt-5.4\n---\nhello"),
+ extractVariables: vi.fn(() => []),
+}));
+
+const sseBody = (text: string, splitAt: number | undefined) => {
+ const bytes = new TextEncoder().encode(text);
+ const parts = splitAt === undefined ? [bytes] : [bytes.slice(0, splitAt), bytes.slice(splitAt)];
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ parts.forEach((part) => controller.enqueue(part));
+ controller.close();
+ },
+ });
+};
+
+const sendMessage = async (sse: string, splitAt?: number) => {
+ vi.mocked(fetch).mockResolvedValue({ ok: true, body: sseBody(sse, splitAt) } as Response);
+ const { result } = renderHook(() => useConversation({}, "token"));
+ act(() => {
+ result.current.setInputMessage("hi");
+ });
+ await act(async () => {
+ await result.current.handleSendMessage();
+ });
+ return result.current.messages;
+};
+
+describe("useConversation", () => {
+ beforeEach(() => {
+ vi.stubGlobal("fetch", vi.fn());
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("streams the reply into the last assistant message", async () => {
+ const messages = await sendMessage(
+ [
+ 'data: {"model":"gpt-5.4","choices":[{"delta":{"content":"Hel"}}]}',
+ 'data: {"model":"gpt-5.4","choices":[{"delta":{"content":"lo"}}]}',
+ "data: [DONE]",
+ "",
+ ].join("\n\n"),
+ );
+
+ expect(messages.map(({ role, content }) => ({ role, content }))).toEqual([
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "Hello" },
+ ]);
+ });
+
+ it("shows the error event message after the partial reply when the stream ends with an error", async () => {
+ const messages = await sendMessage(
+ [
+ 'data: {"model":"gpt-5.4","choices":[{"delta":{"content":"Hel"}}]}',
+ 'data: {"error":{"message":"blocked by guardrail","type":"None","code":"400"}}',
+ "data: [DONE]",
+ "",
+ ].join("\n\n"),
+ );
+
+ expect(messages.map(({ role, content }) => ({ role, content }))).toEqual([
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "Hel" },
+ { role: "assistant", content: "Error: blocked by guardrail" },
+ ]);
+ });
+
+ it("shows an error event that arrives split across reads", async () => {
+ const sse = [
+ 'data: {"model":"gpt-5.4","choices":[{"delta":{"content":"Hel"}}]}',
+ 'data: {"error":{"message":"blocked by the café guardrail"}}',
+ "data: [DONE]",
+ "",
+ ].join("\n\n");
+ const insideTheAccent = new TextEncoder().encode(sse.slice(0, sse.indexOf("é"))).length + 1;
+
+ const messages = await sendMessage(sse, insideTheAccent);
+
+ expect(messages.map(({ role, content }) => ({ role, content }))).toEqual([
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "Hel" },
+ { role: "assistant", content: "Error: blocked by the café guardrail" },
+ ]);
+ });
+
+ it("skips a null event and keeps streaming", async () => {
+ const messages = await sendMessage(
+ ["data: null", 'data: {"model":"gpt-5.4","choices":[{"delta":{"content":"Hello"}}]}', "data: [DONE]", ""].join(
+ "\n\n",
+ ),
+ );
+
+ expect(messages.map(({ role, content }) => ({ role, content }))).toEqual([
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "Hello" },
+ ]);
+ });
+
+ it("replaces the empty assistant message with the error when the stream fails before any content", async () => {
+ const messages = await sendMessage(
+ ['data: {"error":{"message":"blocked by guardrail"}}', "data: [DONE]", ""].join("\n\n"),
+ );
+
+ expect(messages).toEqual([
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "Error: blocked by guardrail" },
+ ]);
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.ts b/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.ts
index c9634fd7338..199c2cb3970 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/prompt_editor_view/conversation_panel/useConversation.ts
@@ -4,6 +4,7 @@ import { TokenUsage } from "@/components/chat_ui/ResponseMetrics";
import { Message } from "./types";
import { convertToDotPrompt, extractVariables } from "../utils";
import { getProxyBaseUrl, getGlobalLitellmHeaderName } from "@/components/networking";
+import { streamErrorMessage } from "@/utils/streamErrorMessage";
export const useConversation = (prompt: any, accessToken: string | null) => {
const [isLoading, setIsLoading] = useState(false);
@@ -109,6 +110,7 @@ export const useConversation = (prompt: any, accessToken: string | null) => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
+ let buffer = "";
let assistantMessage = "";
let model: string | undefined;
@@ -120,8 +122,9 @@ export const useConversation = (prompt: any, accessToken: string | null) => {
const { done, value } = await reader.read();
if (done) break;
- const chunk = decoder.decode(value);
- const lines = chunk.split("\n");
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
for (const line of lines) {
if (line.startsWith("data: ")) {
@@ -130,36 +133,43 @@ export const useConversation = (prompt: any, accessToken: string | null) => {
continue;
}
+ let parsed;
try {
- const parsed = JSON.parse(data);
+ parsed = JSON.parse(data);
+ } catch (e) {
+ console.error("Error parsing chunk:", e);
+ continue;
+ }
- if (!model && parsed.model) {
- model = parsed.model;
- }
+ const errorMessage = streamErrorMessage(parsed);
+ if (errorMessage !== null) {
+ throw new Error(errorMessage);
+ }
- if (parsed.usage) {
- usage = parsed.usage;
- }
+ if (!model && parsed?.model) {
+ model = parsed.model;
+ }
+
+ if (parsed?.usage) {
+ usage = parsed.usage;
+ }
- const content = parsed.choices?.[0]?.delta?.content;
- if (content) {
- if (!timeToFirstToken) {
- timeToFirstToken = Date.now() - startTime;
- }
- assistantMessage += content;
- setMessages((prev) => {
- const newMessages = [...prev];
- newMessages[newMessages.length - 1] = {
- role: "assistant",
- content: assistantMessage,
- model,
- timeToFirstToken,
- };
- return newMessages;
- });
+ const content = parsed?.choices?.[0]?.delta?.content;
+ if (content) {
+ if (!timeToFirstToken) {
+ timeToFirstToken = Date.now() - startTime;
}
- } catch (e) {
- console.error("Error parsing chunk:", e);
+ assistantMessage += content;
+ setMessages((prev) => {
+ const newMessages = [...prev];
+ newMessages[newMessages.length - 1] = {
+ role: "assistant",
+ content: assistantMessage,
+ model,
+ timeToFirstToken,
+ };
+ return newMessages;
+ });
}
}
}
diff --git a/ui/litellm-dashboard/src/utils/streamErrorMessage.test.ts b/ui/litellm-dashboard/src/utils/streamErrorMessage.test.ts
new file mode 100644
index 00000000000..934f4f04986
--- /dev/null
+++ b/ui/litellm-dashboard/src/utils/streamErrorMessage.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { streamErrorMessage } from "./streamErrorMessage";
+
+describe("streamErrorMessage", () => {
+ it("returns the message of an error object", () => {
+ expect(streamErrorMessage({ error: { message: "blocked by guardrail", code: "400" } })).toBe(
+ "blocked by guardrail",
+ );
+ });
+
+ it("returns a string error as is", () => {
+ expect(streamErrorMessage({ error: "upstream cut" })).toBe("upstream cut");
+ });
+
+ it("serializes an error object without a string message", () => {
+ expect(streamErrorMessage({ error: { code: 500 } })).toBe('{"code":500}');
+ });
+
+ it.each([[{ choices: [{ delta: { content: "hi" } }] }], [{ error: null }], [7], [null]])(
+ "returns null for a frame that carries no error: %j",
+ (frame) => {
+ expect(streamErrorMessage(frame)).toBeNull();
+ },
+ );
+});
diff --git a/ui/litellm-dashboard/src/utils/streamErrorMessage.ts b/ui/litellm-dashboard/src/utils/streamErrorMessage.ts
new file mode 100644
index 00000000000..e447399f510
--- /dev/null
+++ b/ui/litellm-dashboard/src/utils/streamErrorMessage.ts
@@ -0,0 +1,15 @@
+const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null;
+
+export const streamErrorMessage = (frame: unknown): string | null => {
+ if (!isRecord(frame) || !frame.error) {
+ return null;
+ }
+ const { error } = frame;
+ if (typeof error === "string") {
+ return error;
+ }
+ if (isRecord(error) && typeof error.message === "string") {
+ return error.message;
+ }
+ return JSON.stringify(error);
+};