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]

feat(proxy): add router_model_name to auto-routed response bodies (#37725)

tin-berrif9a8c96b827d
diff --git a/litellm/constants.py b/litellm/constants.py
index 7eccfc58221..11904d5e9c2 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1354,6 +1354,8 @@ X_LITELLM_DISABLE_CALLBACKS: Final = "x-litellm-disable-callbacks"
LITELLM_METADATA_FIELD: Final = "litellm_metadata"
OLD_LITELLM_METADATA_FIELD: Final = "metadata"
RETURN_RAW_MODEL_NAME_METADATA_KEY: Final = "_complexity_router_return_raw_model_name"
+AUTO_ROUTED_REQUEST_METADATA_KEY: Final = "_auto_routed_request"
+ROUTER_MODEL_NAME_RESPONSE_FIELD: Final = "router_model_name"
SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY: Final = "_session_deployment_affinity_ttl"
CONSUMED_REQUEST_TAGS_METADATA_KEY: Final = "_consumed_request_tags"
INTERNAL_CALL_ORIGIN_METADATA_KEY: Final = "internal_call_origin"
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index e5714ef66fb..3fb09cde931 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -22,12 +22,14 @@ import litellm
from litellm._logging import _redact_string, verbose_proxy_logger
from litellm._uuid import uuid
from litellm.constants import (
+ AUTO_ROUTED_REQUEST_METADATA_KEY,
DD_TRACER_STREAMING_CHUNK_YIELD_RESOURCE,
DEFAULT_MAX_RECURSE_DEPTH,
LITELLM_DETAILED_TIMING,
LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED,
MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG,
RETURN_RAW_MODEL_NAME_METADATA_KEY,
+ ROUTER_MODEL_NAME_RESPONSE_FIELD,
STREAM_SSE_DATA_PREFIX,
UNSAFE_PROXY_RESPONSE_HEADERS,
)
@@ -2010,6 +2012,54 @@ class ProxyBaseLLMRequestProcessing:
return deployment
return None
+ @staticmethod
+ def get_router_selected_model_name(
+ litellm_logging_obj: LiteLLMLoggingObj | None,
+ ) -> str | None:
+ """Model group an auto-routing strategy selected, or None if none fired.
+
+ The marker and ``deployment_model_name`` are written by different bucket
+ resolvers (``get_or_create_metadata_bucket`` vs
+ ``_get_router_metadata_variable_name``), so they can land in different
+ buckets on the same request. Resolve each across both.
+ """
+ litellm_params: Final = getattr(litellm_logging_obj, "litellm_params", None)
+ if not isinstance(litellm_params, dict):
+ return None
+ buckets: Final = tuple(
+ bucket for key in ("litellm_metadata", "metadata") if isinstance(bucket := litellm_params.get(key), dict)
+ )
+ if not any(bucket.get(AUTO_ROUTED_REQUEST_METADATA_KEY) is True for bucket in buckets):
+ return None
+ return next(
+ (
+ model_group
+ for bucket in buckets
+ if isinstance(model_group := bucket.get("deployment_model_name"), str) and model_group
+ ),
+ None,
+ )
+
+ @staticmethod
+ def set_router_selected_model_field(
+ *,
+ response_obj: object,
+ router_model_name: str | None,
+ ) -> None:
+ if not router_model_name:
+ return
+ if isinstance(response_obj, dict):
+ response_obj[ROUTER_MODEL_NAME_RESPONSE_FIELD] = router_model_name
+ return
+ try:
+ setattr(response_obj, ROUTER_MODEL_NAME_RESPONSE_FIELD, router_model_name)
+ except (AttributeError, TypeError, ValueError):
+ verbose_proxy_logger.debug(
+ "Could not set %s on response object of type %s",
+ ROUTER_MODEL_NAME_RESPONSE_FIELD,
+ type(response_obj),
+ )
+
@staticmethod
def _response_cost_from_logging_obj(
*,
@@ -2508,6 +2558,10 @@ class ProxyBaseLLMRequestProcessing:
log_context=f"litellm_call_id={logging_obj.litellm_call_id}",
return_raw_model_name=_should_return_raw_model_name(self.data),
)
+ self.set_router_selected_model_field(
+ response_obj=response,
+ router_model_name=self.get_router_selected_model_name(logging_obj),
+ )
hidden_params = get_hidden_params_dict(response) # get any updated response headers
additional_headers = hidden_params.get("additional_headers", {}) or {}
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 9ee62f94647..9f16584340d 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -247,6 +247,7 @@ from litellm.constants import (
PROXY_BUDGET_RESCHEDULER_MAX_TIME,
PROXY_BUDGET_RESCHEDULER_MIN_TIME,
PROXY_CONFIG_RELOAD_INTERVAL_SECONDS,
+ ROUTER_MODEL_NAME_RESPONSE_FIELD,
WEEKLY_SPEND_REPORT_JOB_ID,
)
from litellm.exceptions import RejectedRequestError
@@ -7913,6 +7914,10 @@ def _fast_serialize_simple_model_response_stream(
for top_level_key in ("id", "object", "created"):
if payload[top_level_key] is None:
payload.pop(top_level_key)
+
+ router_model_name: Final = getattr(chunk, ROUTER_MODEL_NAME_RESPONSE_FIELD, None)
+ if router_model_name is not None:
+ payload[ROUTER_MODEL_NAME_RESPONSE_FIELD] = router_model_name
return orjson.dumps(payload)
@@ -8210,6 +8215,9 @@ async def async_data_generator(
model_mismatch_logged = False
fallback_metadata_event_sent = False
include_fallback_errors: Final = _should_include_fallback_errors(request_data)
+ # Fallbacks resolve on the first ``__anext__``, so the selected group is read
+ # per chunk off this object rather than snapshotted here.
+ router_logging_obj: Final = request_data.get("litellm_logging_obj")
# Use a running string instead of list + join to avoid O(n^2) overhead.
# Previously "".join(str_so_far_parts) was called every chunk, re-joining
# the entire accumulated response. String += is O(n) amortized total.
@@ -8299,6 +8307,10 @@ async def async_data_generator(
fallback_was_attempted=fallback_was_attempted,
fallback_model_from_metadata=fallback_model_from_metadata,
)
+ ProxyBaseLLMRequestProcessing.set_router_selected_model_field(
+ response_obj=chunk,
+ router_model_name=ProxyBaseLLMRequestProcessing.get_router_selected_model_name(router_logging_obj),
+ )
if strip_stream_usage and _is_injected_stream_usage_artifact(chunk):
if pending_fallback_event:
@@ -8414,10 +8426,6 @@ async def async_data_generator(
stream_completed = True
yield f"data: {error_returned}\n\n"
finally:
- from litellm.proxy.common_request_processing import (
- ProxyBaseLLMRequestProcessing,
- )
-
await ProxyBaseLLMRequestProcessing._finalize_streaming_generator_cleanup(
request=request,
request_data=request_data,
diff --git a/litellm/router.py b/litellm/router.py
index e9eeab53934..e9d4dd0a482 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -44,6 +44,7 @@ from litellm.caching.caching import (
RedisClusterCache,
)
from litellm.constants import (
+ AUTO_ROUTED_REQUEST_METADATA_KEY,
CONSUMED_REQUEST_TAGS_METADATA_KEY,
DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS,
DEFAULT_HEALTH_CHECK_INTERVAL,
@@ -11647,6 +11648,9 @@ class Router:
self._stamp_or_clear_metadata_key(
request_kwargs=request_kwargs, key=CONSUMED_REQUEST_TAGS_METADATA_KEY, value=None
)
+ self._stamp_or_clear_metadata_key(
+ request_kwargs=request_kwargs, key=AUTO_ROUTED_REQUEST_METADATA_KEY, value=None
+ )
return None
pre_routing_hook_response: Final = await selected_strategy.strategy.async_pre_routing_hook(
@@ -11674,6 +11678,13 @@ class Router:
request_tags=_get_tags_from_request_kwargs(request_kwargs),
),
)
+ # Gates the proxy's `router_model_name` response field; the body `model` is
+ # always restamped back to the alias the client sent.
+ self._stamp_or_clear_metadata_key(
+ request_kwargs=request_kwargs,
+ key=AUTO_ROUTED_REQUEST_METADATA_KEY,
+ value=(True if pre_routing_hook_response is not None else None),
+ )
# `model` (the alias, e.g. "smart-router") is never the deployment actually
# called - apply the router marker's own litellm_params to the request,
diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py
index 716fba370df..bcf34a83bb4 100644
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@ -13,7 +13,11 @@ from fastapi.responses import JSONResponse, StreamingResponse
import litellm
from litellm._uuid import uuid
-from litellm.constants import RETURN_RAW_MODEL_NAME_METADATA_KEY
+from litellm.constants import (
+ AUTO_ROUTED_REQUEST_METADATA_KEY,
+ RETURN_RAW_MODEL_NAME_METADATA_KEY,
+ ROUTER_MODEL_NAME_RESPONSE_FIELD,
+)
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.opentelemetry import UserAPIKeyAuth
from litellm.proxy.common_request_processing import (
@@ -7100,3 +7104,125 @@ async def test_a_broken_hook_does_not_replace_the_real_error_with_its_own_bug():
error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())
assert error_frame["error"]["message"] == "rate limited"
assert "audit backend" not in collected[-2].decode()
+
+
+class TestRouterModelNameOnNonStreamingResponse:
+ """
+ The proxy restamps the response body `model` back to the client-requested
+ alias, so an auto-routed request (auto_router / complexity_router /
+ adaptive_router / quality_router) had no body-level surface naming the model
+ group that actually served it. `router_model_name` is now set on the response
+ whenever the router marked the request as auto-routed.
+ """
+
+ @staticmethod
+ def _logging_obj(*, metadata_bucket, bucket_name="metadata"):
+ logging_obj = MagicMock()
+ logging_obj.litellm_call_id = "call-auto-routed"
+ logging_obj.cost_breakdown = None
+ logging_obj.model_call_details = {}
+ logging_obj.litellm_params = {bucket_name: metadata_bucket}
+ logging_obj._enqueue_deferred_logging = None
+ logging_obj._on_deferred_stream_complete = None
+ return logging_obj
+
+ async def _drive(self, *, monkeypatch, logging_obj):
+ import litellm.proxy.common_request_processing as crp
+ from litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth
+ from litellm.types.utils import ModelResponse
+
+ response = ModelResponse(
+ model="deep-model",
+ choices=[{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
+ )
+
+ async def fake_route_request(**kwargs):
+ async def _llm_call():
+ return response
+
+ return _llm_call()
+
+ monkeypatch.setattr(crp, "route_request", fake_route_request)
+
+ async def fake_post_call_success_hook(data, user_api_key_dict, response):
+ return response
+
+ proxy_logging_obj = MagicMock(spec=ProxyLogging)
+ proxy_logging_obj.during_call_hook = AsyncMock(return_value=None)
+ proxy_logging_obj.update_request_status = AsyncMock(return_value=None)
+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})
+ proxy_logging_obj.post_call_success_hook = fake_post_call_success_hook
+
+ processing_obj = ProxyBaseLLMRequestProcessing(
+ data={"model": "smart-route", "litellm_logging_obj": logging_obj}
+ )
+
+ with patch.object(ProxyBaseLLMRequestProcessing, "_has_post_call_guardrails", return_value=False):
+ return await processing_obj.base_process_llm_request(
+ request=MagicMock(spec=Request, headers={}),
+ fastapi_response=Response(),
+ user_api_key_dict=RealUserAPIKeyAuth(api_key="sk-test"),
+ route_type="acompletion",
+ proxy_logging_obj=proxy_logging_obj,
+ general_settings={},
+ proxy_config=MagicMock(spec=ProxyConfig),
+ select_data_generator=None,
+ llm_router=None,
+ skip_pre_call_logic=True,
+ )
+
+ @pytest.mark.asyncio
+ async def test_auto_routed_request_carries_router_model_name(self, monkeypatch):
+ result = await self._drive(
+ monkeypatch=monkeypatch,
+ logging_obj=self._logging_obj(
+ metadata_bucket={
+ AUTO_ROUTED_REQUEST_METADATA_KEY: True,
+ "deployment_model_name": "deep-model",
+ }
+ ),
+ )
+
+ assert result.model == "smart-route"
+ assert result.model_dump(exclude_none=True, exclude_unset=True)[ROUTER_MODEL_NAME_RESPONSE_FIELD] == (
+ "deep-model"
+ )
+
+ @pytest.mark.asyncio
+ async def test_marker_and_model_name_in_different_buckets(self, monkeypatch):
+ logging_obj = self._logging_obj(metadata_bucket={AUTO_ROUTED_REQUEST_METADATA_KEY: True})
+ logging_obj.litellm_params["litellm_metadata"] = {"deployment_model_name": "deep-model"}
+
+ result = await self._drive(monkeypatch=monkeypatch, logging_obj=logging_obj)
+
+ assert result.model_dump(exclude_none=True, exclude_unset=True)[ROUTER_MODEL_NAME_RESPONSE_FIELD] == (
+ "deep-model"
+ )
+
+ @pytest.mark.asyncio
+ async def test_plain_model_group_request_has_no_router_model_name(self, monkeypatch):
+ result = await self._drive(
+ monkeypatch=monkeypatch,
+ logging_obj=self._logging_obj(metadata_bucket={"deployment_model_name": "deep-model"}),
+ )
+
+ assert ROUTER_MODEL_NAME_RESPONSE_FIELD not in result.model_dump(exclude_none=True, exclude_unset=True)
+
+ @pytest.mark.asyncio
+ async def test_typeddict_response_gets_router_model_name(self):
+ from litellm.types.utils import AnthropicMessagesResponse
+
+ response: AnthropicMessagesResponse = {"id": "msg_1", "model": "smart-route", "type": "message"}
+ ProxyBaseLLMRequestProcessing.set_router_selected_model_field(
+ response_obj=response,
+ router_model_name=ProxyBaseLLMRequestProcessing.get_router_selected_model_name(
+ self._logging_obj(
+ metadata_bucket={
+ AUTO_ROUTED_REQUEST_METADATA_KEY: True,
+ "deployment_model_name": "deep-model",
+ }
+ )
+ ),
+ )
+
+ assert response[ROUTER_MODEL_NAME_RESPONSE_FIELD] == "deep-model"
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index 83e9095c8ec..4f0029e8281 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -11195,3 +11195,156 @@ class TestEmbeddingsFailureHookRequestData:
hook_request_data = mock_logging.post_call_failure_hook.await_args.kwargs["request_data"]
assert hook_request_data is captured["processor_data"]
assert hook_request_data["litellm_logging_obj"] is logging_obj_sentinel
+
+
+class TestRouterModelNameOnStreamingChunks:
+ """
+ Streaming chunks get the body `model` restamped to the client-requested alias
+ just like non-streaming responses, so an auto-routed request had no way to
+ name the model group that served it without reading response headers. Every
+ emitted chunk now carries `router_model_name`.
+
+ These assert on the serialized SSE bytes, not on the chunk objects. The fast
+ path (`_fast_serialize_simple_model_response_stream`) hand-builds a
+ closed-set dict, so a chunk object can carry the field while the wire drops
+ it, and an object-level assertion would pass against that bug.
+ """
+
+ @staticmethod
+ def _chunk(*, with_usage=False):
+ from litellm.types.utils import ModelResponseStream
+
+ return ModelResponseStream(
+ model="smart-route",
+ choices=[{"index": 0, "delta": {"role": "assistant", "content": "hi"}}],
+ usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} if with_usage else None,
+ )
+
+ @staticmethod
+ def _request_data(*, auto_routed):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ logging_obj = MagicMock()
+ logging_obj.litellm_params = {
+ "metadata": {
+ **({AUTO_ROUTED_REQUEST_METADATA_KEY: True} if auto_routed else {}),
+ "deployment_model_name": "deep-model",
+ }
+ }
+ return {"model": "smart-route", "litellm_logging_obj": logging_obj}
+
+ async def _drive(self, *, chunks, request_data, on_yield=None):
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.proxy_server import async_data_generator
+ from litellm.proxy.utils import ProxyLogging
+
+ class MockStream:
+ def __aiter__(self):
+ return self._stream()
+
+ async def _stream(self):
+ for index, chunk in enumerate(chunks):
+ if on_yield is not None:
+ on_yield(index)
+ yield chunk
+
+ mock_response = MockStream()
+ mock_response.aclose = AsyncMock()
+
+ proxy_logging_obj = MagicMock(spec=ProxyLogging)
+ proxy_logging_obj.has_streaming_callbacks.return_value = False
+ proxy_logging_obj.needs_iterator_wrap.return_value = False
+ proxy_logging_obj.needs_per_chunk_streaming_hook.return_value = False
+ proxy_logging_obj.async_post_call_streaming_iterator_hook = MagicMock()
+ proxy_logging_obj.async_post_call_streaming_hook = AsyncMock()
+ proxy_logging_obj.post_call_failure_hook = AsyncMock()
+
+ with patch("litellm.proxy.proxy_server.proxy_logging_obj", proxy_logging_obj):
+ with patch.object(ProxyLogging, "_fire_deferred_stream_logging"):
+ return [
+ data
+ async for data in async_data_generator(
+ mock_response, MagicMock(spec=UserAPIKeyAuth), request_data
+ )
+ ]
+
+ @staticmethod
+ def _data_frames(emitted):
+ return [
+ frame.decode() if isinstance(frame, bytes) else frame
+ for frame in emitted
+ if b"[DONE]" not in (frame if isinstance(frame, bytes) else frame.encode())
+ ]
+
+ @pytest.mark.asyncio
+ async def test_fast_path_chunk_carries_router_model_name_on_the_wire(self):
+ emitted = await self._drive(chunks=[self._chunk()], request_data=self._request_data(auto_routed=True))
+
+ frames = self._data_frames(emitted)
+ assert frames
+ assert all('"router_model_name":"deep-model"' in frame for frame in frames)
+ assert all('"model":"smart-route"' in frame for frame in frames)
+
+ @pytest.mark.asyncio
+ async def test_slow_path_chunk_carries_router_model_name_on_the_wire(self):
+ emitted = await self._drive(
+ chunks=[self._chunk(with_usage=True)], request_data=self._request_data(auto_routed=True)
+ )
+
+ frames = self._data_frames(emitted)
+ assert frames
+ assert all('"router_model_name":"deep-model"' in frame for frame in frames)
+
+ @pytest.mark.asyncio
+ async def test_plain_model_group_stream_has_no_router_model_name(self):
+ emitted = await self._drive(
+ chunks=[self._chunk(), self._chunk(with_usage=True)],
+ request_data=self._request_data(auto_routed=False),
+ )
+
+ frames = self._data_frames(emitted)
+ assert frames
+ assert all("router_model_name" not in frame for frame in frames)
+
+ @pytest.mark.asyncio
+ async def test_fallback_out_of_the_routed_group_drops_the_field(self):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ request_data = self._request_data(auto_routed=True)
+ bucket = request_data["litellm_logging_obj"].litellm_params["metadata"]
+
+ def fall_back(index):
+ if index == 1:
+ bucket.pop(AUTO_ROUTED_REQUEST_METADATA_KEY)
+ bucket["deployment_model_name"] = "backup-model"
+
+ emitted = await self._drive(
+ chunks=[self._chunk(), self._chunk(), self._chunk()],
+ request_data=request_data,
+ on_yield=fall_back,
+ )
+
+ frames = self._data_frames(emitted)
+ assert len(frames) >= 3
+ assert '"router_model_name":"deep-model"' in frames[0]
+ assert all("router_model_name" not in frame for frame in frames[1:])
+
+ @pytest.mark.asyncio
+ async def test_fallback_to_another_auto_router_reports_the_new_tier(self):
+ request_data = self._request_data(auto_routed=True)
+ bucket = request_data["litellm_logging_obj"].litellm_params["metadata"]
+
+ def fall_back(index):
+ if index == 1:
+ bucket["deployment_model_name"] = "backup-tier"
+
+ emitted = await self._drive(
+ chunks=[self._chunk(), self._chunk(), self._chunk()],
+ request_data=request_data,
+ on_yield=fall_back,
+ )
+
+ frames = self._data_frames(emitted)
+ assert len(frames) >= 3
+ assert '"router_model_name":"deep-model"' in frames[0]
+ assert all('"router_model_name":"backup-tier"' in frame for frame in frames[1:])
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index a47525749f6..1d6eb1bc590 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -8549,3 +8549,93 @@ def test_get_router_model_info_keeps_explicit_pricing_overrides():
assert merged["input_cost_per_token"] == 1e-08
assert litellm.get_model_info(model="anthropic/claude-sonnet-4-5")["input_cost_per_token"] != 1e-08
+
+
+class TestAutoRoutedRequestMarker:
+ """The proxy exposes the routed model group in the response body only when an
+ auto-routing strategy actually picked it. The marker is what separates that from
+ ordinary model-group routing, so it must clear on any re-entry (fallbacks reuse the
+ same request_kwargs) that routes plainly."""
+
+ class _RewriteStrategy:
+ async def async_pre_routing_hook(
+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False
+ ):
+ from litellm.types.router import PreRoutingHookResponse
+
+ return PreRoutingHookResponse(model="gemini-flash", messages=messages)
+
+ class _AbstainStrategy:
+ async def async_pre_routing_hook(
+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False
+ ):
+ return None
+
+ @classmethod
+ def _router(cls, strategy) -> "litellm.Router":
+ from litellm.types.router import TaggedPreRoutingStrategy
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "smart-route", "litellm_params": {"model": "openai/gpt-4o"}},
+ {"model_name": "gemini-flash", "litellm_params": {"model": "gemini/gemini-3.6-flash"}},
+ ],
+ )
+ router.auto_routers = {"smart-route": [TaggedPreRoutingStrategy(tags=(), strategy=strategy)]}
+ return router
+
+ @pytest.mark.asyncio
+ async def test_marks_the_request_when_an_auto_routing_strategy_picked_the_group(self):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ router = self._router(self._RewriteStrategy())
+ request_kwargs = {"metadata": {}}
+
+ await router.async_pre_routing_hook(model="smart-route", request_kwargs=request_kwargs)
+
+ assert request_kwargs["metadata"][AUTO_ROUTED_REQUEST_METADATA_KEY] is True
+
+ @pytest.mark.asyncio
+ async def test_marks_into_litellm_metadata_when_the_request_uses_that_bucket(self):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ router = self._router(self._RewriteStrategy())
+ request_kwargs = {"litellm_metadata": {}}
+
+ await router.async_pre_routing_hook(model="smart-route", request_kwargs=request_kwargs)
+
+ assert request_kwargs["litellm_metadata"][AUTO_ROUTED_REQUEST_METADATA_KEY] is True
+
+ @pytest.mark.asyncio
+ async def test_no_marker_when_the_group_has_no_auto_routing_strategy(self):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ router = self._router(self._RewriteStrategy())
+ request_kwargs = {"metadata": {}}
+
+ await router.async_pre_routing_hook(model="gemini-flash", request_kwargs=request_kwargs)
+
+ assert AUTO_ROUTED_REQUEST_METADATA_KEY not in request_kwargs["metadata"]
+
+ @pytest.mark.asyncio
+ async def test_no_marker_when_the_strategy_declined_to_route(self):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ router = self._router(self._AbstainStrategy())
+ request_kwargs = {"metadata": {}}
+
+ await router.async_pre_routing_hook(model="smart-route", request_kwargs=request_kwargs)
+
+ assert AUTO_ROUTED_REQUEST_METADATA_KEY not in request_kwargs["metadata"]
+
+ @pytest.mark.asyncio
+ async def test_fallback_reentry_with_a_plain_group_clears_the_stale_marker(self):
+ from litellm.constants import AUTO_ROUTED_REQUEST_METADATA_KEY
+
+ router = self._router(self._RewriteStrategy())
+ request_kwargs = {"metadata": {}}
+
+ await router.async_pre_routing_hook(model="smart-route", request_kwargs=request_kwargs)
+ await router.async_pre_routing_hook(model="gemini-flash", request_kwargs=request_kwargs)
+
+ assert AUTO_ROUTED_REQUEST_METADATA_KEY not in request_kwargs["metadata"]