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]

chore: merge litellm_internal_staging into the mid-stream failure logging branch

mateo-berrif15bdfb66952
diff --cc litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py
index 34286e2171f,66e36dab2ba..275608fcccc
--- a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py
@@@ -660,25 -671,27 +660,25 @@@ class BaseAnthropicMessagesStreamingIte
self,
queue: "asyncio.Queue[bytes | None | BaseException]",
client_detached: "asyncio.Event",
- collected_chunks: list[bytes], # mutable-ok: SSE buffer forwarded to list-typed _bill_collected_chunks
- exc: BaseException,
+ collected_chunks: Sequence[bytes],
+ exc: Exception,
) -> None:
- """Forward a provider error to a still-connected client, else salvage partial spend.
+ """Forward a provider error to a still-connected client and log the request as failed.
- Handing the original exception to the client-facing generator lets it
- re-raise so the proxy's failure handling keeps the provider status and
- owns logging (no success-bill). If the client already went away, or
- disconnects before ever consuming the queued exception, no failure hook
- runs, so bill the partial instead of dropping the request.
+ The relay re-raises the forwarded exception so the proxy's failure hook
+ keeps the provider status; the logging object's failure handlers fire
+ here either way, carrying the partial usage the provider already
+ billed, so a client that left before consuming the exception still
+ gets a failure row rather than a success one.
"""
- from litellm._logging import verbose_proxy_logger
+ from litellm.proxy.pass_through_endpoints.streaming_handler import PassThroughStreamingHandler
- if not client_detached.is_set() and await self._enqueue_for_client(queue, client_detached, exc):
- await client_detached.wait()
- if not _exception_left_unconsumed(queue, exc):
- return
- verbose_proxy_logger.warning(
- "async_sse_wrapper upstream pump failed after client disconnect (%d chunks): %s(%s)",
- len(collected_chunks),
- type(exc).__name__,
- exc,
+ if not client_detached.is_set():
+ await self._enqueue_for_client(queue, client_detached, exc)
+ PassThroughStreamingHandler.schedule_stream_failure_logging(
+ litellm_logging_obj=self.litellm_logging_obj,
+ endpoint_type=EndpointType.ANTHROPIC,
- request_body=self.request_body or {},
++ request_body=self.request_body,
+ raw_bytes=collected_chunks,
+ exception=exc,
)
- await self._bill_collected_chunks(collected_chunks, stream_teardown=True)
diff --cc litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py
index 4ce840ce6f9,0acc7b1b584..dae52bab956
--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py
+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py
@@@ -148,137 -148,10 +149,138 @@@ class AnthropicPassthroughLoggingHandle
return model_group.removeprefix("passthrough/")
return model
+ @staticmethod
+ def _resolve_logged_model(
+ litellm_logging_obj: LiteLLMLoggingObj,
+ request_body: Mapping[str, object],
+ all_chunks: Sequence[str | bytes],
+ ) -> str:
+ request_model: Final = request_body.get("model")
+ logged_model: Final = (
+ request_model
+ if isinstance(request_model, str) and request_model
+ else str(litellm_logging_obj.model_call_details.get("model") or "")
+ )
+ if logged_model and logged_model != "unknown":
+ return logged_model
+ return AnthropicPassthroughLoggingHandler._extract_model_from_anthropic_chunks(all_chunks) or logged_model
+
+ @staticmethod
+ def _usage_only_response_or_none(
+ all_chunks: Sequence[str | bytes], model: str, speed: str | None
+ ) -> ModelResponse | None:
+ try:
+ return AnthropicPassthroughLoggingHandler._build_usage_only_response_from_chunks(
+ all_chunks=all_chunks, model=model, speed=speed
+ )
- except Exception as e:
++ except Exception as e: # noqa: BLE001 # the usage-only fallback must never raise out of failure logging
+ verbose_proxy_logger.warning("Anthropic passthrough: usage-only fallback failed (model=%s): %s", model, e)
+ return None
+
+ @staticmethod
+ def _assemble_streaming_response(
+ all_chunks: Sequence[str | bytes],
+ litellm_logging_obj: LiteLLMLoggingObj,
+ model: str,
+ speed: str | None,
+ ) -> ModelResponse | TextCompletionResponse | None:
+ try:
+ assembled: Final = AnthropicPassthroughLoggingHandler._build_complete_streaming_response(
+ all_chunks=all_chunks,
+ litellm_logging_obj=litellm_logging_obj,
+ model=model,
+ speed=speed,
+ )
- except Exception as e:
++ except Exception as e: # noqa: BLE001 # any assembly error falls back to usage-only cost
+ verbose_proxy_logger.warning(
+ "Anthropic passthrough: stream assembly raised (model=%s): %s; falling "
+ "back to usage-only cost from raw SSE events.",
+ model,
+ e,
+ )
+ return AnthropicPassthroughLoggingHandler._usage_only_response_or_none(all_chunks, model, speed)
+ if assembled is not None:
+ return assembled
+ return AnthropicPassthroughLoggingHandler._usage_only_response_or_none(all_chunks, model, speed)
+
+ @staticmethod
+ def _build_streaming_response_for_logging(
+ litellm_logging_obj: LiteLLMLoggingObj,
+ request_body: Mapping[str, object],
+ all_chunks: Sequence[str | bytes],
+ model: str,
+ ) -> ModelResponse | TextCompletionResponse | None:
+ response: Final = AnthropicPassthroughLoggingHandler._assemble_streaming_response(
+ all_chunks=all_chunks,
+ litellm_logging_obj=litellm_logging_obj,
+ model=model,
+ speed=AnthropicPassthroughLoggingHandler._cost_relevant_speed(request_body),
+ )
+ if response is None:
+ return None
+ AnthropicPassthroughLoggingHandler._recover_interrupted_stream_output_tokens(
+ response=response, all_chunks=all_chunks, model=model
+ )
+ return response
+
+ @staticmethod
+ def record_partial_usage_for_failure(
+ litellm_logging_obj: LiteLLMLoggingObj,
+ request_body: Mapping[str, object],
+ all_chunks: Sequence[str | bytes],
+ ) -> None:
+ if not all_chunks:
+ return
+ model: Final = AnthropicPassthroughLoggingHandler._resolve_logged_model(
+ litellm_logging_obj, request_body, all_chunks
+ )
+ partial_response: Final = AnthropicPassthroughLoggingHandler._build_streaming_response_for_logging(
+ litellm_logging_obj=litellm_logging_obj, request_body=request_body, all_chunks=all_chunks, model=model
+ )
+ usage: Final = cast(Usage | None, getattr(partial_response, "usage", None))
+ if partial_response is None or usage is None:
+ return
+ try:
+ response_cost: Final = AnthropicPassthroughLoggingHandler._compute_response_cost(
+ litellm_model_response=partial_response,
+ model=AnthropicPassthroughLoggingHandler._resolve_costing_model(model, litellm_logging_obj),
+ logging_obj=litellm_logging_obj,
+ )
- except Exception as e:
++ except Exception as e: # noqa: BLE001 # an uncostable partial stream must still log as a failure
+ verbose_proxy_logger.warning(
+ "Anthropic passthrough: could not cost the partial usage of a failed stream (model=%s): %s", model, e
+ )
+ return
+ litellm_logging_obj.record_partial_usage_for_failure(usage=usage, response_cost=response_cost)
+
+ @staticmethod
+ def _compute_response_cost(
+ litellm_model_response: ModelResponse | TextCompletionResponse,
+ model: str,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> float:
+ if logging_obj.model_call_details.get("cache_hit") is True:
+ return 0.0
+ custom_llm_provider: Final = logging_obj.model_call_details.get("custom_llm_provider")
+ model_for_cost: Final = (
+ f"{custom_llm_provider}/{model}"
+ if custom_llm_provider and not model.startswith(f"{custom_llm_provider}/")
+ else model
+ )
+ return litellm.completion_cost(
+ completion_response=litellm_model_response,
+ model=model_for_cost,
+ custom_llm_provider=custom_llm_provider,
+ custom_pricing=use_custom_pricing_for_model(
+ litellm_params=(logging_obj.litellm_params if hasattr(logging_obj, "litellm_params") else None)
+ ),
+ router_model_id=logging_obj.get_router_model_id(),
+ )
+
@staticmethod
- def _extract_model_from_anthropic_chunks(
+ def _extract_message_start_field(
all_chunks: Sequence[str | bytes],
+ field: str,
) -> str | None:
for raw in all_chunks:
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
diff --cc litellm/proxy/pass_through_endpoints/streaming_handler.py
index 88c14c9348c,022a1ecbac4..4be0235adbb
--- a/litellm/proxy/pass_through_endpoints/streaming_handler.py
+++ b/litellm/proxy/pass_through_endpoints/streaming_handler.py
@@@ -1,7 -1,5 +1,7 @@@
-from collections.abc import Coroutine
-from datetime import datetime
+import traceback
- from collections.abc import Coroutine, Mapping, Sequence
++from collections.abc import Coroutine, Sequence
+from dataclasses import dataclass
+from datetime import datetime, timezone
from typing import Final, Protocol
import httpx
@@@ -59,72 -50,6 +59,72 @@@ class PassThroughStreamingHandler
if litellm_logging_obj.completion_start_time is None:
litellm_logging_obj._update_completion_start_time(completion_start_time=datetime.now())
+ @staticmethod
+ def schedule_stream_failure_logging(
+ litellm_logging_obj: LiteLLMLoggingObj,
+ endpoint_type: EndpointType,
- request_body: Mapping[str, object],
++ request_body: dict[str, object],
+ raw_bytes: Sequence[bytes],
+ exception: Exception,
+ stream_context: PassThroughStreamContext | None = None,
+ ) -> None:
+ PassThroughStreamingHandler._record_partial_usage_for_failure(
+ litellm_logging_obj=litellm_logging_obj,
+ endpoint_type=endpoint_type,
+ request_body=request_body,
+ raw_bytes=raw_bytes,
+ stream_context=stream_context,
+ )
+ try:
+ GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(
+ async_coroutine=litellm_logging_obj.dispatch_failure_handlers(
+ exception, traceback.format_exc(), prefer_async_handlers=True
+ )
+ )
+ except Exception as e:
+ verbose_proxy_logger.error("Error scheduling stream failure logging: %s", e)
+
+ @staticmethod
+ def _record_partial_usage_for_failure(
+ litellm_logging_obj: LiteLLMLoggingObj,
+ endpoint_type: EndpointType,
- request_body: Mapping[str, object],
++ request_body: dict[str, object],
+ raw_bytes: Sequence[bytes],
+ stream_context: PassThroughStreamContext | None,
+ ) -> None:
+ if endpoint_type == EndpointType.ANTHROPIC:
+ AnthropicPassthroughLoggingHandler.record_partial_usage_for_failure(
+ litellm_logging_obj=litellm_logging_obj, request_body=request_body, all_chunks=raw_bytes
+ )
+ return
+ if stream_context is None or not raw_bytes:
+ return
+ try:
+ partial_response, kwargs = PassThroughStreamingHandler._build_passthrough_logging_result(
+ litellm_logging_obj=litellm_logging_obj,
+ passthrough_success_handler_obj=stream_context.passthrough_success_handler_obj,
+ url_route=stream_context.url_route,
- request_body=dict(request_body),
++ request_body=request_body,
+ endpoint_type=endpoint_type,
+ start_time=stream_context.start_time,
- raw_bytes=list(raw_bytes),
++ raw_bytes=raw_bytes,
+ end_time=datetime.now(timezone.utc),
+ model=None,
+ )
+ except Exception as e:
+ verbose_proxy_logger.warning(
+ "Could not recover the partial usage of a failed %s pass-through stream: %s", endpoint_type.value, e
+ )
+ return
+ usage: Final = getattr(partial_response, "usage", None)
+ if not isinstance(usage, Usage):
+ return
+ response_cost: Final = kwargs.get("response_cost")
+ litellm_logging_obj.record_partial_usage_for_failure(
+ usage=usage,
+ response_cost=float(response_cost) if isinstance(response_cost, (int, float)) else 0.0,
+ )
+
@staticmethod
async def chunk_processor(
response: httpx.Response,
@@@ -140,13 -65,13 +140,14 @@@
route_streaming_logging or PassThroughStreamingHandler._route_streaming_logging_to_handler
)
raw_bytes: Final[list[bytes]] = []
++ resolved_request_body: Final[dict[str, object]] = request_body or {}
def _build_logging_coroutine() -> Coroutine[None, None, None]:
return resolved_route_streaming_logging(
litellm_logging_obj=litellm_logging_obj,
passthrough_success_handler_obj=passthrough_success_handler_obj,
url_route=url_route,
-- request_body=request_body or {},
++ request_body=resolved_request_body,
endpoint_type=endpoint_type,
start_time=start_time,
raw_bytes=raw_bytes,
@@@ -219,20 -144,6 +220,20 @@@
litellm_logging_obj._deferred_stream_complete_args = (_build_logging_coroutine(),)
except Exception as e:
verbose_proxy_logger.error("Error in chunk_processor: %s", e)
+ if response.status_code < 400:
+ logging_scheduled = True
+ PassThroughStreamingHandler.schedule_stream_failure_logging(
+ litellm_logging_obj=litellm_logging_obj,
+ endpoint_type=endpoint_type,
- request_body=request_body or {},
++ request_body=resolved_request_body,
+ raw_bytes=raw_bytes,
+ exception=e,
+ stream_context=PassThroughStreamContext(
+ passthrough_success_handler_obj=passthrough_success_handler_obj,
+ url_route=url_route,
+ start_time=start_time,
+ ),
+ )
raise
finally:
# GeneratorExit (raised on client disconnect) is not caught by
@@@ -257,7 -168,7 +258,7 @@@
request_body: dict,
endpoint_type: EndpointType,
start_time: datetime,
-- raw_bytes: list[bytes],
++ raw_bytes: Sequence[bytes],
end_time: datetime,
model: str | None = None,
):
@@@ -307,7 -218,7 +308,7 @@@
request_body: dict,
endpoint_type: EndpointType,
start_time: datetime,
-- raw_bytes: list[bytes],
++ raw_bytes: Sequence[bytes],
end_time: datetime,
model: str | None,
) -> tuple[PassThroughEndpointLoggingResultValues, dict]:
@@@ -425,7 -336,7 +426,7 @@@
return None
@staticmethod
-- def _convert_raw_bytes_to_str_lines(raw_bytes: list[bytes]) -> list[str]:
++ def _convert_raw_bytes_to_str_lines(raw_bytes: Sequence[bytes]) -> list[str]:
"""
Converts a list of raw bytes into a list of string lines, similar to aiter_lines()