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]

Merge origin/litellm_internal_staging into litellm_anthropic_stream_model_alias

mateo-berri97e2aa9e7f17
diff --cc litellm/proxy/anthropic_endpoints/streaming_model_restamp.py
index 857b6abd065,00000000000..bbb7f2ceaa3
mode 100644,000000..100644
--- a/litellm/proxy/anthropic_endpoints/streaming_model_restamp.py
+++ b/litellm/proxy/anthropic_endpoints/streaming_model_restamp.py
@@@ -1,79 -1,0 +1,81 @@@
+"""
+Restamp the public ``model`` on the Anthropic Messages ``message_start`` event, the only
+stream event carrying a model, so streamed responses report the requested model like
+non-streaming ones do.
+
+Chunks reach the serializer either as already-encoded SSE frames (``bytes``/``str``, the
+provider passthrough path) or as event dicts (fake-stream and agentic paths).
+"""
+
+import json
++from collections.abc import Mapping
++from typing import Final
+
+from pydantic import TypeAdapter, ValidationError
+
- _MESSAGE_START_EVENT = "message_start"
- _SSE_DATA_FIELD = "data:"
++_MESSAGE_START_EVENT: Final = "message_start"
++_SSE_DATA_FIELD: Final = "data:"
+
- _EVENT_ADAPTER: TypeAdapter[dict[str, object]] = TypeAdapter(dict[str, object])
++_EVENT_ADAPTER: Final = TypeAdapter(Mapping[str, object])
+
+
- def _restamped_event(event: dict[str, object], requested_model: str) -> dict[str, object] | None:
- message = event.get("message")
++def _restamped_event(event: Mapping[str, object], requested_model: str) -> Mapping[str, object] | None:
++ message: Final = event.get("message")
+ if event.get("type") != _MESSAGE_START_EVENT or not isinstance(message, dict):
+ return None
+ if message.get("model") == requested_model:
+ return None
+ return {**event, "message": {**message, "model": requested_model}} # mutable-ok: SSE payload, re-serialized as is
+
+
+def _restamped_data_line(line: str, requested_model: str) -> str | None:
- stripped = line.strip()
++ stripped: Final = line.strip()
+ if not stripped.startswith(_SSE_DATA_FIELD):
+ return None
- payload = stripped[len(_SSE_DATA_FIELD) :].strip()
++ payload: Final = stripped[len(_SSE_DATA_FIELD) :].strip()
+ if not payload or payload == "[DONE]":
+ return None
+ try:
- event = _EVENT_ADAPTER.validate_json(payload)
++ event: Final = _EVENT_ADAPTER.validate_json(payload)
+ except ValidationError:
+ return None
- restamped = _restamped_event(event, requested_model)
++ restamped: Final = _restamped_event(event, requested_model)
+ if restamped is None:
+ return None
+ return f"data: {json.dumps(restamped, separators=(',', ':'))}"
+
+
+def _restamped_frame(frame: str, requested_model: str) -> str | None:
- lines = frame.split("\n")
- restamped = tuple(_restamped_data_line(line, requested_model) for line in lines)
++ lines: Final = frame.split("\n")
++ restamped: Final = tuple(_restamped_data_line(line, requested_model) for line in lines)
+ if all(line is None for line in restamped):
+ return None
+ return "\n".join(new if new is not None else old for new, old in zip(restamped, lines))
+
+
+def restamp_anthropic_stream_chunk_model(chunk: object, requested_model: str) -> object:
+ """
+ Return ``chunk`` with the ``message_start`` model replaced by ``requested_model``.
+
+ Chunks that carry no model are returned unchanged.
+ """
+ if isinstance(chunk, dict):
+ try:
- event = _EVENT_ADAPTER.validate_python(chunk)
++ event: Final = _EVENT_ADAPTER.validate_python(chunk)
+ except ValidationError:
+ return chunk
+ return _restamped_event(event, requested_model) or chunk
+
+ if isinstance(chunk, (bytes, bytearray)):
+ if _MESSAGE_START_EVENT.encode() not in chunk:
+ return chunk
- restamped = _restamped_frame(chunk.decode("utf-8", errors="ignore"), requested_model)
- return chunk if restamped is None else restamped.encode("utf-8")
++ restamped_bytes: Final = _restamped_frame(chunk.decode("utf-8", errors="ignore"), requested_model)
++ return chunk if restamped_bytes is None else restamped_bytes.encode("utf-8")
+
+ if isinstance(chunk, str):
+ if _MESSAGE_START_EVENT not in chunk:
+ return chunk
- restamped = _restamped_frame(chunk, requested_model)
- return chunk if restamped is None else restamped
++ restamped_text: Final = _restamped_frame(chunk, requested_model)
++ return chunk if restamped_text is None else restamped_text
+
+ return chunk
diff --cc litellm/proxy/common_request_processing.py
index fd5de0debec,ed66bb65ced..23e887f34a3
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@@ -70,10 -176,11 +176,14 @@@ if TYPE_CHECKING
ProxyConfig = _ProxyConfig
else:
ProxyConfig = Any
+from litellm.proxy.anthropic_endpoints.streaming_model_restamp import (
+ restamp_anthropic_stream_chunk_model,
+)
- from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
+ from litellm.proxy.litellm_pre_call_utils import (
+ add_litellm_data_to_request,
+ refresh_proxy_server_request_body_snapshot,
+ reject_url_valued_destination,
+ )
from litellm.types.utils import (
ModelResponse,
ModelResponseStream,
@@@ -1956,12 -2451,12 +2454,15 @@@ class ProxyBaseLLMRequestProcessing
request_data=self.data,
proxy_logging_obj=proxy_logging_obj,
request=request,
+ restamp_model=(
+ None if _should_return_raw_model_name(self.data) else requested_model_from_client
+ ),
)
return await create_response(
- generator=selected_data_generator,
+ generator=wrap_sse_stream_with_keepalive_pings(
+ stream=selected_data_generator,
+ ping_interval_seconds=litellm.anthropic_sse_ping_interval_seconds,
+ ),
media_type="text/event-stream",
headers=custom_headers,
request=request,