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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(guardrails): resolve judge_model credentials via lazy Router lookup in llm_as_a_judge (#34509)
devin-ai-integration[bot]24123269ccb7
diff --git a/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.pyindex a17ca07ae2e..5a72e6872ef 100644--- a/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py@@ -1,8 +1,9 @@"""LLM-as-a-Judge guardrail: uses an LLM to score responses against weighted criteria."""import json+import refrom datetime import datetime-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Union, castimport litellmfrom fastapi import HTTPException@@ -13,6 +14,7 @@ from litellm.types.guardrails import GuardrailEventHooks, SupportedGuardrailIntefrom litellm.types.utils import GenericGuardrailAPIInputs, GuardrailStatusif TYPE_CHECKING:+ from litellm import Routerfrom litellm.types.guardrails import Guardrail, LitellmParamsfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.types.utils import StandardLoggingEvalInformation@@ -30,6 +32,38 @@ Return ONLY valid JSON in this exact format:_VALID_ON_FAILURE = frozenset({"block", "log"})+def _default_router_provider() -> "Router | None":+ try:+ from litellm.proxy.proxy_server import llm_router+ except ImportError:+ return None++ return llm_router+++_JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(.*?)\s*```", re.DOTALL | re.IGNORECASE)+++def _parse_judge_verdict(raw: str) -> Dict[str, Any]:+ """Parse the judge's JSON verdict, tolerating markdown fences and surrounding prose."""+ text = raw.strip()+ fenced = _JSON_FENCE_RE.search(text)+ if fenced is not None:+ text = fenced.group(1).strip()+ parsed: object+ try:+ parsed = json.loads(text)+ except json.JSONDecodeError:+ start = text.find("{")+ end = text.rfind("}")+ if start == -1 or end <= start:+ raise+ parsed = json.loads(text[start : end + 1])+ if not isinstance(parsed, dict):+ raise ValueError("judge response is not a JSON object")+ return cast(Dict[str, Any], parsed) # cast-ok: narrowed to dict by the isinstance guard above++def _extract_text_from_content(content: Any) -> str:"""Return plain text from a message content field (str or multimodal list)."""if isinstance(content, str):@@ -94,6 +128,7 @@ class LLMAsAJudgeGuardrail(CustomGuardrail):on_failure: Literal["block", "log"] = "block",event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks]]] = None,default_on: bool = False,+ router_provider: "Callable[[], Router | None] | None" = None,**kwargs: Any,) -> None:_event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks]]] = None@@ -114,6 +149,7 @@ class LLMAsAJudgeGuardrail(CustomGuardrail):self.criteria = criteriaself.overall_threshold = overall_thresholdself.on_failure = on_failure+ self._router_provider = router_provider or _default_router_provider@classmethoddef get_supported_event_hooks(cls) -> List[GuardrailEventHooks]:@@ -131,14 +167,27 @@ class LLMAsAJudgeGuardrail(CustomGuardrail):"content": _build_judge_prompt(self.criteria, messages, response_text),},]- response = await litellm.acompletion(- model=self.judge_model,- messages=judge_messages,- response_format={"type": "json_object"},- temperature=0,- )+ router = self._router_provider()+ if router is not None and (+ self.judge_model in router.model_group_alias or router.get_model_list(model_name=self.judge_model)+ ):+ response = await router.acompletion(+ model=self.judge_model,+ messages=judge_messages,+ response_format={"type": "json_object"},+ temperature=0,+ num_retries=0,+ fallbacks=[],+ )+ else:+ response = await litellm.acompletion(+ model=self.judge_model,+ messages=judge_messages,+ response_format={"type": "json_object"},+ temperature=0,+ )raw = response.choices[0].message.content or "{}" # type: ignore[union-attr]- return json.loads(raw)+ return _parse_judge_verdict(raw)async def apply_guardrail(self,diff --git a/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py b/tests/test_litellm/proxy/guardrails/test_guardrail_registry.pyindex 14cab50f441..4feadc49160 100644--- a/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py+++ b/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py@@ -407,3 +407,65 @@ def test_repeated_db_sync_does_not_accumulate_runner_instances():finally:for cb_list, snapshot in zip(lists, snapshots):cb_list[:] = snapshot+++def _judge_guardrail(guardrail_id: str) -> Guardrail:+ return Guardrail(+ guardrail_id=guardrail_id,+ guardrail_name="quality-judge",+ litellm_params={+ "guardrail": "llm_as_a_judge",+ "mode": "post_call",+ "judge_model": "my-judge-alias",+ "overall_threshold": 80,+ "on_failure": "log",+ "criteria": [{"name": "helpfulness", "weight": 100, "description": "helpful?"}],+ },+ )+++def test_db_synced_judge_guardrail_uses_lazy_router_provider():+ """A judge guardrail created/synced through a DB path must resolve the active+ Router lazily at call time (issue: UI-created guardrails failed open because the+ Router was captured at construction; a guardrail created before the Router+ existed captured None and never recovered). Asserting the default provider is+ wired guarantees the instance reads the live global rather than a stale value."""+ from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import (+ LLMAsAJudgeGuardrail,+ _default_router_provider,+ )++ handler = InMemoryGuardrailHandler()++ lists = _all_callback_lists()+ snapshots = [list(cb_list) for cb_list in lists]+ try:+ handler.sync_guardrail_from_db(_judge_guardrail("judge-db"))++ instance = handler.guardrail_id_to_custom_guardrail["judge-db"]+ assert isinstance(instance, LLMAsAJudgeGuardrail)+ assert instance._router_provider is _default_router_provider+ finally:+ for cb_list, snapshot in zip(lists, snapshots):+ cb_list[:] = snapshot+++def test_reinitialized_judge_guardrail_uses_lazy_router_provider():+ from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import (+ LLMAsAJudgeGuardrail,+ _default_router_provider,+ )++ handler = InMemoryGuardrailHandler()++ lists = _all_callback_lists()+ snapshots = [list(cb_list) for cb_list in lists]+ try:+ handler.reinitialize_guardrail(_judge_guardrail("judge-reinit"), source="db")++ instance = handler.guardrail_id_to_custom_guardrail["judge-reinit"]+ assert isinstance(instance, LLMAsAJudgeGuardrail)+ assert instance._router_provider is _default_router_provider+ finally:+ for cb_list, snapshot in zip(lists, snapshots):+ cb_list[:] = snapshotdiff --git a/tests/test_litellm/proxy/guardrails/test_llm_as_a_judge.py b/tests/test_litellm/proxy/guardrails/test_llm_as_a_judge.pyindex c9fde4ffbae..45dec4ddb2d 100644--- a/tests/test_litellm/proxy/guardrails/test_llm_as_a_judge.py+++ b/tests/test_litellm/proxy/guardrails/test_llm_as_a_judge.py@@ -10,6 +10,7 @@ from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import (LLMAsAJudgeGuardrail,_build_judge_prompt,_extract_text_from_content,+ _parse_judge_verdict,initialize_guardrail,)@@ -198,6 +199,86 @@ async def test_apply_guardrail_log_mode_does_not_block(mock_completion):assert request_data["metadata"]["eval_information"]["passed"] is False+# ---------------------------------------------------------------------------+# _parse_judge_verdict — tolerate fenced/prose-wrapped JSON+# ---------------------------------------------------------------------------+++def test_parse_judge_verdict_plain_json():+ assert _parse_judge_verdict('{"overall_score": 90}')["overall_score"] == 90+++def test_parse_judge_verdict_strips_json_fence_and_prose():+ raw = 'Here is my verdict:\n```json\n{"overall_score": 42}\n```\nHope that helps'+ assert _parse_judge_verdict(raw)["overall_score"] == 42+++def test_parse_judge_verdict_strips_bare_fence():+ raw = '```\n{"overall_score": 7}\n```'+ assert _parse_judge_verdict(raw)["overall_score"] == 7+++def test_parse_judge_verdict_extracts_json_from_surrounding_prose():+ raw = 'Sure, here it is: {"overall_score": 55} let me know'+ assert _parse_judge_verdict(raw)["overall_score"] == 55+++def test_parse_judge_verdict_reraises_when_no_json():+ with pytest.raises(json.JSONDecodeError):+ _parse_judge_verdict("no json here")+++def test_parse_judge_verdict_rejects_json_non_object():+ """Valid JSON that is not an object (e.g. a bare list) raises ValueError."""+ with pytest.raises(ValueError):+ _parse_judge_verdict("[1, 2, 3]")+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion")+async def test_apply_guardrail_enforces_fenced_verdict(mock_completion):+ """A failing verdict wrapped in a code fence blocks with a 422."""+ fenced = "```json\n" + json.dumps(_make_verdict_response(50.0)) + "\n```"+ mock_completion.return_value = MagicMock(choices=[MagicMock(message=MagicMock(content=fenced))])+ guardrail = _make_guardrail(overall_threshold=80.0, on_failure="block", router_provider=lambda: None)+ inputs = {"texts": ["bad response"]}+ request_data: dict = {"messages": [], "metadata": {}}+ with pytest.raises(HTTPException) as exc_info:+ await guardrail.apply_guardrail(inputs, request_data, "response")+ assert exc_info.value.status_code == 422+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion")+async def test_apply_guardrail_non_object_verdict_fails_open_with_status(mock_completion):+ """A non-object verdict fails open and logs guardrail_failed_to_respond."""+ mock_completion.return_value = MagicMock(+ choices=[MagicMock(message=MagicMock(content='[{"overall_score": 50}]'))]+ )+ guardrail = _make_guardrail(overall_threshold=80.0, on_failure="block", router_provider=lambda: None)+ inputs = {"texts": ["response"]}+ request_data: dict = {"messages": [], "metadata": {}}+ result = await guardrail.apply_guardrail(inputs, request_data, "response")+ assert result is inputs+ logged = request_data["metadata"]["standard_logging_guardrail_information"]+ assert logged[0]["guardrail_status"] == "guardrail_failed_to_respond"+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion")+async def test_apply_guardrail_parses_fenced_json_verdict(mock_completion):+ """Fencing-prone judge models wrap the verdict in a ```json fence; the guardrail+ must parse it and evaluate rather than failing open on json.loads."""+ fenced = "```json\n" + json.dumps(_make_verdict_response(90.0)) + "\n```"+ mock_completion.return_value = MagicMock(choices=[MagicMock(message=MagicMock(content=fenced))])+ guardrail = _make_guardrail(overall_threshold=80.0)+ inputs = {"texts": ["good response"]}+ request_data: dict = {"messages": [], "metadata": {}}+ result = await guardrail.apply_guardrail(inputs, request_data, "response")+ assert result is inputs+ assert request_data["metadata"]["eval_information"]["passed"] is True++@pytest.mark.asyncio@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion")async def test_apply_guardrail_judge_error_fails_open(mock_completion):@@ -209,6 +290,167 @@ async def test_apply_guardrail_judge_error_fails_open(mock_completion):assert result is inputs+# ---------------------------------------------------------------------------+# judge_model credential/provider resolution — route through the proxy Router+# ---------------------------------------------------------------------------+++def _judge_response_mock() -> MagicMock:+ return MagicMock(choices=[MagicMock(message=MagicMock(content=json.dumps(_make_verdict_response(90.0))))])+++def _real_router(model_list, **router_kwargs):+ """Build a real Router so the router-membership decision is exercised for+ real (wildcards, model_group_alias, exact names), stubbing only the outbound+ completion so no network call is made."""+ from litellm import Router++ router = Router(model_list=model_list, **router_kwargs)+ router.acompletion = AsyncMock(return_value=_judge_response_mock())+ return router+++ "model_list, router_kwargs, judge_model",+ [+ (+ [{"model_name": "my-judge-alias", "litellm_params": {"model": "anthropic/claude-sonnet-4-6", "api_key": "sk-ant-test"}}],+ {},+ "my-judge-alias",+ ),+ (+ [{"model_name": "anthropic/*", "litellm_params": {"model": "anthropic/*", "api_key": "sk-ant-test"}}],+ {},+ "anthropic/claude-sonnet-4-6",+ ),+ (+ [{"model_name": "backing-group", "litellm_params": {"model": "anthropic/claude-sonnet-4-6", "api_key": "sk-ant-test"}}],+ {"model_group_alias": {"my-judge-alias": "backing-group"}},+ "my-judge-alias",+ ),+ (+ [{"model_name": "backing-group", "litellm_params": {"model": "anthropic/claude-sonnet-4-6", "api_key": "sk-ant-test"}}],+ {"model_group_alias": {"my-judge-alias": {"model": "backing-group", "hidden": True}}},+ "my-judge-alias",+ ),+ ],+ ids=["plain-deployment", "wildcard-route", "model-group-alias", "hidden-model-group-alias"],+)+@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion", new_callable=AsyncMock)+async def test_judge_routes_through_router_for_router_served_model(+ mock_sdk_completion, model_list, router_kwargs, judge_model+):+ """Any judge_model the Router can serve must resolve its credentials via the+ Router. Wildcard and alias shapes regress the naive `judge_model in+ get_model_names()` check, which reports patterns/aliases literally and so+ routes a servable model to the SDK, where deployment creds do not resolve."""+ router = _real_router(model_list, **router_kwargs)+ guardrail = _make_guardrail(judge_model=judge_model, router_provider=lambda: router)+ inputs = {"texts": ["good response"]}+ request_data: dict = {"messages": [{"role": "user", "content": "hi"}], "metadata": {}}++ result = await guardrail.apply_guardrail(inputs, request_data, "response")++ assert result is inputs+ router.acompletion.assert_awaited_once()+ call_kwargs = router.acompletion.await_args.kwargs+ assert call_kwargs["model"] == judge_model+ assert call_kwargs["num_retries"] == 0+ assert call_kwargs["fallbacks"] == []+ mock_sdk_completion.assert_not_called()+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion", new_callable=AsyncMock)+async def test_judge_call_falls_back_to_sdk_when_model_not_in_router(mock_sdk_completion):+ """A judge_model the Router cannot serve (e.g. a raw provider model resolved+ from the environment) must fall back to the SDK."""+ mock_sdk_completion.return_value = _judge_response_mock()+ router = _real_router(+ [{"model_name": "some-other-model", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-test"}}]+ )+ guardrail = _make_guardrail(judge_model="gpt-4o-mini", router_provider=lambda: router)+ inputs = {"texts": ["good response"]}+ request_data: dict = {"messages": [], "metadata": {}}++ result = await guardrail.apply_guardrail(inputs, request_data, "response")++ assert result is inputs+ router.acompletion.assert_not_called()+ mock_sdk_completion.assert_awaited_once()+ assert mock_sdk_completion.await_args.kwargs["model"] == "gpt-4o-mini"+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion", new_callable=AsyncMock)+async def test_judge_call_uses_sdk_when_no_router(mock_sdk_completion):+ mock_sdk_completion.return_value = _judge_response_mock()+ guardrail = _make_guardrail(judge_model="gpt-4o-mini", router_provider=lambda: None)+ inputs = {"texts": ["good response"]}+ request_data: dict = {"messages": [], "metadata": {}}++ result = await guardrail.apply_guardrail(inputs, request_data, "response")++ assert result is inputs+ mock_sdk_completion.assert_awaited_once()+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion", new_callable=AsyncMock)+async def test_judge_resolves_router_lazily_per_call(mock_sdk_completion):+ """The Router is resolved at call time, not captured at construction. A+ guardrail built before the proxy Router exists (provider returns None) starts+ routing through the Router as soon as it is available, with no re-init. This+ regresses the config-less DB-backed startup order where the guardrail was+ created while the global Router was still None and then never recovered."""+ mock_sdk_completion.return_value = _judge_response_mock()+ holder: dict = {"router": None}+ guardrail = _make_guardrail(judge_model="my-judge-alias", router_provider=lambda: holder["router"])++ await guardrail.apply_guardrail({"texts": ["r"]}, {"messages": [], "metadata": {}}, "response")+ mock_sdk_completion.assert_awaited_once()++ holder["router"] = _real_router(+ [{"model_name": "my-judge-alias", "litellm_params": {"model": "anthropic/claude-sonnet-4-6", "api_key": "sk-ant-test"}}]+ )+ await guardrail.apply_guardrail({"texts": ["r"]}, {"messages": [], "metadata": {}}, "response")+ holder["router"].acompletion.assert_awaited_once()+ mock_sdk_completion.assert_awaited_once()+++def test_default_router_provider_returns_none_when_proxy_not_importable():+ """If the proxy dependency set is not importable, the provider must return None+ so the judge falls back to the SDK rather than the ImportError being swallowed+ by the fail-open handler and the guardrail silently no-opping."""+ import sys++ from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import _default_router_provider++ with patch.dict(sys.modules, {"litellm.proxy.proxy_server": None}):+ assert _default_router_provider() is None+++def test_default_router_provider_reads_global_router():+ """The default provider must read the live proxy global so the router is+ resolved lazily rather than captured."""+ from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import _default_router_provider++ sentinel = object()+ with patch("litellm.proxy.proxy_server.llm_router", sentinel):+ assert _default_router_provider() is sentinel+++@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.logging_callback_manager")+def test_initialize_guardrail_uses_default_router_provider(mock_mgr):+ from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import _default_router_provider++ lp = _make_litellm_params()+ g = _make_guardrail_dict(judge_model="my-judge-alias")+ instance = initialize_guardrail(lp, g)+ assert instance._router_provider is _default_router_provider++@pytest.mark.asyncio@patch("litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge.litellm.acompletion")async def test_apply_guardrail_clamps_score(mock_completion):