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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(streaming): report the deployment's api_base when a stream fails mid-way (#47045)
Mateo Wangc143954493ba
diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.pyindex f8aadc4258d..13a53c55337 100644--- a/litellm/litellm_core_utils/exception_mapping_utils.py+++ b/litellm/litellm_core_utils/exception_mapping_utils.py@@ -2413,6 +2413,35 @@ def _map_exception_by_status()+_NO_LITELLM_PARAMS: Final[Mapping[str, object]] = MappingProxyType({})+_URL_SCHEME: Final = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*")+_HOST_WITH_OPTIONAL_PORT: Final = re.compile(+ r"(?:(?:[A-Za-z0-9-]+\.)+[A-Za-z0-9-]+|localhost|\[[0-9A-Fa-f:.]+\])(?::\d+)?"+)+++def with_deployment_api_base(litellm_params: object) -> Mapping[str, object]:+ params: Final = as_str_mapping(litellm_params) or _NO_LITELLM_PARAMS+ metadata: Final = as_str_mapping(params.get("metadata"))+ deployment_api_base: Final = None if metadata is None else metadata.get("api_base")+ if not isinstance(deployment_api_base, str) or not deployment_api_base:+ return params+ return MappingProxyType({**params, "api_base": deployment_api_base})+++def _api_base_without_credentials(api_base: str) -> str:+ scheme, separator, _ = api_base.partition("://")+ scheme_prefix: Final = scheme + separator if separator and _URL_SCHEME.fullmatch(scheme) else ""+ authority_and_rest: Final = api_base[len(scheme_prefix) :]+ authority: Final = re.split(r"[/?#]", authority_and_rest, maxsplit=1)[0]+ after_authority: Final = authority_and_rest[len(authority) :]+ host: Final = authority.rpartition("@")[2]+ if "@" in after_authority and _HOST_WITH_OPTIONAL_PORT.fullmatch(host) is None:+ return ""+ path: Final = re.split(r"[?#]", after_authority, maxsplit=1)[0]+ return f"{scheme_prefix}{host}{path}"++def _is_guardrail_block(original_exception: Exception) -> bool:from litellm.integrations.custom_guardrail import is_guardrail_intervention@@ -2483,8 +2512,9 @@ def exception_type(if isinstance(custom_llm_provider, str) and len(custom_llm_provider) > 0:exception_provider = custom_llm_provider[0].upper() + custom_llm_provider[1:] + "Exception"- if _api_base:- extra_information += f"\nAPI Base: `{_api_base}`"+ shown_api_base: Final = _api_base_without_credentials(_api_base) if _api_base else ""+ if shown_api_base:+ extra_information += f"\nAPI Base: `{shown_api_base}`"if messages and len(messages) > 0 and litellm.redact_messages_in_exceptions is False:extra_information += f"\nMessages: `{messages}`"diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 78fb82c98e7..78cfb58bedf 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -47,7 +47,7 @@ from litellm.types.utils import GenericStreamingChunk as GChunkfrom ..exceptions import OpenAIErrorfrom .core_helpers import map_finish_reason, process_response_headers-from .exception_mapping_utils import exception_type+from .exception_mapping_utils import exception_type, with_deployment_api_basefrom .llm_response_utils.get_api_base import get_api_basefrom .rules import Rules@@ -1579,11 +1579,7 @@ class CustomStreamWrapper:except Exception as e:traceback.format_exc()setattr(e, "message", str(e))- raise exception_type(- model=self.model,- custom_llm_provider=self.custom_llm_provider,- original_exception=e,- )+ raise self._map_stream_exception(e)def set_logging_event_loop(self, loop):"""@@ -2370,6 +2366,14 @@ class CustomStreamWrapper:if not self._emitted_disqualifying_content and self._delta_disqualifies_continuation(delta):self._emitted_disqualifying_content = True+ def _map_stream_exception(self, original_exception: Exception) -> Exception:+ return exception_type(+ model=self.model,+ custom_llm_provider=self.custom_llm_provider,+ original_exception=original_exception,+ extra_kwargs=with_deployment_api_base(self.logging_obj.model_call_details.get("litellm_params")),+ )+def _handle_stream_fallback_error(self, e: Exception) -> "NoReturn":"""Common error handling for both __next__ and __anext__.@@ -2414,13 +2418,7 @@ class CustomStreamWrapper:mapped_exception: Exception = eelse:try:- mapped_exception = exception_type(- model=self.model,- custom_llm_provider=self.custom_llm_provider,- original_exception=e,- completion_kwargs={},- extra_kwargs={},- )+ mapped_exception = self._map_stream_exception(e)except Exception as mapping_error:mapped_exception = mapping_errorself._restore_consumer_correlation_context()diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.pyindex 89c32aed1fb..5897b0ac954 100644--- a/litellm/responses/streaming_iterator.py+++ b/litellm/responses/streaming_iterator.py@@ -28,6 +28,7 @@ from litellm.constants import (from litellm.exceptions import MidStreamFallbackError, RateLimitErrorfrom litellm.litellm_core_utils.asyncify import run_async_functionfrom litellm.litellm_core_utils.core_helpers import process_response_headers+from litellm.litellm_core_utils.exception_mapping_utils import with_deployment_api_basefrom litellm.litellm_core_utils.internal_call_metadata import without_budget_reservationfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.litellm_core_utils.llm_response_utils.get_api_base import get_api_base@@ -264,7 +265,11 @@ def stream_error_status_and_message(error_obj: object) -> tuple[int, str]:def _map_stream_error_to_exception(- error_obj: object, model: str, custom_llm_provider: str, headers: httpx.Headers | None = None+ error_obj: object,+ model: str,+ custom_llm_provider: str,+ headers: httpx.Headers | None = None,+ logging_obj: LiteLLMLoggingObj | None = None,) -> Exception:from litellm.llms.base_llm.chat.transformation import BaseLLMException@@ -277,13 +282,18 @@ def _map_stream_error_to_exception(body=error_body,headers=headers,)+ litellm_params: Final = (+ None+ if logging_obj is None+ else _typed_gets_litellm_params(logging_obj.model_call_details.get)("litellm_params", {})+ )try:return litellm.exception_type(model=model,custom_llm_provider=custom_llm_provider,original_exception=provider_exception,completion_kwargs={},- extra_kwargs={},+ extra_kwargs=with_deployment_api_base(litellm_params),)except Exception as mapped_exception:return mapped_exception@@ -676,6 +686,7 @@ class BaseResponsesAPIStreamingIterator:self.model or "",self.custom_llm_provider or "",headers=provider_request_id_headers(self._raw_response_headers),+ logging_obj=self.logging_obj,)def _maybe_raise_for_error_event(self, result: object) -> None:@@ -1983,13 +1994,17 @@ class _ResponsesWsTurn:def with_event(self, event: Mapping[str, object]) -> _ResponsesWsTurn:return _ResponsesWsTurn(logging_obj=self.logging_obj, events=(*self.events, event))- def failure(self, model: str, custom_llm_provider: str) -> Exception | None:+ def failure(+ self, model: str, custom_llm_provider: str, connection_logging_obj: LiteLLMLoggingObj+ ) -> Exception | None:failed_event: Final = next((event for event in self.events if event.get("type") in _RESPONSES_WS_FAILURE_EVENT_TYPES), None)if failed_event is None:return None- return _map_stream_error_to_exception(_ws_event_error(failed_event), model, custom_llm_provider)+ return _map_stream_error_to_exception(+ _ws_event_error(failed_event), model, custom_llm_provider, logging_obj=connection_logging_obj+ )_RESPONSES_WS_OUTPUT_ITEM_EVENT_TYPES: Final = frozenset({"response.output_item.added", "response.output_item.done"})@@ -2148,7 +2163,7 @@ class ResponsesWebSocketStreaming:def _log_turn(self, turn: _ResponsesWsTurn) -> None:events: Final = list(turn.events)- exception: Final = turn.failure(self.authorized_model or "", self.custom_llm_provider or "")+ exception: Final = turn.failure(self.authorized_model or "", self.custom_llm_provider or "", self.logging_obj)if exception is None:asyncio.create_task(turn.logging_obj.dispatch_success_handlers(events, prefer_async_handlers=True))returndiff --git a/tests/integration/observability/test_stream_error_alert_api_base.py b/tests/integration/observability/test_stream_error_alert_api_base.pynew file mode 100644index 00000000000..449e378dfc7--- /dev/null+++ b/tests/integration/observability/test_stream_error_alert_api_base.py@@ -0,0 +1,482 @@+import asyncio+import hashlib+import json+import uuid+from collections.abc import Callable, Iterable, Iterator, Mapping+from dataclasses import dataclass+from pathlib import Path+from types import MappingProxyType+from typing import Final++import anthropic+import openai+import pytest+import yaml+from anthropic.types import RawContentBlockDeltaEvent, TextDelta+from integration._support.anthropic_sse import DROP_PAUSE, dropping_reply, stream_reply+from integration._support.client import (+ JSON_OBJECT,+ Gateway,+ Scenario,+ eventually,+ gateway_from_environment,+ object_value,+ string_value,+)+from integration._support.database import read_rows+from integration._support.process import graceful_stop_seconds, owned_proxy+from integration._support.responses_stream import created, delta, failed, frame+from integration._support.responses_ws_peer import PROVIDER_MODEL, Script, events, responses_peer, session+from integration._support.tls import write_self_signed_cert+from integration._support.vertex import service_account_json+from integration._support.wire import Reply, Request, Wire, wire_server+from openai.types.chat import ChatCompletionChunk+from openai.types.responses import ResponseFailedEvent, ResponseTextDeltaEvent+from pydantic import JsonValue++pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)++AZURE_KEY: Final = "synthetic-azure-key"+API_VERSION: Final = "2025-04-01-preview"+AZURE_CHAT_BACKEND: Final = "azure/gpt-4o-mini"+PARTIAL_TEXT: Final = "partial answer"+ALERT_SECONDS: Final = 40+NO_RETRY_NO_CACHE: Final[Mapping[str, JsonValue]] = MappingProxyType({"num_retries": 0, "cache": {"no-cache": True}})+EMPTY_MODEL_LIST: Final = Reply(body=b'{"object": "list", "data": []}')+VERTEX_PROJECT: Final = "alert-vertex-project"+VERTEX_LOCATION: Final = "us-east5"+VERTEX_PARTNER_BACKEND: Final = "claude-opus-5-5@default"+VERTEX_PARTNER_URL: Final = (+ f"https://{VERTEX_LOCATION}-aiplatform.googleapis.com/v1/projects/{VERTEX_PROJECT}"+ f"/locations/{VERTEX_LOCATION}/publishers/anthropic/models/{VERTEX_PARTNER_BACKEND}"+)+VERTEX_OVERLOADED: Final = Reply(+ status=500, body=b'{"error": {"code": 500, "message": "vertex partner overloaded", "status": "INTERNAL"}}'+)++API_BASES: Final[Mapping[str, Callable[[str, str], str]]] = MappingProxyType(+ {+ "plain": lambda url, _: f"{url}/gateway",+ "code": lambda url, secret: f"{url}/gateway?code={secret}",+ "subscription-key": lambda url, secret: f"{url}/gateway?subscription-key={secret}",+ "userinfo": lambda url, secret: url.replace("://", f"://alice:{secret}@", 1) + "/gateway",+ }+)+++@dataclass(frozen=True, slots=True)+class AlertingProxy:+ gateway: Gateway+ alerts: Wire+ vertex: Wire+ cert: tuple[Path, Path]+++@dataclass(frozen=True, slots=True)+class Caller:+ key: str+ key_alias: str+ team_alias: str+++@dataclass(frozen=True, slots=True)+class Outcome:+ text: str+ failure: str+++def accept_alert(request: Request) -> Reply:+ return Reply(body=b"ok", content_type="text/plain")+++def overloaded_vertex(request: Request) -> Reply:+ return VERTEX_OVERLOADED+++def alerting_config(directory: Path) -> Path:+ base: Final = JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))+ config: Final = {+ **base,+ "general_settings": {+ **object_value(base["general_settings"]),+ "alerting": ["slack"],+ "alert_types": ["llm_exceptions"],+ },+ }+ path: Final = directory / "alerting.yaml"+ path.write_text(yaml.safe_dump(config))+ return path++[email protected](scope="module")+def alerting(tmp_path_factory: pytest.TempPathFactory) -> Iterator[AlertingProxy]:+ directory: Final = tmp_path_factory.mktemp("stream-error-alerts")+ cert: Final = write_self_signed_cert(directory)+ with (+ gateway_from_environment() as shared,+ wire_server(accept_alert) as alerts,+ wire_server(overloaded_vertex) as vertex,+ ):+ with owned_proxy(+ shared,+ directory,+ {+ "SLACK_WEBHOOK_URL": alerts.url,+ "DEFAULT_FLUSH_INTERVAL_SECONDS": "1",+ "SSL_CERT_FILE": str(cert[0]),+ "VERTEXAI_API_BASE": vertex.url,+ },+ config=alerting_config(directory),+ ) as gateway:+ yield AlertingProxy(gateway, alerts, vertex, cert)+++def alert_naming(alerts: Wire, marker: str) -> str:+ def matching() -> tuple[str, ...]:+ texts: Final = (string_value(JSON_OBJECT.validate_json(request.body)["text"]) for request in alerts.drain())+ return tuple(text for text in texts if marker in text)++ return eventually(matching, lambda found: len(found) > 0, seconds=ALERT_SECONDS)[0]+++def api_base_line(alert: str) -> str | None:+ return next((line for line in alert.splitlines() if line.startswith("API Base:")), None)+++def assert_names_deployment(alert: str, api_base: str, model_group: str, backend: str, caller: Caller) -> None:+ assert api_base_line(alert) == f"API Base: `{api_base}`", alert+ assert f"model_group: `{model_group}`" in alert, alert+ assert f"deployment: `{backend}`" in alert, alert+ assert f"Key Name: `{caller.key_alias}`\nTeam: `{caller.team_alias}`" in alert, alert+++def keyed_caller(scenario: Scenario) -> Caller:+ team_alias: Final = f"alert-team-{uuid.uuid4().hex[:12]}"+ key_alias: Final = f"alert-key-{uuid.uuid4().hex[:12]}"+ team: Final = scenario.team(team_alias=team_alias)+ return Caller(scenario.key(key_alias=key_alias, team_id=team), key_alias, team_alias)+++def azure_chat(scenario: Scenario, api_base: str, *, bridged: bool = False) -> str:+ return scenario.model(+ model=AZURE_CHAT_BACKEND,+ api_base=api_base,+ api_key=AZURE_KEY,+ api_version=API_VERSION,+ num_retries=0,+ use_chat_completions_api=bridged,+ )+++def provider_message(marker: str) -> str:+ return f"upstream overloaded {marker}"+++def chat_chunk(marker: str, content: Mapping[str, JsonValue]) -> bytes:+ body: Final = {+ "id": f"chatcmpl-{marker}",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": f"gpt-4o-mini-{marker}",+ "choices": [{"index": 0, "delta": dict(content), "finish_reason": None}],+ }+ return b"data: " + json.dumps(body).encode() + b"\n\n"+++def first_text(marker: str) -> bytes:+ return chat_chunk(marker, {"role": "assistant", "content": PARTIAL_TEXT})+++def cut_after_text(marker: str) -> Reply:+ return dropping_reply((first_text(marker), chat_chunk(marker, {"content": " never sent"})), abort_after=1)+++def error_frame_after_text(marker: str) -> Reply:+ error: Final = {"error": {"message": provider_message(marker), "type": "server_error", "code": "server_error"}}+ return stream_reply((first_text(marker), b"data: " + json.dumps(error).encode() + b"\n\n"), pause=DROP_PAUSE)+++def rejected_before_stream(marker: str) -> Reply:+ return Reply(+ status=500, body=json.dumps({"error": {"message": provider_message(marker), "type": "server_error"}}).encode()+ )+++def chat_upstream(reply: Callable[[str], Reply], marker: str) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ if request.method != "POST":+ return EMPTY_MODEL_LIST+ return reply(marker)++ return respond+++def items_or_error(open_stream: Callable[[], Iterable[object]], error_type: type[Exception]) -> Iterator[object]:+ try:+ yield from open_stream()+ except error_type as error:+ yield error+++def chunk_text(item: object) -> str:+ if not isinstance(item, ChatCompletionChunk):+ return ""+ return "".join(choice.delta.content or "" for choice in item.choices)+++def message_text(item: object) -> str:+ if isinstance(item, RawContentBlockDeltaEvent) and isinstance(item.delta, TextDelta):+ return item.delta.text+ return ""+++def responses_text(item: object) -> str:+ return item.delta if isinstance(item, ResponseTextDeltaEvent) else ""+++def failure_of(item: object) -> str:+ if isinstance(item, Exception):+ return str(item)+ if isinstance(item, ResponseFailedEvent) and item.response.error is not None:+ return item.response.error.message+ return ""+++def outcome(items: tuple[object, ...], text_of: Callable[[object], str]) -> Outcome:+ return Outcome("".join(text_of(item) for item in items), "".join(failure_of(item) for item in items))+++def openai_client(gateway: Gateway, key: str) -> openai.OpenAI:+ return openai.OpenAI(base_url=f"{gateway.client.base_url}/v1", api_key=key, max_retries=0, timeout=60)+++def chat_outcome(gateway: Gateway, key: str, model: str) -> Outcome:+ with openai_client(gateway, key) as client:+ items: Final = tuple(+ items_or_error(+ lambda: client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": "stream an answer"}],+ stream=True,+ extra_body=dict(NO_RETRY_NO_CACHE),+ ),+ openai.APIError,+ )+ )+ return outcome(items, chunk_text)+++def messages_outcome(gateway: Gateway, key: str, model: str) -> Outcome:+ with anthropic.Anthropic(base_url=str(gateway.client.base_url), api_key=key, max_retries=0, timeout=60) as client:+ items: Final = tuple(+ items_or_error(+ lambda: client.messages.create(+ model=model,+ max_tokens=64,+ messages=[{"role": "user", "content": "stream an answer"}],+ stream=True,+ extra_body=dict(NO_RETRY_NO_CACHE),+ ),+ anthropic.APIError,+ )+ )+ return outcome(items, message_text)+++def responses_outcome(gateway: Gateway, key: str, model: str) -> Outcome:+ with openai_client(gateway, key) as client:+ items: Final = tuple(+ items_or_error(+ lambda: client.responses.create(+ model=model, input="stream an answer", stream=True, extra_body=dict(NO_RETRY_NO_CACHE)+ ),+ openai.APIError,+ )+ )+ return outcome(items, responses_text)+++ENTRYPOINTS: Final[Mapping[str, Callable[[Gateway, str, str], Outcome]]] = MappingProxyType(+ {"chat": chat_outcome, "messages": messages_outcome, "responses-bridge": responses_outcome}+)+FAILURES: Final[Mapping[str, Callable[[str], Reply]]] = MappingProxyType(+ {"cut": cut_after_text, "error-frame": error_frame_after_text}+)+++ ("entrypoint", "failure"),+ [("chat", "cut"), ("chat", "error-frame"), ("messages", "error-frame"), ("responses-bridge", "error-frame")],+)+def test_mid_stream_failure_alert_names_the_deployment(alerting: AlertingProxy, entrypoint: str, failure: str) -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(chat_upstream(FAILURES[failure], marker)) as wire, alerting.gateway.scenario() as scenario:+ model: Final = azure_chat(scenario, wire.url, bridged=entrypoint == "responses-bridge")+ caller: Final = keyed_caller(scenario)+ seen: Final = ENTRYPOINTS[entrypoint](alerting.gateway, caller.key, model)+ assert seen.text == PARTIAL_TEXT and seen.failure, seen+ assert failure == "cut" or provider_message(marker) in seen.failure, seen+ assert_names_deployment(alert_naming(alerting.alerts, marker), wire.url, model, AZURE_CHAT_BACKEND, caller)+++def test_native_responses_failed_event_alert_names_the_deployment(alerting: AlertingProxy) -> None:+ marker: Final = uuid.uuid4().hex+ identity: Final = f"resp_{marker}"+ stream: Final = (+ frame(created(identity)),+ frame(delta(identity, PARTIAL_TEXT)),+ frame(failed(identity, "server_error", provider_message(marker))),+ )++ def respond(request: Request) -> Reply:+ if request.method != "POST":+ return EMPTY_MODEL_LIST+ assert "/responses" in request.target, request.target+ return stream_reply(stream)++ with wire_server(respond) as wire, alerting.gateway.scenario() as scenario:+ model: Final = scenario.model(model=AZURE_CHAT_BACKEND, api_base=wire.url, api_key=AZURE_KEY, num_retries=0)+ caller: Final = keyed_caller(scenario)+ seen: Final = responses_outcome(alerting.gateway, caller.key, model)+ assert seen.text == PARTIAL_TEXT and provider_message(marker) in seen.failure, seen+ assert_names_deployment(alert_naming(alerting.alerts, marker), wire.url, model, AZURE_CHAT_BACKEND, caller)+++def failing_turn(marker: str) -> Script:+ def script(+ response_id: str,+ ) -> tuple[dict[str, JsonValue], ...]: # mutable-ok: responses_peer's Script returns dicts+ opened, text_delta, completed_event = events(response_id, PARTIAL_TEXT)+ response: Final = object_value(completed_event["response"])+ return (+ opened,+ text_delta,+ {+ "type": "response.failed",+ "response": {+ **response,+ "status": "failed",+ "output": [],+ "error": {"code": "server_error", "message": provider_message(marker)},+ },+ },+ )++ return script+++def test_responses_websocket_turn_failure_alert_names_the_deployment(alerting: AlertingProxy) -> None:+ marker: Final = uuid.uuid4().hex+ backend: Final = f"openai/{PROVIDER_MODEL}"+ with responses_peer(alerting.cert, failing_turn(marker)) as peer, alerting.gateway.scenario() as scenario:+ model: Final = scenario.model(model=backend, api_base=peer.url, num_retries=0)+ caller: Final = keyed_caller(scenario)+ (received,) = asyncio.run(session(str(alerting.gateway.client.base_url), caller.key, model, (marker,)))+ assert [event["type"] for event in received] == [+ "response.created",+ "response.output_text.delta",+ "response.failed",+ ], received+ assert_names_deployment(alert_naming(alerting.alerts, marker), peer.url, model, backend, caller)+ (row,) = eventually(+ lambda: read_rows(+ 'SELECT status, metadata FROM "LiteLLM_SpendLogs" WHERE api_key = %s',+ (hashlib.sha256(caller.key.encode()).hexdigest(),),+ ),+ lambda rows: len(rows) >= 1,+ seconds=70,+ )+ assert row["status"] == "failure", row+ error_information: Final = object_value(object_value(row["metadata"])["error_information"])+ assert provider_message(marker) in string_value(error_information["error_message"]), error_information+++ ("phase", "placement"),+ [+ ("pre-stream", "plain"),+ ("pre-stream", "code"),+ ("pre-stream", "subscription-key"),+ ("pre-stream", "userinfo"),+ ("mid-stream", "code"),+ ],+)+def test_alert_api_base_line_keeps_credentials_out(alerting: AlertingProxy, phase: str, placement: str) -> None:+ marker: Final = uuid.uuid4().hex+ secret: Final = f"credential{uuid.uuid4().hex}"+ pre_stream: Final = phase == "pre-stream"+ reply: Final = rejected_before_stream if pre_stream else error_frame_after_text+ with wire_server(chat_upstream(reply, marker)) as wire, alerting.gateway.scenario() as scenario:+ model: Final = azure_chat(scenario, API_BASES[placement](wire.url, secret))+ caller: Final = keyed_caller(scenario)+ seen: Final = chat_outcome(alerting.gateway, caller.key, model)+ assert seen.failure and seen.text == ("" if pre_stream else PARTIAL_TEXT), seen+ alert: Final = alert_naming(alerting.alerts, model if pre_stream else marker)+ assert secret not in alert, alert+ assert_names_deployment(alert, f"{wire.url}/gateway", model, AZURE_CHAT_BACKEND, caller)+++def test_alert_api_base_line_keeps_a_malformed_password_out(alerting: AlertingProxy) -> None:+ password_start: Final = f"credential{uuid.uuid4().hex[:8]}"+ password_end: Final = uuid.uuid4().hex+ with alerting.gateway.scenario() as scenario:+ model: Final = azure_chat(scenario, f"http://alice:{password_start}?{password_end}@127.0.0.1:9/gateway")+ caller: Final = keyed_caller(scenario)+ seen: Final = chat_outcome(alerting.gateway, caller.key, model)+ assert seen.failure and not seen.text, seen+ line: Final = api_base_line(alert_naming(alerting.alerts, model)) or ""+ assert not any(part in line for part in ("alice", password_start, password_end)), line+++def test_alert_api_base_line_names_a_vertex_partner_model_version(alerting: AlertingProxy) -> None:+ with alerting.gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"vertex_ai/{VERTEX_PARTNER_BACKEND}",+ api_base=None,+ api_key=None,+ vertex_project=VERTEX_PROJECT,+ vertex_location=VERTEX_LOCATION,+ vertex_credentials=service_account_json(VERTEX_PROJECT, alerting.gateway.upstream_url.rstrip("/")),+ num_retries=0,+ )+ caller: Final = keyed_caller(scenario)+ seen: Final = chat_outcome(alerting.gateway, caller.key, model)+ assert seen.failure and not seen.text, seen+ assert any(+ f"/publishers/anthropic/models/{VERTEX_PARTNER_BACKEND}:" in request.target+ for request in alerting.vertex.drain()+ )+ line: Final = api_base_line(alert_naming(alerting.alerts, model)) or ""+ assert line.startswith(f"API Base: `{VERTEX_PARTNER_URL}:"), line+++def test_fallback_mid_stream_failure_alert_names_the_fallback_deployment(alerting: AlertingProxy) -> None:+ marker: Final = uuid.uuid4().hex+ primary_reply: Final = Reply(status=500, body=b'{"error": {"message": "primary is down", "type": "server_error"}}')+ with (+ wire_server(chat_upstream(lambda _: primary_reply, marker)) as primary_wire,+ wire_server(chat_upstream(cut_after_text, marker)) as backup_wire,+ alerting.gateway.scenario() as scenario,+ ):+ primary: Final = azure_chat(scenario, primary_wire.url)+ backup: Final = azure_chat(scenario, backup_wire.url)+ caller: Final = keyed_caller(scenario)+ with openai_client(alerting.gateway, caller.key) as client:+ items: Final = tuple(+ items_or_error(+ lambda: client.chat.completions.create(+ model=primary,+ messages=[{"role": "user", "content": "stream an answer"}],+ stream=True,+ extra_body={**NO_RETRY_NO_CACHE, "fallbacks": [backup]},+ ),+ openai.APIError,+ )+ )+ seen: Final = outcome(items, chunk_text)+ assert seen.text == PARTIAL_TEXT and seen.failure, seen+ assert [request.method for request in primary_wire.drain()].count("POST") == 1+ assert [request.method for request in backup_wire.drain()].count("POST") == 1+ alert: Final = alert_naming(alerting.alerts, marker)+ assert_names_deployment(alert, backup_wire.url, backup, AZURE_CHAT_BACKEND, caller)+ assert primary_wire.url not in alert, alertdiff --git a/tests/integration/sdk/test_stream_error_api_base_sdk.py b/tests/integration/sdk/test_stream_error_api_base_sdk.pynew file mode 100644index 00000000000..922e518c7bf--- /dev/null+++ b/tests/integration/sdk/test_stream_error_api_base_sdk.py@@ -0,0 +1,69 @@+import json+from collections.abc import AsyncIterable, AsyncIterator+from typing import Final++import openai+from integration._support.anthropic_sse import dropping_reply+from integration._support.wire import Reply, Request, wire_server++import litellm+from litellm.exceptions import MidStreamFallbackError++_PARTIAL_TEXT: Final = "partial answer"+++def _chunk(content: str) -> bytes:+ body: Final = {+ "id": "chatcmpl-sdk-cut",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "gpt-4o-mini",+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": content}, "finish_reason": None}],+ }+ return b"data: " + json.dumps(body).encode() + b"\n\n"+++def _cut_after_text(request: Request) -> Reply:+ assert request.method == "POST" and "/chat/completions" in request.target, request.target+ return dropping_reply((_chunk(_PARTIAL_TEXT), _chunk(" never sent")), abort_after=1)+++def _text(item: object) -> str:+ if not isinstance(item, litellm.ModelResponseStream):+ return ""+ return "".join(choice.delta.content or "" for choice in item.choices)+++async def _items_or_error(stream: AsyncIterable[object]) -> AsyncIterator[object]:+ try:+ async for item in stream:+ yield item+ except openai.APIError as error:+ yield error+++async def test_sdk_mid_stream_failure_debug_info_names_the_api_base_it_called() -> None:+ with wire_server(_cut_after_text) as wire:+ response: Final = await litellm.acompletion(+ model="azure/gpt-4o-mini",+ api_base=wire.url,+ api_key="synthetic-azure-key",+ api_version="2025-04-01-preview",+ messages=[{"role": "user", "content": "stream an answer"}],+ stream=True,+ num_retries=0,+ )+ assert isinstance(response, AsyncIterable), response+ items: Final = [item async for item in _items_or_error(response)]+ errors: Final = [item for item in items if isinstance(item, openai.APIError)]+ assert len(errors) == 1 and items[-1] is errors[0], items+ assert "".join(_text(item) for item in items) == _PARTIAL_TEXT, items+ error: Final = errors[0]+ mapped: Final = (+ error.original_exception+ if isinstance(error, MidStreamFallbackError) and error.original_exception is not None+ else error+ )+ debug_info: Final = getattr(mapped, "litellm_debug_info", None)+ assert isinstance(debug_info, str), mapped+ assert f"\nAPI Base: `{wire.url}`" in debug_info, debug_infodiff --git a/tests/unit/litellm_core_utils/test_exception_mapping_utils.py b/tests/unit/litellm_core_utils/test_exception_mapping_utils.pyindex b24348cfaa8..9eb99516e02 100644--- a/tests/unit/litellm_core_utils/test_exception_mapping_utils.py+++ b/tests/unit/litellm_core_utils/test_exception_mapping_utils.py@@ -57,6 +57,104 @@ def test_openai_cyber_policy_uses_the_structured_error_code(shape: str, code: stassert caught.value.response.headers["x-request-id"] == "cyber-policy-request"++def _debug_info_for_api_base(configured_api_base: str) -> str:+ request: Final = httpx.Request("POST", "https://gateway.example/v1/chat/completions")+ original: Final = OpenAIError(+ status_code=500, message="upstream failed", request=request, response=httpx.Response(500, request=request)+ )+ with pytest.raises(litellm.InternalServerError) as caught:+ exception_type(+ model="gpt-5.4-mini",+ original_exception=original,+ custom_llm_provider="openai",+ completion_kwargs={},+ extra_kwargs={"api_base": configured_api_base},+ )+ debug_info: Final = caught.value.litellm_debug_info+ assert isinstance(debug_info, str)+ return debug_info+++ ("configured_api_base", "shown_api_base"),+ [+ ("https://qa-user:[email protected]/v1?code=function-secret", "https://gateway.example/v1"),+ ("https://gateway.example/v1#function-secret", "https://gateway.example/v1"),+ ("qa-user:[email protected]:8080/v1", "gateway.example:8080/v1"),+ ("https://gateway.example?code=function/secret", "https://gateway.example"),+ ("https://[email protected]&code=function-secret", "https://gateway.example"),+ ("https://[email protected]", "https://gateway.example"),+ ("qa-user:[email protected]/v1?next=https://other.example/y", "gateway.example/v1"),+ (+ "https://qa-user:[email protected]/models/claude-opus-5-5@default",+ "https://gateway.example/models/claude-opus-5-5@default",+ ),+ ],+ ids=[+ "userinfo_and_query",+ "fragment",+ "no_scheme",+ "slash_in_query_without_path",+ "at_sign_in_query_without_path",+ "at_sign_names_other_host",+ "no_scheme_with_url_in_query",+ "userinfo_and_at_sign_in_path",+ ],+)+def test_api_base_line_keeps_credentials_out(configured_api_base: str, shown_api_base: str) -> None:+ debug_info: Final = _debug_info_for_api_base(configured_api_base)+ assert f"API Base: `{shown_api_base}`" in debug_info+ assert "function-secret" not in debug_info+ assert "secret" not in debug_info.split("API Base:", 1)[1].split("\n", 1)[0]+++ "configured_api_base",+ [+ "https://qa-user:[email protected]/v1",+ "https://qa-user:qa#[email protected]/v1",+ "https://qa-user:qa/[email protected]/v1",+ "https://qa-user:qa/[email protected]/v1",+ "https://qa.user:qa/[email protected]/v1",+ "https://qa-user:1234/[email protected]/v1",+ "https://function-secret/[email protected]/v1",+ "qa-user:qa://[email protected]",+ ],+ ids=[+ "question_mark_in_password",+ "hash_in_password",+ "slash_in_password",+ "slash_and_question_mark_in_password",+ "dotted_username_and_slash_in_password",+ "numeric_password_with_slash",+ "slash_in_username",+ "no_scheme_with_scheme_separator_in_password",+ ],+)+def test_api_base_line_is_left_out_when_a_password_breaks_the_url(configured_api_base: str) -> None:+ debug_info: Final = _debug_info_for_api_base(configured_api_base)+ assert "API Base:" not in debug_info+ assert not any(part in debug_info for part in ("qa-user", "qa.user", "function", "secret"))+++ "api_base",+ [+ "https://us-east5-aiplatform.googleapis.com/v1/projects/p/locations/us-east5"+ "/publishers/anthropic/models/claude-opus-5-5@default:rawPredict",+ "us-central1-aiplatform.googleapis.com/v1/projects/p/locations/us-central1"+ "/publishers/mistralai/models/mistral-large@2407:rawPredict",+ "https://gateway.ai.cloudflare.com/v1/account/gateway/workers-ai/@cf/meta/llama-3.1-8b-instruct",+ "http://localhost:4000/v1/models/claude@default",+ "https://[::1]:8080/v1/models/claude@default",+ ],+ ids=["vertex_partner_model", "vertex_without_scheme", "workers_ai_path", "localhost", "ipv6"],+)+def test_api_base_line_keeps_an_at_sign_in_the_path(api_base: str) -> None:+ assert f"API Base: `{api_base}`" in _debug_info_for_api_base(api_base)++# Test cases for is_error_str_context_window_exceeded# Tuple format: (error_message, expected_result)context_window_test_cases = [diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.pyindex 93f700b1c2a..c07fe2d1c31 100644--- a/tests/unit/litellm_core_utils/test_streaming_handler.py+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py@@ -2,14 +2,17 @@ import asyncioimport jsonimport threadingimport time-from typing import Final, NoReturn, Optional+from typing import AsyncIterator, Final, Iterator, Literal, NoReturn, Optionalfrom unittest.mock import AsyncMock, MagicMock, Mock, patch+import httpximport pytestimport litellmfrom litellm import verbose_loggerfrom litellm._logging import session_id_var, trace_id_var+from litellm.exceptions import MidStreamFallbackError+from litellm.litellm_core_utils.get_litellm_params import get_litellm_paramsfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.litellm_core_utils.streaming_handler import (CustomStreamWrapper,@@ -1382,6 +1385,140 @@ async def test_async_streaming_read_timeout_triggers_midstream_fallback(assert isinstance(excinfo.value.original_exception, Exception)+_AZURE_DEPLOYMENT_API_BASE: Final = "https://mid-stream-debug.openai.azure.com"+_AZURE_DEPLOYMENT_REQUEST_URL: Final = (+ f"{_AZURE_DEPLOYMENT_API_BASE}/openai/deployments/gpt-5.4-mini/chat/completions?api-version=2025-04-01-preview"+)+_MID_STREAM_START_TIME: Final = 1_790_000_000.0+++def _azure_deployment_logging_obj(logged_api_base: str | None, routed_api_base: str | None) -> Logging:+ logging_obj: Final = Logging(+ model="gpt-5.4-mini",+ messages=[{"role": "user", "content": "Count from 1 to 40"}],+ stream=True,+ call_type="acompletion",+ start_time=_MID_STREAM_START_TIME,+ litellm_call_id="mid-stream-debug-info",+ function_id="mid-stream-debug-info",+ )+ logging_obj.update_environment_variables(+ model="gpt-5.4-mini",+ optional_params={},+ litellm_params=get_litellm_params(+ api_base=logged_api_base,+ custom_llm_provider="azure",+ metadata={+ "model_group": "gpt-5.4-mini-azure",+ "deployment": "azure/gpt-5.4-mini",+ "api_base": routed_api_base,+ },+ ),+ )+ return logging_obj+++def _content_then_failure(failure: Literal["transport_error", "unparseable_chunk"]) -> Iterator[object]:+ yield ModelResponseStream(+ model="gpt-5.4-mini-2026-03-17",+ choices=[StreamingChoices(index=0, delta=Delta(content="1", role="assistant"))],+ )+ if failure == "transport_error":+ raise httpx.ReadError("Response payload is not completed")+ yield object()+++async def _as_async(chunks: Iterator[object]) -> AsyncIterator[object]:+ for chunk in chunks:+ yield chunk+++async def _drain(wrapper: CustomStreamWrapper, sync_mode: bool) -> None:+ if sync_mode:+ for _ in wrapper:+ pass+ return+ async for _ in wrapper:+ pass+++async def _mid_stream_debug_info(+ logged_api_base: str | None,+ routed_api_base: str | None,+ failure: Literal["transport_error", "unparseable_chunk"],+ sync_mode: bool,+) -> str:+ chunks: Final = _content_then_failure(failure)+ wrapper: Final = CustomStreamWrapper(+ completion_stream=chunks if sync_mode else _as_async(chunks),+ model="gpt-5.4-mini-2026-03-17",+ logging_obj=_azure_deployment_logging_obj(logged_api_base, routed_api_base),+ custom_llm_provider="azure",+ )+ with pytest.raises(MidStreamFallbackError) as excinfo:+ await _drain(wrapper, sync_mode)+ assert excinfo.value.is_pre_first_chunk is False+ debug_info: Final = getattr(excinfo.value.original_exception, "litellm_debug_info", None)+ assert isinstance(debug_info, str)+ return debug_info++[email protected]("sync_mode", [True, False])[email protected]("failure", ["transport_error", "unparseable_chunk"])+ ("logged_api_base", "routed_api_base"),+ [+ (_AZURE_DEPLOYMENT_REQUEST_URL, _AZURE_DEPLOYMENT_API_BASE),+ (_AZURE_DEPLOYMENT_API_BASE, None),+ (_AZURE_DEPLOYMENT_API_BASE, ""),+ ],+ ids=["routed", "sdk", "empty_routed"],+)+async def test_mid_stream_error_reports_the_deployment_it_was_sent_to(+ logged_api_base: str,+ routed_api_base: str | None,+ failure: Literal["transport_error", "unparseable_chunk"],+ sync_mode: bool,+):+ debug_info: Final = await _mid_stream_debug_info(logged_api_base, routed_api_base, failure, sync_mode)++ assert f"API Base: `{_AZURE_DEPLOYMENT_API_BASE}`" in debug_info+ assert "model_group: `gpt-5.4-mini-azure`" in debug_info+ assert "deployment: `azure/gpt-5.4-mini`" in debug_info+ assert "Count from 1 to 40" not in debug_info+ assert "api.openai.com" not in debug_info+++async def test_mid_stream_error_leaves_out_an_api_base_it_cannot_resolve():+ debug_info: Final = await _mid_stream_debug_info(None, None, "transport_error", sync_mode=False)++ assert "model_group: `gpt-5.4-mini-azure`" in debug_info+ assert "API Base:" not in debug_info++++ "routed_api_base",+ [+ f"{_AZURE_DEPLOYMENT_API_BASE}?subscription-key=deployment-secret-value",+ f"{_AZURE_DEPLOYMENT_API_BASE}?code=deployment-secret-value",+ _AZURE_DEPLOYMENT_API_BASE.replace("https://", "https://qa-user:deployment-secret-value@"),+ ],+ ids=["subscription_key", "function_code", "userinfo"],+)+async def test_mid_stream_error_keeps_credentials_in_the_api_base_out(routed_api_base: str):+ debug_info: Final = await _mid_stream_debug_info(+ _AZURE_DEPLOYMENT_REQUEST_URL, routed_api_base, "transport_error", sync_mode=False+ )++ assert f"API Base: `{_AZURE_DEPLOYMENT_API_BASE}`" in debug_info+ assert "deployment-secret" not in debug_info+++def test_streaming_handler_with_created_time_propagation(initialized_custom_stream_wrapper: CustomStreamWrapper, logging_obj: Logging):diff --git a/tests/unit/responses/test_streaming_iterator_error_events.py b/tests/unit/responses/test_streaming_iterator_error_events.pyindex 001be7e1fbd..04d2b9ddf81 100644--- a/tests/unit/responses/test_streaming_iterator_error_events.py+++ b/tests/unit/responses/test_streaming_iterator_error_events.py@@ -19,6 +19,7 @@ Also covers: ErrorEventError.param must accept dict payloads without raising aPydantic ValidationError (previously typed as Optional[str])."""+import asyncioimport jsonfrom datetime import datetimefrom importlib import import_module@@ -31,15 +32,18 @@ import pytestimport litellmfrom litellm.exceptions import MidStreamFallbackErrorfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.litellm_core_utils.get_litellm_params import get_litellm_paramsfrom litellm.litellm_core_utils.litellm_logging import _get_provider_request_idfrom litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfigfrom litellm.responses.streaming_iterator import (_ERROR_CODE_HTTP_STATUS,BaseResponsesAPIStreamingIterator,ResponsesAPIStreamingIterator,+ ResponsesWebSocketStreaming,SyncResponsesAPIStreamingIterator,_status_code_for_error_fields,)+from litellm.utils import ProviderConfigManagerfrom litellm.types.llms.openai import (ErrorEvent,ErrorEventError,@@ -658,3 +662,140 @@ def test_openai_top_level_error_event_keeps_the_provider_code_and_message(assert exc_info.value.status_code == status_codeassert type(exc_info.value.original_exception) is exception_typeassert f"upstream said {code}" in str(exc_info.value.original_exception)+++_AZURE_RESPONSES_API_BASE: Final = "https://responses-mid-stream.openai.azure.com"+_AZURE_RESPONSES_REQUEST_URL: Final = f"{_AZURE_RESPONSES_API_BASE}/openai/responses?api-version=2025-04-01-preview"+_AZURE_RESPONSES_FAILED_EVENT: Final = {+ "type": "response.failed",+ "sequence_number": 2,+ "response": {+ "id": "resp_mid_stream",+ "object": "response",+ "created_at": 1790000000,+ "status": "failed",+ "model": "gpt-5.4-mini",+ "output": [],+ "error": {"code": "server_error", "message": "upstream failed mid-stream"},+ },+}+_AZURE_RESPONSES_WS_URL: Final = "wss://responses-mid-stream.openai.azure.com/openai/v1/responses?api-version=preview"+++def _azure_responses_logging_obj(logged_api_base: str, routed_api_base: str | None) -> LiteLLMLoggingObj:+ logging_obj: Final = LiteLLMLoggingObj(+ model="gpt-5.4-mini",+ messages=[],+ stream=True,+ call_type="aresponses",+ start_time=datetime(2026, 1, 1),+ litellm_call_id="responses-mid-stream",+ function_id="responses-mid-stream",+ )+ logging_obj.update_environment_variables(+ model="gpt-5.4-mini",+ optional_params={},+ litellm_params=get_litellm_params(+ api_base=logged_api_base,+ custom_llm_provider="azure",+ metadata={+ "model_group": "gpt-5.4-mini-azure",+ "deployment": "azure/gpt-5.4-mini",+ "api_base": routed_api_base,+ },+ ),+ )+ return logging_obj+++def _assert_names_the_azure_deployment(exception: BaseException, api_base: str = _AZURE_RESPONSES_API_BASE) -> None:+ debug_info: Final = getattr(exception, "litellm_debug_info", None)+ assert isinstance(debug_info, str)+ assert f"API Base: `{api_base}`" in debug_info+ assert "model_group: `gpt-5.4-mini-azure`" in debug_info+ assert "deployment: `azure/gpt-5.4-mini`" in debug_info+ assert "api.openai.com" not in debug_info+++async def test_response_failed_after_output_reports_the_deployment_it_was_sent_to():+ delta: Final = {+ "type": "response.output_text.delta",+ "sequence_number": 1,+ "item_id": "msg_mid_stream",+ "output_index": 0,+ "content_index": 0,+ "delta": "1",+ }+ body: Final = "".join(f"data: {json.dumps(event)}\n\n" for event in (delta, _AZURE_RESPONSES_FAILED_EVENT))+ iterator: Final = ResponsesAPIStreamingIterator(+ response=httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body.encode()),+ model="gpt-5.4-mini",+ responses_api_provider_config=ProviderConfigManager.get_provider_responses_api_config(+ provider="azure", model="gpt-5.4-mini"+ ),+ logging_obj=_azure_responses_logging_obj(_AZURE_RESPONSES_REQUEST_URL, _AZURE_RESPONSES_API_BASE),+ custom_llm_provider="azure",+ )+ stream: Final = aiter(iterator)+ assert getattr(await anext(stream), "delta", None) == "1"++ with pytest.raises(MidStreamFallbackError) as exc_info:+ await anext(stream)+ assert exc_info.value.is_pre_first_chunk is False+ _assert_names_the_azure_deployment(exc_info.value.original_exception)+++class _ScriptedAzureSocket:+ def __init__(self, events: tuple[str, ...]) -> None:+ self._events = iter(events)+ self._drained = asyncio.Event()++ async def recv(self, decode: bool = False) -> str:+ event: Final = next(self._events, None)+ if event is None:+ self._drained.set()+ raise ConnectionError("backend closed")+ return event++ async def send(self, message: str) -> None:+ return None++ async def close(self) -> None:+ return None++ async def send_text(self, data: str) -> None:+ return None++ async def receive_text(self) -> str:+ await self._drained.wait()+ raise ConnectionError("client closed")+++ ("routed_api_base", "reported_api_base"),+ [+ (_AZURE_RESPONSES_API_BASE, _AZURE_RESPONSES_API_BASE),+ (None, "wss://responses-mid-stream.openai.azure.com/openai/v1/responses"),+ ],+ ids=["router", "no_router"],+)+async def test_responses_websocket_turn_failure_reports_the_deployment_it_was_sent_to(+ routed_api_base: str | None, reported_api_base: str+):+ connection_logging_obj: Final = _azure_responses_logging_obj(_AZURE_RESPONSES_WS_URL, routed_api_base)+ connection_logging_obj.pre_call(input=None, api_key="", additional_args={"api_base": _AZURE_RESPONSES_WS_URL})+ socket: Final = _ScriptedAzureSocket((json.dumps(_AZURE_RESPONSES_FAILED_EVENT),))+ streaming: Final = ResponsesWebSocketStreaming(+ websocket=socket,+ backend_ws=socket,+ logging_obj=connection_logging_obj,+ authorized_model="gpt-5.4-mini",+ custom_llm_provider="azure",+ )++ failure: Final = await streaming.bidirectional_forward()++ assert failure is not None+ _assert_names_the_azure_deployment(failure, reported_api_base)