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(shadow_eval): schema-constrain the judge verdict like the classifier (#37239)

tin-berrib20314efcf96
diff --git a/litellm/integrations/shadow_eval_logger.py b/litellm/integrations/shadow_eval_logger.py
index 1797ac0da14..da02db4e44b 100644
--- a/litellm/integrations/shadow_eval_logger.py
+++ b/litellm/integrations/shadow_eval_logger.py
@@ -16,7 +16,7 @@ from datetime import datetime, timezone
from itertools import groupby
from operator import itemgetter
from types import MappingProxyType
-from typing import TYPE_CHECKING, Final
+from typing import TYPE_CHECKING, Final, Literal
from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, field_validator, model_validator
@@ -33,6 +33,7 @@ from litellm.litellm_core_utils.llm_judge import (
parse_json_verdict,
)
from litellm.litellm_core_utils.redact_messages import should_redact_message_logging
+from litellm.llms.base_llm.base_utils import type_to_response_format_param
from litellm.types.management_endpoints.auto_router_endpoints import ShadowEvalDirection
from litellm.types.utils import SHADOW_EVAL_JUDGE_CALL_ORIGIN, SHADOW_EVAL_ROUTER_CALL_ORIGIN
@@ -306,16 +307,21 @@ Criteria: correctness, completeness, clarity, conciseness.
Return ONLY valid JSON in this exact format, no other text:
{
"preference": "A" | "B" | "tie",
- "confidence": <0.0 to 1.0>,
- "reasoning": "<one sentence>"
+ "confidence": <0.0 to 1.0>
}"""
class PairwiseVerdict(BaseModel):
- """The judge's blind A/B verdict, validated at the parse boundary."""
+ """The judge's blind A/B verdict: the response_format schema sent with the judge call
+ and the validation contract on its reply. Both fields are required and preference is
+ closed over the prompt's labels, so a malformed or truncated reply is an
+ unparseable-verdict error row, never a defaulted or fabricated verdict."""
- preference: str = "tie"
- confidence: float = 0.0
+ preference: Literal["A", "B", "tie"]
+ confidence: float
+
+
+PAIRWISE_JUDGE_RESPONSE_FORMAT: Final = type_to_response_format_param(PairwiseVerdict)
def _sample_hits(request_id: str, job_id: str, percentage: float) -> bool:
@@ -826,6 +832,7 @@ class ShadowEvalLogger(CustomLogger):
judge_messages, # pyright: ignore[reportArgumentType] # plain SDK message dicts
temperature=0,
max_tokens=JUDGE_MAX_OUTPUT_TOKENS,
+ response_format=PAIRWISE_JUDGE_RESPONSE_FORMAT,
metadata=judge_metadata,
)
except Exception as e: # noqa: BLE001 # judge outages become error rows, not crashes
diff --git a/tests/test_litellm/integrations/test_shadow_eval_logger.py b/tests/test_litellm/integrations/test_shadow_eval_logger.py
index ce284a7b201..514d5c6adca 100644
--- a/tests/test_litellm/integrations/test_shadow_eval_logger.py
+++ b/tests/test_litellm/integrations/test_shadow_eval_logger.py
@@ -15,6 +15,7 @@ from litellm.integrations.shadow_eval_logger import (
_MAX_ERROR_CHARS,
_MAX_JUDGE_PROMPT_CHARS,
JUDGE_MAX_OUTPUT_TOKENS,
+ PAIRWISE_JUDGE_RESPONSE_FORMAT,
ActiveShadowEvalJob,
ShadowEvalLogger,
_failure_detail,
@@ -493,6 +494,26 @@ class TestSuccessHookSkipChain:
assert row["error"] is None
assert prisma.db.litellm_shadowevaljob.find_many.await_count == 0
+ async def test_judge_call_carries_the_verdict_schema(self, monkeypatch: pytest.MonkeyPatch):
+ import litellm as litellm_module
+
+ monkeypatch.setattr(litellm_module, "completion_cost", lambda completion_response: 0.005)
+ router = _router()
+ logger = _logger(router=router, prisma=_prisma(), jobs=(_job(),))
+
+ await logger.async_log_success_event(_success_kwargs(), RESPONSE, None, None)
+ await _drain(logger)
+
+ judge_call = next(
+ c.kwargs
+ for c in router.acompletion.call_args_list
+ if c.kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) == SHADOW_EVAL_JUDGE_CALL_ORIGIN
+ )
+ assert judge_call["response_format"] == PAIRWISE_JUDGE_RESPONSE_FORMAT
+ schema = judge_call["response_format"]["json_schema"]["schema"]
+ assert schema["required"] == ["preference", "confidence"]
+ assert schema["properties"]["preference"]["enum"] == ["A", "B", "tie"]
+
async def test_shadow_call_messages_survive_in_place_provider_rewrites(self, monkeypatch: pytest.MonkeyPatch):
"""Provider transforms (anthropic factory, cache-control hook) rewrite messages with
`messages[i] = ...`; the logger's immutable snapshot must never reach them directly."""
@@ -760,8 +781,17 @@ class TestShadowPipeline:
[
(lambda: _failing_router(), "provider exploded", 0.0),
(lambda: _router(judge_json="I prefer response A, definitely"), "unparseable judge verdict", 0.007),
+ (lambda: _router(judge_json='{"preference": "'), "unparseable judge verdict", 0.007),
+ (lambda: _router(judge_json="{}"), "unparseable judge verdict", 0.007),
+ (lambda: _router(judge_json='{"preference": "A", "confidence": "0.8'), "unparseable judge verdict", 0.007),
+ ],
+ ids=[
+ "shadow-call-fails",
+ "judge-verdict-unparseable",
+ "verdict-truncated-before-fields",
+ "verdict-empty-object",
+ "verdict-truncated-inside-confidence",
],
- ids=["shadow-call-fails", "judge-verdict-unparseable"],
)
async def test_failures_become_error_rows_and_keep_billed_judge_cost(
self, router_factory, expected_error, expected_cost, monkeypatch: pytest.MonkeyPatch