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]

fix(router): merge staging and retain native classifier audits

moe-berri73013124b919
diff --cc litellm/litellm_core_utils/classifier_logging.py
index 4cbfdb8cd49,00000000000..fdc1cac26c0
mode 100644,000000..100644
--- a/litellm/litellm_core_utils/classifier_logging.py
+++ b/litellm/litellm_core_utils/classifier_logging.py
@@@ -1,59 -1,0 +1,67 @@@
+from collections.abc import Mapping
++from types import MappingProxyType
+from typing import Final
+
+from pydantic import JsonValue, TypeAdapter, ValidationError
+
+from litellm.constants import INTERNAL_CALL_ORIGIN_METADATA_KEY
+from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+from litellm.litellm_core_utils.sensitive_data_masker import redact_credentials_in_payload
+from litellm.types.utils import AUTOROUTER_CLASSIFIER_CALL_ORIGIN, ClassifierAudit
+
+CLASSIFIER_AUDIT_FIELDS: Final = ("classifier_input", "originating_request_masked")
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+
+
+def classifier_input_snapshot(value: object, *, openai_sdk: bool = False) -> Mapping[str, JsonValue] | None:
+ try:
+ if openai_sdk and isinstance(value, Mapping):
- body: Final = {
- key: item for key, item in value.items() if key not in ("extra_headers", "extra_query", "extra_body")
- }
++ body: Final = MappingProxyType(
++ {key: item for key, item in value.items() if key not in ("extra_headers", "extra_query", "extra_body")}
++ )
+ extra_body: Final = value.get("extra_body")
- return _JSON_OBJECT.validate_python({**body, **extra_body} if isinstance(extra_body, Mapping) else body)
++ return _JSON_OBJECT.validate_python(
++ MappingProxyType({**body, **extra_body}) if isinstance(extra_body, Mapping) else body
++ )
+ return (
+ _JSON_OBJECT.validate_json(value)
+ if isinstance(value, (str, bytes))
+ else _JSON_OBJECT.validate_python(value)
+ )
+ except ValidationError:
+ return None
+
+
+def is_classifier_call(call_type: str, params: Mapping[str, object]) -> bool:
- return call_type in ("completion", "acompletion") and any(
++ return call_type in ("completion", "acompletion", "responses", "aresponses") and any(
+ isinstance(metadata := params.get(key), Mapping)
+ and metadata.get(INTERNAL_CALL_ORIGIN_METADATA_KEY) == AUTOROUTER_CLASSIFIER_CALL_ORIGIN
+ for key in ("metadata", "litellm_metadata")
+ )
+
+
+def masked_originating_request(request_kwargs: Mapping[str, object] | None) -> Mapping[str, JsonValue] | None:
+ request: Final = request_kwargs.get("proxy_server_request") if request_kwargs is not None else None
+ body: Final = request.get("body") if isinstance(request, Mapping) else None
+ if not isinstance(body, Mapping):
+ return None
+ serializable: Final = classifier_input_snapshot(safe_dumps(body))
+ return classifier_input_snapshot(redact_credentials_in_payload(serializable)) if serializable is not None else None
+
+
+def classifier_audit_fields(payload: Mapping[str, object]) -> ClassifierAudit:
+ classifier_input: Final = classifier_input_snapshot(payload.get("classifier_input"))
+ originating_request: Final = classifier_input_snapshot(payload.get("originating_request_masked"))
- return {
- **(ClassifierAudit(classifier_input=classifier_input) if classifier_input is not None else {}),
- **(ClassifierAudit(originating_request_masked=originating_request) if originating_request is not None else {}),
- }
++ if classifier_input is None:
++ return (
++ ClassifierAudit(originating_request_masked=originating_request)
++ if originating_request is not None
++ else ClassifierAudit()
++ )
++ if originating_request is None:
++ return ClassifierAudit(classifier_input=classifier_input)
++ return ClassifierAudit(classifier_input=classifier_input, originating_request_masked=originating_request)
+
+
+def without_classifier_audit(payload: Mapping[str, object]) -> dict[str, object]:
+ return {key: value for key, value in payload.items() if key not in CLASSIFIER_AUDIT_FIELDS}
diff --cc litellm/litellm_core_utils/litellm_logging.py
index f85aa32829f,cb9209be267..893bfeefff8
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@@ -42,6 -42,6 +42,7 @@@ from litellm.caching.caching_handler im
from litellm.constants import (
DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT,
DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT,
++ EMPTY_MAPPING,
PROVIDER_REQUEST_ID_HEADERS,
SENTRY_DENYLIST,
SENTRY_PII_DENYLIST,
@@@ -1218,14 -1211,6 +1219,14 @@@ class Logging(LiteLLMLoggingBaseClass)
self.model_call_details["api_key"] = api_key
self.model_call_details["additional_args"] = additional_args
self.model_call_details["log_event_type"] = "pre_api_call"
- if is_classifier_call(self.call_type, self.model_call_details.get("litellm_params") or {}):
++ if is_classifier_call(self.call_type, self.model_call_details.get("litellm_params") or EMPTY_MAPPING):
+ self.classifier_input = (
+ None
+ if should_redact_message_logging(self.model_call_details)
+ else classifier_input_snapshot(
+ additional_args.get("complete_input_dict"), openai_sdk=additional_args.get("openai_sdk") is True
+ )
+ )
if model: # if model name was changes pre-call, overwrite the initial model call name with the new one
self.model_call_details["model"] = model
self.model_call_details["litellm_params"]["api_base"] = self._get_masked_api_base(
@@@ -6308,16 -6293,6 +6309,18 @@@ def get_standard_logging_object_payload
)
payload: Final[StandardLoggingPayload] = StandardLoggingPayload(
+ **(
+ classifier_audit_fields(
- {
- "classifier_input": logging_obj.classifier_input,
- "originating_request_masked": proxy_server_request.get("originating_request_masked"),
- }
++ MappingProxyType(
++ {
++ "classifier_input": logging_obj.classifier_input,
++ "originating_request_masked": proxy_server_request.get("originating_request_masked"),
++ }
++ )
+ )
+ if is_classifier_call(call_type or "", litellm_params) and not should_redact_message_logging(kwargs)
- else {}
++ else EMPTY_MAPPING
+ ),
id=str(id),
litellm_call_id=kwargs.get("litellm_call_id") or litellm_params.get("litellm_call_id"),
trace_id=StandardLoggingPayloadSetup.get_standard_logging_payload_trace_id(
diff --cc litellm/proxy/spend_tracking/spend_management_endpoints.py
index ee43972309b,f8831ca4152..42b99b78f5c
--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py
+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py
@@@ -26,8 -26,7 +26,12 @@@ from typing_extensions import ReadOnl
import litellm
from litellm._logging import verbose_proxy_logger
- from litellm.constants import LITELLM_TRUNCATED_PAYLOAD_FIELD, LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
-from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
++from litellm.constants import (
++ EMPTY_MAPPING,
++ LITELLM_TRUNCATED_PAYLOAD_FIELD,
++ LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
++)
+from litellm.litellm_core_utils.classifier_logging import classifier_audit_fields, classifier_input_snapshot
from litellm.proxy._types import *
from litellm.proxy._types import ProviderBudgetResponse, ProviderBudgetResponseObject
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
@@@ -3129,15 -3124,6 +3133,18 @@@ async def _resolve_request_response_pay
if payload is None:
return pg_payload
+ cold_audit: Final = classifier_audit_fields(payload)
+ resolved_request: Final = (
- {**(classifier_input_snapshot(payload.get("proxy_server_request")) or stored_request or {}), **cold_audit}
++ {
++ **(classifier_input_snapshot(payload.get("proxy_server_request")) or stored_request or EMPTY_MAPPING),
++ **cold_audit,
++ }
+ if cold_audit
+ else payload.get("proxy_server_request")
+ )
+ if truncated_audit:
+ return RequestResponsePayload(messages, response, resolved_request if cold_audit else proxy_server_request)
+
return RequestResponsePayload(
messages=payload.get("messages"),
response=payload.get("response"),
diff --cc litellm/proxy/spend_tracking/spend_tracking_utils.py
index 360b24575bf,a21d761996f..da35553a941
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@@ -11,6 -11,6 +11,7 @@@ from pydantic import BaseMode
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.constants import (
++ EMPTY_MAPPING,
LITELLM_PROXY_MASTER_KEY_ALIAS,
LITELLM_TRUNCATED_PAYLOAD_FIELD,
LITELLM_TRUNCATION_DB_SAFEGUARD_NOTE,
@@@ -1248,13 -1247,9 +1249,13 @@@ def _get_proxy_server_request_for_spend
If turn_off_message_logging is enabled, redact messages in the request body.
"""
if _should_store_prompts_and_responses_in_spend_logs():
-- _proxy_server_request: Final = cast(dict | None, litellm_params.get("proxy_server_request", {}))
++ _proxy_server_request: Final = cast(dict | None, litellm_params.get("proxy_server_request", EMPTY_MAPPING))
if _proxy_server_request is not None:
-- _request_body = _proxy_server_request.get("body", {}) or {}
++ _request_body = _proxy_server_request.get("body", EMPTY_MAPPING) or EMPTY_MAPPING
+
- standard_payload: Final = (kwargs or {}).get("standard_logging_object")
++ standard_payload: Final = (kwargs or EMPTY_MAPPING).get("standard_logging_object")
+ if isinstance(standard_payload, Mapping):
+ _request_body = {**_request_body, **classifier_audit_fields(standard_payload)}
if kwargs is not None:
realtime_tools: Final = kwargs.get("realtime_tools")
diff --cc litellm/router_strategy/complexity_router/complexity_router.py
index 162fcf2efb0,214872c17c9..6b30c6f3588
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@@ -2002,23 -2063,23 +2061,26 @@@ class ComplexityRouter(CustomLogger)
if llm_config.reasoning_effort is not None:
classifier_call_params = MappingProxyType({"reasoning_effort": llm_config.reasoning_effort})
+ payload: Final = (
+ self._native_classifier_payload(messages_for_call, response_format, encrypted_task)
+ if encrypted_task is not None
+ else {"messages": messages_for_call, "response_format": response_format, **classifier_call_params}
+ )
- proxy_server_request: Final = {"body": {"model": llm_config.model, **payload}}
+ proxy_server_request: Final = {
+ "originating_request_masked": masked_originating_request(request_kwargs),
- "body": {
- "model": llm_config.model,
- "messages": messages_for_call,
- "response_format": response_format,
- **classifier_call_params,
- },
++ "body": {"model": llm_config.model, **payload},
+ }
+ classify: Final = (
+ self.litellm_router_instance.aresponses
+ if encrypted_task is not None
+ else self.litellm_router_instance.acompletion
+ )
classifier_timeout_s: Final[float] = llm_config.timeout_ms / 1000
- response: Final[ModelResponse] = await asyncio.wait_for(
- self.litellm_router_instance.acompletion(
+ response: Final[ModelResponse | ResponsesAPIResponse] = await asyncio.wait_for(
+ classify(
model=llm_config.model,
- messages=messages_for_call,
stream=False,
- response_format=response_format,
timeout=classifier_timeout_s,
num_retries=0,
disable_fallbacks=True,
diff --cc tests/test_litellm/litellm_core_utils/test_litellm_logging.py
index 6de0fd3d4e0,6aa77745e3d..aeaa8f18c26
--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@@@ -6801,131 -6801,3 +6801,147 @@@ def test_get_error_information_redacts_
assert "REDACTED" in result["traceback"]
assert "REDACTED" in result["error_message"]
assert result["error_code"] == "400"
+
+
- @pytest.mark.parametrize("provider", ["openai", "azure", "anthropic", "bedrock"])
[email protected]("provider", ["openai", "azure", "anthropic", "bedrock", "responses"])
+async def test_classifier_audit_matches_provider_transport(provider: str) -> None:
+ import json
+
+ from openai import AsyncAzureOpenAI, AsyncOpenAI
+
+ from litellm.litellm_core_utils.classifier_logging import classifier_input_snapshot
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ outbound: Final = asyncio.Queue()
+ logs: Final = asyncio.Queue()
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ outbound.put_nowait(json.loads(request.content))
+ content: Final = '{"tier":"SIMPLE"}'
++ if provider == "responses":
++ from litellm.responses.main import mock_responses_api_response
++
++ return httpx.Response(200, json=mock_responses_api_response(content).model_dump())
+ if provider == "anthropic":
+ return httpx.Response(200, json={
+ "id": "msg-audit", "type": "message", "role": "assistant", "model": "claude-haiku-4-5",
+ "content": [{"type": "text", "text": content}], "stop_reason": "end_turn",
+ "usage": {"input_tokens": 10, "output_tokens": 5},
+ })
+ if provider == "bedrock":
+ return httpx.Response(200, json={
+ "output": {"message": {"role": "assistant", "content": [{"text": content}]}},
+ "stopReason": "end_turn", "usage": {"inputTokens": 10, "outputTokens": 5, "totalTokens": 15},
+ "metrics": {"latencyMs": 1},
+ })
+ return httpx.Response(200, json={
+ "id": "chatcmpl-audit", "object": "chat.completion", "created": 0, "model": "gpt-5.6",
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
+ })
+
+ async def capture(kwargs, response_obj, start_time, end_time):
+ logs.put_nowait(kwargs["standard_logging_object"])
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client:
+ handler: Final = AsyncHTTPHandler()
+ await handler.close()
+ handler.client = http_client
+ client: Final = (
+ AsyncAzureOpenAI(
+ api_key="transport-only", azure_endpoint="https://azure.invalid",
+ api_version="2025-04-01-preview", http_client=http_client,
+ )
+ if provider == "azure" else AsyncOpenAI(api_key="transport-only", http_client=http_client)
+ if provider == "openai" else handler
+ )
+ model: Final = {
+ "openai": "openai/gpt-5.6",
+ "azure": "azure/gpt-5.6",
+ "anthropic": "anthropic/claude-haiku-4-5",
+ "bedrock": "bedrock/anthropic.claude-haiku-4-5-20251001-v1:0",
++ "responses": "openai/gpt-5.6",
+ }[provider]
+
+ async def run(marker: str) -> None:
++ if provider == "responses":
++ await litellm.aresponses(
++ model=model, api_key="transport-only", client=client, max_output_tokens=128,
++ instructions="classifier-rubric", input=marker,
++ metadata={"internal_call_origin": "autorouter_classifier"},
++ proxy_server_request={"body": {}, "originating_request_masked": {"input": f"source-only-{marker}"}},
++ success_callback=[capture], num_retries=0,
++ )
++ return
+ await litellm.acompletion(
+ model=model, api_key="transport-only", client=client, max_tokens=128,
+ aws_access_key_id="transport-only", aws_secret_access_key="transport-only", aws_region_name="us-east-1",
+ messages=[{"role": "system", "content": "classifier-rubric"}, {"role": "user", "content": marker}],
+ metadata={"internal_call_origin": "autorouter_classifier"},
+ proxy_server_request={"body": {}, "originating_request_masked": {"input": f"source-only-{marker}"}},
+ success_callback=[capture], num_retries=0,
+ **({"api_base": "https://azure.invalid", "api_version": "2025-04-01-preview"} if provider == "azure" else {}),
+ **({"extra_body": {"audit_context": "provider-extra"}, "extra_headers": {"X-Audit": "header-only-secret"}}
+ if provider in ("openai", "azure") else {}),
+ )
+
+ await asyncio.gather(run("request-one"), run("request-two"))
+ requests: Final = await asyncio.wait_for(asyncio.gather(outbound.get(), outbound.get()), timeout=10)
+ payloads: Final = await asyncio.wait_for(asyncio.gather(logs.get(), logs.get()), timeout=10)
+ for payload in payloads:
+ snapshot: Final = payload["classifier_input"]
+ assert snapshot in requests
+ assert "source-only" not in json.dumps(snapshot)
+ assert "classifier-rubric" in json.dumps(snapshot)
+ assert "transport-only" not in json.dumps(snapshot)
+ assert "header-only-secret" not in json.dumps(snapshot)
+ assert "SIMPLE" in json.dumps(payload["response"])
+ marker: Final = "request-one" if "request-one" in json.dumps(snapshot) else "request-two"
+ assert payload["originating_request_masked"] == {"input": f"source-only-{marker}"}
+ assert classifier_input_snapshot(snapshot) is not None
- if provider not in ("openai", "azure"):
++ if provider not in ("openai", "azure", "responses"):
+ assert all("system" in request for request in requests)
+
+
[email protected]("redaction", ["none", "global", "request", "header"])
[email protected]("status", ["success", "failure"])
- def test_classifier_audit_obeys_message_logging_before_payload_emission(logging_obj, monkeypatch, redaction, status):
[email protected]("call_type", ["completion", "acompletion", "responses", "aresponses"])
++def test_classifier_audit_obeys_message_logging_before_payload_emission(logging_obj, monkeypatch, redaction, status, call_type):
+ from litellm.litellm_core_utils.litellm_logging import get_standard_logging_object_payload
+
+ monkeypatch.setattr(litellm, "turn_off_message_logging", redaction == "global")
+ params: Final = {
+ "metadata": {"internal_call_origin": "autorouter_classifier", **(
+ {"headers": {"x-litellm-enable-message-redaction": "true"}} if redaction == "header" else {}
+ )},
+ "proxy_server_request": {"body": {}, "originating_request_masked": {"input": "source-only"}},
+ }
++ logging_obj.call_type = call_type
+ logging_obj.model_call_details["litellm_params"] = params
+ logging_obj.model_call_details["standard_callback_dynamic_params"] = (
+ {"turn_off_message_logging": True} if redaction == "request" else {}
+ )
+ logging_obj.pre_call(
+ input=[], api_key=None, additional_args={"complete_input_dict": {"system": "rubric", "messages": []}}
+ )
+ now: Final = datetime.datetime.now()
+ payload: Final = get_standard_logging_object_payload(
- kwargs={**logging_obj.model_call_details, "call_type": "completion"}, init_response_obj={},
++ kwargs={**logging_obj.model_call_details, "call_type": call_type}, init_response_obj={},
+ start_time=now, end_time=now, logging_obj=logging_obj, status=status,
+ )
+ assert payload is not None
+ if redaction == "none":
+ assert payload["classifier_input"] == {"system": "rubric", "messages": []}
+ assert payload["originating_request_masked"] == {"input": "source-only"}
+ else:
+ assert "classifier_input" not in payload
+ assert "originating_request_masked" not in payload
+
+
[email protected]("call_type,origin", [("completion", None), ("aembedding", "autorouter_classifier")])
+def test_classifier_audit_is_not_added_to_other_calls(logging_obj, call_type, origin):
+ logging_obj.call_type = call_type
+ logging_obj.model_call_details["litellm_params"] = {"metadata": {"internal_call_origin": origin}}
+ logging_obj.pre_call(input=[], api_key=None, additional_args={"complete_input_dict": {"input": "embedding"}})
+ assert logging_obj.classifier_input is None
diff --cc tests/test_litellm/router_strategy/test_complexity_router.py
index 45b2faea126,cd8f05d1e41..b8e728c44a9
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@@ -2482,6 -2496,340 +2496,346 @@@ class TestTierLabels
assert set(config.tier_boundaries) == {"simple_medium", "medium_complex", "complex_reasoning"}
+ def _encrypted_agent_task() -> dict[str, object]:
+ return {
+ "type": "agent_message",
+ "author": "/root",
+ "recipient": "/root/child",
+ "content": [
+ {"type": "input_text", "text": "Message Type: NEW_TASK\nTask name: /root/child\nPayload:\nHello"},
+ {"type": "encrypted_content", "encrypted_content": "opaque-provider-task"},
+ ],
+ }
+
+
+ def _native_classifier_response(content: str) -> ResponsesAPIResponse:
+ response: Final = ResponsesAPIResponse(
+ id="resp_classifier",
+ created_at=0,
+ status="completed",
+ output=[{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": content}]}],
+ )
+ response._hidden_params = {"response_cost": 0.0001}
+ return response
+
+
+ def _native_classifier_router(
+ output: str = '{"tier":"REASONING"}',
+ classifier_type: str = "llm",
+ deployment_model: str = "openai/gpt-6-astra",
+ failure: Exception | None = None,
+ native_router: Router | None = None,
+ http_handler: AsyncHTTPHandler | None = None,
+ ) -> tuple[ComplexityRouter, MagicMock]:
+ dependency: Final = MagicMock(
+ aresponses=(
+ native_router.factory_function(partial(litellm.aresponses, client=http_handler), call_type="aresponses")
+ if native_router is not None
+ else AsyncMock(return_value=_native_classifier_response(output), side_effect=failure)
+ ),
+ acompletion=AsyncMock(return_value=_llm_response('{"tier":"SIMPLE"}')),
+ get_model_list=(
+ native_router.get_model_list
+ if native_router is not None
+ else MagicMock(return_value=[{"litellm_params": {"model": deployment_model}}])
+ ),
+ )
+ return (
+ ComplexityRouter(
+ model_name="encrypted-router",
+ litellm_router_instance=dependency,
+ complexity_router_config={
+ "tiers": {"SIMPLE": "cheap-model", "REASONING": "deep-model"},
+ "classifier_type": classifier_type,
+ "classifier_llm_config": {
+ "model": "classifier",
+ "timeout_ms": 5000 if native_router is not None else 100,
+ "reasoning_effort": "low",
+ },
+ "heuristic_first_max_tier": "SIMPLE" if classifier_type == "heuristic_first" else None,
+ "hybrid_boundary_margin": 0.01 if classifier_type == "hybrid" else None,
+ "classifier_fallback": "default_model",
+ "default_model": "deep-model",
+ "session_affinity": False,
+ "deployment_affinity": False,
+ },
+ ),
+ dependency,
+ )
+
+
+ @pytest.fixture
+ async def native_classifier_http() -> AsyncIterator[tuple[AsyncHTTPHandler, MagicMock]]:
+ respond: Final = MagicMock(
+ return_value=httpx.Response(200, json=_native_classifier_response('{"tier":"REASONING"}').model_dump())
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:
+ handler: Final = AsyncHTTPHandler()
+ await handler.client.aclose()
+ handler.client = client
+ yield handler, respond
+
+
+ class TestEncryptedTaskClassifier:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("classifier_type", ["llm", "heuristic_first", "hybrid"])
+ @pytest.mark.parametrize("codex", [True, False])
+ @pytest.mark.parametrize(
+ "reminder",
+ [
+ "<environment_context>cwd=/repo</environment_context>",
+ "<user_instructions>Keep answers concise</user_instructions>",
+ ],
+ )
+ async def test_encrypted_task_detection_uses_request_reminder_markers(
+ self, classifier_type: str, codex: bool, reminder: str
+ ):
+ router, dependency = _native_classifier_router(classifier_type=classifier_type)
+ task: Final = _encrypted_agent_task()
+ request: Final = {
+ "input": [task, {"role": "user", "content": reminder}],
+ "metadata": {"user_agent": "codex-tui" if codex else "curl/8.7.1"},
+ }
+ original: Final = deepcopy(request)
+
+ result: Final = await router.async_pre_routing_hook(model="encrypted-router", request_kwargs=request)
+
+ assert request == original
+ assert result.model == ("deep-model" if codex else "cheap-model")
+ if codex:
+ assert result.routing_decision["cause"] == "llm_classifier"
+ assert result.routing_decision["tier"] == "REASONING"
+ dependency.aresponses.assert_awaited_once()
+ assert dependency.aresponses.call_args.kwargs["input"][-1] == task
+ dependency.acompletion.assert_not_called()
+ else:
+ dependency.aresponses.assert_not_called()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("classifier_type", ["llm", "heuristic_first", "hybrid"])
+ @pytest.mark.parametrize("tier,model", [("SIMPLE", "cheap-model"), ("REASONING", "deep-model")])
+ async def test_encrypted_task_routes_by_native_verdict(self, classifier_type: str, tier: str, model: str):
+ router, dependency = _native_classifier_router(json.dumps({"tier": tier}), classifier_type)
+ task: Final = _encrypted_agent_task()
+ request: Final = {
+ "input": [
+ {"role": "user", "content": "Prior task context"},
+ task,
+ {"type": "function_call_output", "call_id": "call_1", "output": "Tool output"},
+ {"role": "user", "content": "<system-reminder>Injected reminder</system-reminder>"},
+ ],
+ "instructions": "Caller constraints",
++ "proxy_server_request": {"body": {"input": [task], "metadata": {"authorization": "source-secret"}}},
+ "tools": [{"type": "function", "name": "execute"}],
+ "previous_response_id": "resp_parent",
+ "litellm_session_id": "parent-session",
+ "litellm_trace_id": "parent-trace",
+ "turn_off_message_logging": True,
+ "litellm_metadata": {"user_api_key_hash": "caller-key-hash"},
+ }
+ original: Final = deepcopy(request)
+
+ result: Final = await router.async_pre_routing_hook(model="encrypted-router", request_kwargs=request)
+
+ assert result.model == model
+ assert result.routing_decision["tier"] == tier
+ assert result.routing_decision["cause"] == "llm_classifier"
+ assert result.routing_decision["classifier_cost"] == 0.0001
+ assert result.messages is None
+ assert request == original
+ dependency.acompletion.assert_not_called()
+ call: Final = dependency.aresponses.call_args.kwargs
+ assert call["input"][-1] == task
+ assert "opaque-provider-task" not in json.dumps(call["input"][:-1])
+ assert "Prior task context" in json.dumps(call["input"][:-1])
+ assert "Caller constraints" in json.dumps(call["input"][:-1])
+ assert "Caller constraints" not in call["instructions"]
+ assert "SIMPLE" in call["instructions"] and "REASONING" in call["instructions"]
+ assert call["text"]["format"]["schema"]["properties"]["tier"]["enum"] == [
+ "SIMPLE",
+ "MEDIUM",
+ "COMPLEX",
+ "REASONING",
+ ]
+ assert call["text"]["format"]["strict"] is True
+ assert call["reasoning"] == {"effort": "low"}
+ assert call["store"] is False
+ assert call["_require_encrypted_task_support"] is True
+ assert call["stream"] is False
+ assert "tools" not in call and "previous_response_id" not in call
+ assert "messages" not in call and "response_format" not in call
+ assert call["timeout"] == 0.1 and call["num_retries"] == 0 and call["disable_fallbacks"] is True
+ assert call["litellm_session_id"] == "parent-session"
+ assert call["litellm_trace_id"] == "parent-trace"
+ assert call["turn_off_message_logging"] is True
+ assert call["metadata"]["user_api_key_hash"] == "caller-key-hash"
+ assert call["proxy_server_request"]["body"]["input"] == call["input"]
++ assert call["proxy_server_request"]["originating_request_masked"] == {
++ "input": [task], "metadata": {"authorization": "REDACTED"},
++ }
++ assert "source-secret" not in json.dumps(call)
++ assert "originating_request_masked" not in call["proxy_server_request"]["body"]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "items",
+ [
+ [
+ {"type": "reasoning", "encrypted_content": "opaque-history", "summary": []},
+ {"role": "user", "content": "hi"},
+ ],
+ [_encrypted_agent_task(), {"role": "user", "content": "hi"}],
+ [{**_encrypted_agent_task(), "content": [{"type": "input_text", "text": "hi"}]}],
+ [{"role": "user", "content": "gAAAA is plain text"}],
+ [
+ {"role": "user", "content": "hi"},
+ {"type": "function_call_output", "call_id": "call_1", "output": "opaque-provider-task"},
+ ],
+ ],
+ ids=[
+ "historical-reasoning",
+ "older-encrypted-task",
+ "plaintext-agent",
+ "ciphertext-looking-text",
+ "tool-output",
+ ],
+ )
+ async def test_other_asks_keep_chat_classifier(self, items: list[dict[str, object]]):
+ router, dependency = _native_classifier_router()
+
+ result: Final = await router.async_pre_routing_hook(model="encrypted-router", request_kwargs={"input": items})
+
+ assert result.model == "cheap-model"
+ assert result.routing_decision["cause"] == "llm_classifier"
+ dependency.aresponses.assert_not_called()
+ dependency.acompletion.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("output", ["", "not-json", '{"tier":"UNKNOWN"}'])
+ async def test_invalid_native_verdict_uses_existing_fallback(self, output: str):
+ router, dependency = _native_classifier_router(output=output)
+
+ result: Final = await router.async_pre_routing_hook(
+ model="encrypted-router", request_kwargs={"input": [_encrypted_agent_task()]}
+ )
+
+ assert result.model == "deep-model"
+ assert result.routing_decision["cause"] == "default_model_fallback"
+ dependency.aresponses.assert_awaited_once()
+ dependency.acompletion.assert_not_called()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "deployment_model",
+ ["anthropic/test-classifier", "openai/chat_completions/gpt-6-astra", "xai/test-classifier"],
+ )
+ async def test_incompatible_classifier_does_not_flatten_encryption(
+ self, deployment_model: str, native_classifier_http: tuple[AsyncHTTPHandler, MagicMock]
+ ):
+ handler, respond = native_classifier_http
+ native: Final = Router(
+ model_list=[
+ {
+ "model_name": "classifier",
+ "litellm_params": {
+ "model": deployment_model,
+ "api_key": "test-key",
+ "api_base": "https://classifier.test/v1",
+ },
+ }
+ ],
+ num_retries=0,
+ )
+ router, _ = _native_classifier_router(native_router=native, http_handler=handler)
+
+ result: Final = await router.async_pre_routing_hook(
+ model="encrypted-router", request_kwargs={"input": [_encrypted_agent_task()]}
+ )
+
+ assert result.model == "deep-model"
+ assert result.routing_decision["cause"] == "default_model_fallback"
+ respond.assert_not_called()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("blocked", [True, False])
+ async def test_native_classifier_validates_selected_deployment(
+ self, blocked: bool, native_classifier_http: tuple[AsyncHTTPHandler, MagicMock]
+ ):
+ handler, respond = native_classifier_http
+ native: Final = Router(
+ model_list=[
+ {
+ "model_name": "classifier",
+ "litellm_params": {"model": "anthropic/test-classifier", "api_key": "test-key", "order": 0},
+ "model_info": {"id": "incompatible", "blocked": blocked},
+ },
+ {
+ "model_name": "classifier",
+ "litellm_params": {
+ "model": "openai/gpt-6-astra",
+ "api_key": "test-key",
+ "order": 1,
+ "api_base": "https://classifier.test/v1",
+ },
+ "model_info": {"id": "compatible"},
+ },
+ ],
+ num_retries=0,
+ )
+ router, _ = _native_classifier_router(native_router=native, http_handler=handler)
+ task: Final = _encrypted_agent_task()
+
+ result: Final = await router.async_pre_routing_hook(model="encrypted-router", request_kwargs={"input": [task]})
+
+ assert result.model == "deep-model"
+ assert result.routing_decision["cause"] == ("llm_classifier" if blocked else "default_model_fallback")
+ if blocked:
+ respond.assert_called_once()
+ request: Final = respond.call_args.args[0]
+ assert request.url.path == "/v1/responses"
+ body: Final = json.loads(request.content)
+ assert body["input"][-1] == task
+ assert "_require_encrypted_task_support" not in body
+ else:
+ respond.assert_not_called()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("classifier_type", ["llm", "heuristic_first", "hybrid"])
+ @pytest.mark.parametrize(
+ "input_items",
+ [
+ ["unsupported-input-item"],
+ [{**_encrypted_agent_task(), "content": [{"type": "input_text", "text": "hi"}, None]}],
+ ],
+ )
+ async def test_encrypted_detection_does_not_reject_other_input_shapes(
+ self, classifier_type: str, input_items: list[object]
+ ):
+ router, dependency = _native_classifier_router(classifier_type=classifier_type)
+
+ result: Final = await router.aclassify("hi", request_kwargs={"input": input_items})
+
+ assert result.cause != "default_model_fallback"
+ assert result.tier == ComplexityTier.SIMPLE
+ dependency.aresponses.assert_not_called()
+ if classifier_type == "llm":
+ dependency.acompletion.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("failure", [ValueError("invalid_encrypted_content"), TimeoutError("classifier timed out")])
+ async def test_native_provider_failure_uses_existing_fallback(self, failure: Exception):
+ router, dependency = _native_classifier_router(failure=failure)
+
+ result: Final = await router.async_pre_routing_hook(
+ model="encrypted-router", request_kwargs={"input": [_encrypted_agent_task()]}
+ )
+
+ assert result.model == "deep-model"
+ assert result.routing_decision["cause"] == "default_model_fallback"
+ dependency.aresponses.assert_awaited_once()
+ dependency.acompletion.assert_not_called()
+
+
class TestLLMClassifier:
"""Test the LLM-based classifier path (aclassify) and its fallback behavior."""
diff --cc ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.integration.test.tsx
index d538b16d6a2,e0d6a1d41e0..721525268b3
--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.integration.test.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.integration.test.tsx
@@@ -272,57 -272,6 +272,59 @@@ describe("LogDetailContent", () =>
expect(screen.queryByRole("tab", { name: "Request" })).not.toBeInTheDocument();
});
+ it.each(["object", "serialized", "messages only", "null captures"])(
+ "preserves request inspection and copying for classifier logs with %s data",
+ async (shape) => {
+ const user = userEvent.setup();
+ const messages = [{ role: "user", content: "legacy classifier prompt" }];
+ const request = {
+ messages,
+ temperature: 0.5,
+ ...(shape === "null captures" ? { classifier_input: null, originating_request_masked: null } : {}),
+ };
+ const storedRequest = shape === "serialized" ? JSON.stringify(request) : request;
+ const logEntry: Partial<LogEntry> = {
+ call_type: "acompletion",
+ messages,
+ proxy_server_request: shape === "messages only" ? undefined : storedRequest,
+ metadata: { status: "success", internal_call_origin: "autorouter_classifier" },
+ };
+ render(<LogDetailContent logEntry={createLogEntry(logEntry)} />);
+
+ expect(screen.getByText("legacy classifier prompt")).toBeInTheDocument();
+ expect(screen.queryByRole("region", { name: "Classifier input" })).not.toBeInTheDocument();
+ await user.click(screen.getByRole("tab", { name: "JSON", exact: true }));
+ await user.click(screen.getByRole("button", { name: "Copy JSON", exact: true }));
+ expect(await navigator.clipboard.readText()).toBe(
+ JSON.stringify(shape === "messages only" ? messages : request, null, 2),
+ );
+ },
+ );
+
- it.each(["classifier_input", "originating_request_masked"])(
- "shows partial classifier audits when only %s is captured",
- (field) => {
- render(
- <LogDetailContent
- logEntry={createLogEntry({
- call_type: "acompletion",
- proxy_server_request: JSON.stringify({
- [field]: { messages: [{ role: "user", content: "captured prompt" }] },
- }),
- metadata: { status: "success", internal_call_origin: "autorouter_classifier" },
- })}
- />,
- );
++ it.each([
++ ["classifier_input", "acompletion"],
++ ["originating_request_masked", "acompletion"],
++ ["classifier_input", "aresponses"],
++ ["originating_request_masked", "responses"],
++ ])("shows partial classifier audits when only %s is captured for %s", (field, callType) => {
++ render(
++ <LogDetailContent
++ logEntry={createLogEntry({
++ call_type: callType,
++ proxy_server_request: JSON.stringify({
++ [field]: { messages: [{ role: "user", content: "captured prompt" }] },
++ }),
++ metadata: { status: "success", internal_call_origin: "autorouter_classifier" },
++ })}
++ />,
++ );
+
- expect(screen.getByRole("region", { name: "Classifier input" })).toBeInTheDocument();
- expect(screen.getByRole("region", { name: "Originating request, credentials masked" })).toBeInTheDocument();
- expect(screen.getByText("Not captured or message logging disabled")).toBeInTheDocument();
- expect(screen.queryByText("Request & Response")).not.toBeInTheDocument();
- },
- );
++ expect(screen.getByRole("region", { name: "Classifier input" })).toBeInTheDocument();
++ expect(screen.getByRole("region", { name: "Originating request, credentials masked" })).toBeInTheDocument();
++ expect(screen.getByText("Not captured or message logging disabled")).toBeInTheDocument();
++ expect(screen.queryByText("Request & Response")).not.toBeInTheDocument();
++ });
+
it("should display Request and Response tabs when JSON view is selected", async () => {
const user = userEvent.setup();
render(<LogDetailContent logEntry={createLogEntry()} />);
diff --cc ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
index 69be5425ea1,186cb66592b..b5a3412a96f
--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
@@@ -70,12 -68,6 +70,12 @@@ export function LogDetailContent({ logE
const metadata = logEntry.metadata || {};
const hasError = metadata.status === "failure";
const errorInfo = hasError ? metadata.error_information : null;
+ const isClassifier =
+ metadata.internal_call_origin === AUTOROUTER_CLASSIFIER_ORIGIN &&
- (logEntry.call_type === "completion" || logEntry.call_type === "acompletion");
++ ["completion", "acompletion", "responses", "aresponses"].includes(logEntry.call_type);
+ const rawRequest = formatData(logEntry.proxy_server_request || logEntry.messages);
+ const hasClassifierAudit =
+ isClassifier && (rawRequest?.classifier_input != null || rawRequest?.originating_request_masked != null);
const hasMessages = checkHasMessages(logEntry.messages);
const hasResponse = checkHasResponse(logEntry.response);