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
chore: merge litellm_internal_staging into litellm_realtime_router_session_model
Devin AI2d643a86838c
diff --cc litellm/router.pyindex 95509bcdbba,23d8907fb49..48fd8ea517d--- a/litellm/router.py+++ b/litellm/router.py@@@ -29,7 -30,7 +30,7 @@@ import anyiimport httpximport openaifrom openai import AsyncOpenAI- from pydantic import TypeAdapter, ValidationError-from pydantic import BaseModel++from pydantic import BaseModel, TypeAdapter, ValidationErrorfrom typing_extensions import overloadimport litellm@@@ -343,26 -375,160 +375,180 @@@ def _stream_chunks_have_generated_contereturn False+_NO_SESSION_KWARGS: Final[Mapping[str, Mapping[str, object]]] = MappingProxyType({})+_SESSION_ADAPTER: Final = TypeAdapter(Mapping[str, object])+++def _with_router_resolved_session_model(session: object, model_name: str) -> Mapping[str, Mapping[str, object]]:+ """+ Realtime client-secret requests carry the model inside ``session`` as well, and the caller's copy of it still+ holds the pre-routing model group name, so it has to follow the deployment the router just picked.++ Returns kwargs to merge into the downstream call, empty when there is no session model to resolve.+ """+ try:+ typed_session: Final = _SESSION_ADAPTER.validate_python(session)+ except ValidationError:+ return _NO_SESSION_KWARGS+ if "model" not in typed_session:+ return _NO_SESSION_KWARGS+ return MappingProxyType({"session": {**typed_session, "model": model_name}})+++ # Router._aanthropic_messages_streaming_iterator buffers lifecycle chunks+ # until real content commits the primary stream; a hostile or slow-starting+ # upstream that never emits content or an error could otherwise grow that+ # buffer without bound, so hitting this cap forces an early commit instead.+ MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS: Final = 200+++ def _anthropic_stream_should_drop_pre_content_ping(chunk: object, has_generated_content: bool) -> bool:+ """A `ping` keepalive seen before any real content is dropped outright - it recurs indefinitely on a+ slow-starting connection and carries nothing worth buffering toward a possible fallback."""+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import is_anthropic_ping_chunk++ if has_generated_content:+ return False+ return is_anthropic_ping_chunk(chunk)+++ def _anthropic_stream_forwards_ping_live(chunk: object, has_generated_content: bool, buffered_chunk_count: int) -> bool:+ """A `ping` that no lifecycle frame precedes reaches the client live: a fallback's own message_start can still+ follow it without overlapping lifecycles, and AgenticAnthropicStreamingIterator's hold-back keepalive is exactly+ such a ping."""+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import is_anthropic_ping_chunk++ if has_generated_content or buffered_chunk_count:+ return False+ return is_anthropic_ping_chunk(chunk)+++ def _is_retriable_anthropic_status(status_code: int) -> bool:+ return status_code == 429 or status_code >= 500+++ def _anthropic_stream_error_is_gateway_verdict(chunk: object) -> bool:+ """AgenticAnthropicStreamingIterator's own retrieval-failure frame is the gateway's verdict, not a provider+ failure: another deployment would rerun the same failed hook, so it reaches the client instead of falling back."""+ from litellm.llms.anthropic.experimental_pass_through.messages.agentic_streaming_iterator import (+ is_server_fulfilled_tool_leak_error,+ )++ return is_server_fulfilled_tool_leak_error(chunk)+++ def _anthropic_stream_should_decline_fallback(has_generated_content: bool, error: "MidStreamFallbackError") -> bool:+ """+ A MidStreamFallbackError raised directly by the source iterator (the+ completion-bridge path's CustomStreamWrapper, e.g. on a transport drop)+ carries its own pre_first_chunk bookkeeping - gated the same way a+ detected SSE error event is, so a fallback is never appended after real+ content already reached the client on either path.+ """+ return has_generated_content or not error.is_pre_first_chunk+++ def _anthropic_stream_raised_error_status(error: Exception) -> int | None:+ raw_status: Final = getattr(error, "status_code", None)+ if isinstance(raw_status, int):+ return raw_status+ if isinstance(raw_status, str) and raw_status.isdigit():+ return int(raw_status)+ response_status: Final = getattr(getattr(error, "response", None), "status_code", None)+ return response_status if isinstance(response_status, int) else None+++ def _anthropic_stream_fallback_error_for_raised(+ error: Exception, model: str, has_generated_content: bool+ ) -> "MidStreamFallbackError | None":+ """Same gate as a detected SSE error event; None means the raise propagates unchanged."""+ from litellm.exceptions import MidStreamFallbackError++ if has_generated_content:+ return None+ status_code: Final = _anthropic_stream_raised_error_status(error)+ if status_code is not None and not _is_retriable_anthropic_status(status_code):+ return None+ return MidStreamFallbackError(+ message=str(error),+ model=model,+ llm_provider="anthropic",+ original_exception=error,+ is_pre_first_chunk=True,+ )+++ def _anthropic_stream_commits_now(chunk: object, has_generated_content: bool, buffered_chunk_count: int) -> bool:+ """+ Whether `chunk` should make Router._aanthropic_messages_streaming_iterator+ commit to the primary Anthropic stream (real content arrived, or the+ pre-content buffer cap was hit) rather than keep buffering lifecycle+ frames toward a possible fallback.+ """+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (+ is_anthropic_content_delta_chunk,+ )++ if has_generated_content:+ return False+ return is_anthropic_content_delta_chunk(chunk) or buffered_chunk_count >= MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS+++ class FallbackAwareAnthropicMessagesStream:+ """+ Bare async generators can't carry the `_hidden_params` attribute the+ proxy reads response headers off of (see+ router_utils.add_retry_fallback_headers.get_hidden_params_dict), so this+ thin wrapper carries it through from the source iterator - mirrors+ AnthropicMessagesStreamingResponse. Used by+ Router._aanthropic_messages_streaming_iterator.+ """++ def __init__(self, async_generator: AsyncGenerator[bytes, None], source_iterator: object) -> None:+ self._async_generator = async_generator+ self._source_iterator = source_iterator+ self._hidden_params = dict( # mutable-ok: mutated in place by merge_fallback_hidden_params+ getattr(source_iterator, "_hidden_params", None) or {}+ )++ @property+ def has_buffered_provider_output(self) -> bool:+ return getattr(self._source_iterator, "has_buffered_provider_output", False) is True++ def adopt_fallback_source(self, fallback_response: object) -> None:+ self._source_iterator = fallback_response++ def __aiter__(self) -> "FallbackAwareAnthropicMessagesStream":+ return self++ async def __anext__(self) -> bytes:+ return await self._async_generator.__anext__()++ async def aclose(self) -> None:+ await self._async_generator.aclose()++ def merge_fallback_hidden_params(+ self,+ fallback_hidden_params: Mapping[str, object],+ fallback_headers: Mapping[str, object],+ ) -> None:+ """+ Raw bytes can't carry their own _hidden_params the way a+ ModelResponseStream/ResponsesAPI event can, so a mid-stream+ fallback's provider headers (e.g. Bedrock's x-amzn-requestid) are+ merged onto the wrapper itself instead - mirrors+ Router._apply_fallback_hidden_params_to_item's merge shape.+ """+ existing_headers: Final = cast( # cast-ok: additional_headers is always a dict[str, object] when present+ "dict[str, object]", self._hidden_params.get("additional_headers") or {}+ )+ self._hidden_params = { # mutable-ok: matches _hidden_params' existing dict[str, object] shape+ **self._hidden_params,+ **fallback_hidden_params,+ "additional_headers": {**existing_headers, **fallback_headers}, # mutable-ok: same shape+ }++class RoutingArgs(enum.Enum):ttl = 60 # 1min (RPM/TPM expire key)