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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_shadow_eval_judge_output_cap

moe-berrid1fd3a34578a
diff --cc litellm/integrations/shadow_eval_logger.py
index fb75ef74db9,b28d21ba1ca..6c4c25c35fe
--- a/litellm/integrations/shadow_eval_logger.py
+++ b/litellm/integrations/shadow_eval_logger.py
@@@ -345,22 -418,6 +418,20 @@@ def _failure_detail(e: BaseException) -
return f"{type(e).__name__}{location}: {e}"
+def _judge_reply_shape(response: object) -> str:
+ """How an unparseable judge reply was shaped. The parser's own message cannot separate a
+ judge that answered with nothing from one truncated mid-object, and those want opposite
+ fixes. Shape only, never the reply text: the judge quotes the sampled turns it compares,
+ and no attempt row carries sampled content today."""
- try:
- choice: Final = response["choices"][0] # pyright: ignore[reportIndexIssue] # judge replies are subscriptable payloads
- content: Final = choice["message"]["content"]
- finish: Final = choice.get("finish_reason") or "unknown"
- except (AttributeError, KeyError, IndexError, TypeError):
++ read: Final = _chat_message_reader(response)
++ if read is None:
+ return "unreadable judge reply"
- served: Final = str(getattr(response, "model", None) or "unknown")
++ content: Final = read("content")
++ served: Final = str(_field_reader(response)("model") or "unknown")
+ body: Final = f"{len(str(content))} chars" if content else "no content"
- return f"finish_reason={finish}, content={body}, model={served}"
++ return f"finish_reason={_chat_finish_reason(response)}, content={body}, model={served}"
+
+
def _call_cost(response: object) -> float:
"""Price one eval-arm call with the figure the spend pipeline bills: the router client
stamps _hidden_params.response_cost from the deployment's own pricing, which the public
diff --cc tests/test_litellm/integrations/test_shadow_eval_logger.py
index dbc6d4ec915,f273a285d49..4c45b4c2137
--- a/tests/test_litellm/integrations/test_shadow_eval_logger.py
+++ b/tests/test_litellm/integrations/test_shadow_eval_logger.py
@@@ -120,48 -126,39 +126,81 @@@ def _router
return router
+ def _shadow_reply_router(message, finish_reason="stop", routed_model="cheap-model"):
+ """A router whose shadow arm answers with a caller-supplied message, so a reply that
+ yields no judgeable text can be posed as the two different things it can be: an arm
+ that chose a tool, or an arm that returned nothing."""
+ router = MagicMock()
+ router.model_group_alias = {}
+ router.get_model_list = MagicMock(return_value=[{"litellm_params": {"model": "openai/gpt-4o-mini"}}])
+
+ async def acompletion(**kwargs):
+ if kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN:
+ return {"choices": [{"message": {"content": '{"preference": "A", "confidence": 0.9}'}}]}
+ kwargs["metadata"]["routing_decision"] = {"tier_label": "SIMPLE", "routed_model": routed_model}
+ return {"choices": [{"message": message, "finish_reason": finish_reason}]}
+
+ router.acompletion = MagicMock(side_effect=acompletion)
+ return router
+
+
+def _reasoning_judge_router(
+ reasoning_tokens: int, verdict: str = '{"preference": "A", "confidence": 0.9}'
+) -> MagicMock:
+ """A router whose judge arm reasons before it answers, the way a deployment carrying an
+ elevated reasoning_effort does: reasoning bills against the caller's own max_tokens and
+ the reply is cut off at that cap. One character stands in for one token."""
+ router = MagicMock()
+ router.model_group_alias = {}
+ router.get_model_list = MagicMock(return_value=[{"litellm_params": {"model": "openai/gpt-4o-mini"}}])
+
+ async def acompletion(**kwargs):
+ if kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) == SHADOW_EVAL_ROUTER_CALL_ORIGIN:
+ kwargs["metadata"]["routing_decision"] = {"tier_label": "SIMPLE", "routed_model": "cheap-model"}
+ return {"choices": [{"message": {"content": "shadow answer"}}]}
+ budget_for_the_answer = kwargs["max_tokens"] - reasoning_tokens
+ return {"choices": [{"message": {"content": verdict[: max(0, budget_for_the_answer)]}}]}
+
+ router.acompletion = MagicMock(side_effect=acompletion)
+ return router
+
+
+def _judge_reply_router(content: str | None, finish_reason: str = "stop", served_model: str = "judge-pick") -> MagicMock:
+ """A router whose judge arm returns a caller-shaped reply, so the shapes that all land
+ on the same parser error can be posed apart: no content at all, versus JSON cut off
+ mid-object."""
+ router = MagicMock()
+ router.model_group_alias = {}
+ router.get_model_list = MagicMock(return_value=[{"litellm_params": {"model": "openai/gpt-4o-mini"}}])
+
+ async def acompletion(**kwargs):
+ if kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) == SHADOW_EVAL_ROUTER_CALL_ORIGIN:
+ kwargs["metadata"]["routing_decision"] = {"tier_label": "SIMPLE", "routed_model": "cheap-model"}
+ return {"choices": [{"message": {"content": "shadow answer"}}]}
+ return ModelResponse(
+ model=served_model,
+ choices=[{"index": 0, "finish_reason": finish_reason, "message": {"role": "assistant", "content": content}}],
+ )
+
+ router.acompletion = MagicMock(side_effect=acompletion)
+ return router
+
+
+ TOOL_CALL_MESSAGE = {
+ "content": None,
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}],
+ }
+
+ CUSTOM_TOOL_CALL_MESSAGE = {
+ "content": None,
+ "tool_calls": [
+ ChatCompletionMessageCustomToolCall(
+ id="c2", custom=ChatCompletionCustomToolCallPayload(name="exec_sql", input="select 1")
+ )
+ ],
+ }
+
+
def _spend_counter(store=None):
"""In-memory stand-in for the proxy's cross-pod spend counter: reads take the max of
the counter and the caller's fallback, exactly like get_current_spend does for a key
@@@ -1249,34 -1211,206 +1326,234 @@@ class TestShadowPipeline
assert row["shadow_cost"] == 0.007
assert logger._test_counter["spend:shadow_eval:job-1"] == 0.007
+ async def test_the_judge_output_cap_leaves_room_for_a_reasoning_judge(self):
+ """The output cap covers reasoning tokens as well as the answer, and a judge_model
+ deployment carrying an elevated reasoning_effort spends that budget before it writes
+ anything. A cap sized for the verdict JSON alone goes entirely to reasoning and the
+ reply arrives empty, which the attempt records as an unparseable verdict rather than
+ a result. The judge here burns a reasoning budget a live claude-sonnet-5 call was
+ measured at, so the cap has to clear it for the verdict to survive."""
+ reasoning_tokens = 2000
+ logger = _logger(router=_reasoning_judge_router(reasoning_tokens), prisma=(prisma := _prisma()))
+
+ await logger._run_shadow_eval(
+ job=_job(),
+ request_id="req-1",
+ messages=({"role": "user", "content": "hi"},),
+ real_text="real answer",
+ real_model="claude-opus",
+ real_cost=0.0,
+ real_classifier_cost=0.0,
+ real_cache_hit=False,
+ control_tier=None,
+ shadow_params={},
+ parent_metadata={},
+ )
+
+ row = prisma.db.litellm_shadowevalattempt.create.call_args.kwargs["data"]
+ assert row["outcome"] in ("real", "shadow", "tie"), row["error"]
+ assert row["error"] is None
+
+ async def _no_text_error(self, router) -> str:
+ prisma = _prisma()
+ await _logger(router=router, prisma=prisma)._run_shadow_eval(
+ job=_job(),
+ request_id="req-1",
+ messages=({"role": "user", "content": "hi"},),
+ real_text="real answer",
+ real_model="claude-opus",
+ real_cost=0.0,
+ real_classifier_cost=0.0,
+ real_cache_hit=False,
+ control_tier=None,
+ shadow_params={},
+ parent_metadata={},
+ )
+ row = prisma.db.litellm_shadowevalattempt.create.call_args.kwargs["data"]
+ assert row["outcome"] == "error"
+ return row["error"]
+
+ async def _judged_shadow_row(self, router: MagicMock, shadow_params: dict | None = None) -> dict:
+ prisma = _prisma()
+ await _logger(router=router, prisma=prisma)._run_shadow_eval(
+ job=_job(),
+ request_id="req-1",
+ messages=({"role": "user", "content": "hi"},),
+ real_text="real answer",
+ real_model="claude-opus",
+ real_cost=0.0,
+ real_classifier_cost=0.0,
+ real_cache_hit=False,
+ control_tier=None,
+ shadow_params=shadow_params or {},
+ parent_metadata={},
+ )
+ return prisma.db.litellm_shadowevalattempt.create.call_args.kwargs["data"]
+
+ async def test_a_tool_call_shadow_reply_is_judged_rather_than_discarded(self):
+ """An arm that calls a tool where the real model wrote prose has answered, it just
+ answered by acting. Dropping that turn threw away the comparison the job exists to
+ make, and on agentic traffic it threw away most of them, so the tool call is
+ serialized into text and judged like any other response."""
+ row = await self._judged_shadow_row(_shadow_reply_router(TOOL_CALL_MESSAGE, finish_reason="tool_calls"))
+
+ assert row["outcome"] != "error"
+ assert row["error"] is None
+ assert row["confidence"] == 0.9
+
+ async def test_a_tool_call_reaches_the_judge_as_readable_text(self):
+ """The judge only ever sees strings, so a tool call has to arrive as its name and
+ arguments. A serialization that dropped either would ask the judge to score a
+ response it cannot tell apart from any other tool call."""
+ router = _shadow_reply_router(TOOL_CALL_MESSAGE, finish_reason="tool_calls")
+ await self._judged_shadow_row(router)
+
+ judge_prompt = next(
+ call.kwargs["messages"][-1]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "[tool call] Read({})" in judge_prompt
+
+ async def test_the_judge_sees_what_tools_were_available(self):
+ """Scoring whether a tool call was the right response needs to know what else the
+ arm could have called instead. Without the tool list, the judge can score the
+ arguments but not whether Read, specifically, was the correct choice."""
+ router = _shadow_reply_router(TOOL_CALL_MESSAGE, finish_reason="tool_calls")
+ tools = [
+ {"type": "function", "function": {"name": "Read", "description": "read a file from disk"}},
+ {"type": "function", "function": {"name": "Bash", "description": "run a shell command"}},
+ ]
+ await self._judged_shadow_row(router, shadow_params={"tools": tools})
+
+ judge_prompt = next(
+ call.kwargs["messages"][-1]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "Read: read a file from disk" in judge_prompt
+ assert "Bash: run a shell command" in judge_prompt
+
+ async def test_a_custom_tool_definition_is_named_for_the_judge(self):
+ """A custom tool definition nests name and description under `custom`, not
+ `function`, so reading only `function` renders every one of them as unnamed and
+ tells the judge nothing about what the arm could have called."""
+ from openai.types.chat import ChatCompletionCustomToolParam
+
+ router = _shadow_reply_router(TOOL_CALL_MESSAGE, finish_reason="tool_calls")
+ tools = [
+ ChatCompletionCustomToolParam(
+ type="custom",
+ custom={"name": "exec_sql", "description": "run a read-only sql query"},
+ )
+ ]
+ await self._judged_shadow_row(router, shadow_params={"tools": tools})
+
+ judge_prompt = next(
+ call.kwargs["messages"][-1]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "exec_sql: run a read-only sql query" in judge_prompt
+ assert "unnamed" not in judge_prompt
+
+ @pytest.mark.parametrize("shadow_params", [{}, {"tools": []}], ids=["omitted", "empty-list"])
+ async def test_no_tool_definitions_section_when_the_turn_offered_no_tools(self, shadow_params):
+ """Padding every judge prompt with an empty tools section wastes budget on the
+ turns, still the majority, that never offered one, whether tools was left out of
+ the request entirely or sent as an empty list."""
+ router = _shadow_reply_router({"content": "hello"}, finish_reason="stop")
+ await self._judged_shadow_row(router, shadow_params=shadow_params)
+
+ judge_prompt = next(
+ call.kwargs["messages"][-1]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "Tools available" not in judge_prompt
+
+ async def test_a_custom_tool_call_serializes_its_name_and_input(self):
+ """Custom tool calls carry no `function` key: name and arguments live under
+ `custom`, so reading only `function` serializes every one of them as unnamed."""
+ router = _shadow_reply_router(CUSTOM_TOOL_CALL_MESSAGE, finish_reason="tool_calls")
+ await self._judged_shadow_row(router)
+
+ judge_prompt = next(
+ call.kwargs["messages"][-1]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "[tool call] exec_sql(select 1)" in judge_prompt
+
+ async def test_the_judge_is_told_a_tool_call_is_not_a_defect(self):
+ """The judge scores on completeness and clarity. Handed a tool call with no
+ instruction, it marks it down for not reading like an answer, which would bias
+ every verdict against a tool-calling arm on exactly the traffic that calls tools."""
+ router = _shadow_reply_router(TOOL_CALL_MESSAGE, finish_reason="tool_calls")
+ await self._judged_shadow_row(router)
+
+ system_prompt = next(
+ call.kwargs["messages"][0]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "tool call" in system_prompt
+ assert "not a defect" in system_prompt
+
+ async def test_prose_written_alongside_a_tool_call_survives_into_the_verdict(self):
+ """Some providers write a sentence before acting. Serializing only the call would
+ hide half of what the arm actually said from the judge."""
+ router = _shadow_reply_router(
+ {"content": "Let me look that up.", "tool_calls": TOOL_CALL_MESSAGE["tool_calls"]},
+ finish_reason="tool_calls",
+ )
+ await self._judged_shadow_row(router)
+
+ judge_prompt = next(
+ call.kwargs["messages"][-1]["content"]
+ for call in router.acompletion.call_args_list
+ if call.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN
+ )
+
+ assert "Let me look that up. [tool call] Read({})" in judge_prompt
+
+ async def test_an_empty_shadow_reply_names_the_finish_reason_and_the_routed_model(self):
+ """A reply that really carried no text is diagnosable only if the row says what
+ the arm was doing when it produced none: a truncated turn and a model that answers
+ with nothing are different faults with different fixes."""
+ error = await self._no_text_error(
+ _shadow_reply_router({"content": ""}, finish_reason="length", routed_model="some-model")
+ )
+
+ assert "empty response" in error
+ assert "finish_reason=length" in error
+ assert "model=some-model" in error
+
+ async def test_no_text_errors_stay_groupable_across_models_and_finish_reasons(self):
+ """Operators read these rows by grouping on the error text, which is how a job's
+ failures collapse to a handful of causes. Every varying part therefore has to sit
+ behind the first semicolon, or each row becomes its own group and the count that
+ made the problem visible stops existing."""
+ first = await self._no_text_error(
+ _shadow_reply_router({"content": None}, finish_reason="length", routed_model="model-a")
+ )
+ second = await self._no_text_error(
+ _shadow_reply_router(
+ {"content": ""},
+ finish_reason="stop",
+ routed_model="model-b",
+ )
+ )
+
+ assert first != second
+ assert first.split(";")[0] == second.split(";")[0]
+
async def test_a_pipeline_error_after_the_shadow_call_keeps_its_billed_cost(self, monkeypatch: pytest.MonkeyPatch):
"""An unexpected error between the billed shadow call and the attempt write must
still record the shadow cost, or the per-key dollar gate undercounts forever."""