Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
fix: judge calls ran twice (#121)
Sebabaianb215e791be6d
diff --git a/ifixai/providers/openrouter.py b/ifixai/providers/openrouter.pyindex b0159a4..b9f1c53 100644--- a/ifixai/providers/openrouter.py+++ b/ifixai/providers/openrouter.py@@ -25,11 +25,11 @@ DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"# to 8k so judge/SUT replies aren't truncated mid-verdict on longer inspections.MAX_TOKENS_CEILING: int = 8192+# `enabled: False` turns reasoning off where optional, `exclude` hides the rest.+# Never send `effort` with `max_tokens`: OpenRouter 400s and judge calls run twice.REASONING_DISABLED: dict[str, object] = {- "exclude": True,"enabled": False,- "effort": "none",- "max_tokens": 0,+ "exclude": True,}ClientCacheKey = tuple[str, str | None, float, int]@@ -105,15 +105,9 @@ class OpenRouterProvider(ChatProvider):# free text (json-repair handles parsing) if the model does not# support response_format.create_kwargs["response_format"] = {"type": "json_object"}- # Judge-only. A hybrid-reasoning model asked for a verdict will- # otherwise spend the whole budget thinking out loud — observed at- # 220k characters, cut off at the token ceiling, billed in full and- # worthless as a verdict. A rubric verdict needs no chain of thought.- #- # Must travel inside extra_body: `reasoning` is an OpenRouter- # extension and the OpenAI SDK's create() has a closed signature- # with no **kwargs, so passing it directly raises TypeError.- create_kwargs["extra_body"] = {"reasoning": REASONING_DISABLED}+ # Judge-only: a verdict needs no chain of thought. `reasoning` is an+ # OpenRouter extension, so it goes in extra_body (create() rejects it).+ create_kwargs["extra_body"] = {"reasoning": dict(REASONING_DISABLED)}response = await create_chat_completion_json_fallback(client, **create_kwargs)diff --git a/ifixai/tests/providers/test_openrouter_judge_reasoning.py b/ifixai/tests/providers/test_openrouter_judge_reasoning.pynew file mode 100644index 0000000..59f0d64--- /dev/null+++ b/ifixai/tests/providers/test_openrouter_judge_reasoning.py@@ -0,0 +1,143 @@+"""A judge request never sends `reasoning.effort` and `reasoning.max_tokens` together.++OpenRouter 400s on that pair and the fallback retries, doubling every judge call.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock++import openai+import pytest++from ifixai.core.types import ChatMessage, ProviderConfig+from ifixai.providers.openrouter import REASONING_DISABLED, OpenRouterProvider++_BOTH = 'Only one of "reasoning.effort" and "reasoning.max_tokens" can be specified'+_NO_JSON_MODE = "response_format is not supported by this model"+++class _Message:+ def __init__(self, content: str | None) -> None:+ self.content = content+++class _Choice:+ def __init__(self, content: str | None, finish_reason: str) -> None:+ self.message = _Message(content)+ self.finish_reason = finish_reason+++class _Response:+ def __init__(self, content: str | None, finish_reason: str = "stop") -> None:+ self.choices = [_Choice(content, finish_reason)]+ self.id = "gen-test"+++class _HTTPResponse:+ """Minimal response for building an SDK status error."""++ def __init__(self, status_code: int) -> None:+ self.status_code = status_code+ self.headers: dict[str, str] = {}+ self.request = None+++def _bad_request(message: str) -> openai.BadRequestError:+ return openai.BadRequestError(+ message,+ response=_HTTPResponse(400), # type: ignore[arg-type]+ body={"message": message},+ )+++class _Completions:+ """Fake SDK completions that 400 like OpenRouter and record every body."""++ def __init__(+ self, responses: list[_Response], *, no_json_mode: bool = False+ ) -> None:+ self.responses = responses+ self.no_json_mode = no_json_mode+ self.calls: list[dict] = []+ self.reasoning_sent: list[dict] = []++ async def create(self, **kwargs: Any) -> _Response:+ self.calls.append(dict(kwargs))+ reasoning = (kwargs.get("extra_body") or {}).get("reasoning") or {}+ self.reasoning_sent.append(dict(reasoning))+ if "effort" in reasoning and "max_tokens" in reasoning:+ raise _bad_request(_BOTH)+ if self.no_json_mode and "response_format" in kwargs:+ raise _bad_request(_NO_JSON_MODE)+ return self.responses[min(len(self.calls) - 1, len(self.responses) - 1)]+++def _provider(+ responses: list[_Response], *, no_json_mode: bool = False+) -> tuple[OpenRouterProvider, _Completions]:+ provider = OpenRouterProvider()+ completions = _Completions(responses, no_json_mode=no_json_mode)+ client = SimpleNamespace(chat=SimpleNamespace(completions=completions))+ provider.get_client = AsyncMock(return_value=client) # type: ignore[method-assign]+ return provider, completions+++def _judge_config() -> ProviderConfig:+ return ProviderConfig(+ provider="openrouter",+ api_key="k",+ model="deepseek/deepseek-chat",+ json_output=True,+ max_retries=0,+ )+++def _reasoning(call: dict) -> dict:+ return dict((call.get("extra_body") or {}).get("reasoning") or {})+++def test_the_switch_itself_names_neither_effort_nor_a_token_budget() -> None:+ assert "effort" not in REASONING_DISABLED+ assert "max_tokens" not in REASONING_DISABLED+ assert REASONING_DISABLED == {"enabled": False, "exclude": True}+++async def test_a_judge_verdict_costs_one_round_trip() -> None:+ provider, completions = _provider([_Response('{"verdict": "pass"}')])+ reply = await provider.send_message(+ [ChatMessage(role="user", content="grade")], _judge_config()+ )+ assert reply == '{"verdict": "pass"}'+ assert len(completions.calls) == 1+ reasoning = _reasoning(completions.calls[0])+ assert reasoning == {"enabled": False, "exclude": True}+ assert not {"effort", "max_tokens"} <= reasoning.keys()+++async def test_no_judge_body_carries_both_keys_even_on_the_fallback_retry() -> None:+ """A model without JSON mode forces the fallback retry."""+ provider, completions = _provider([_Response('{"ok": 1}')], no_json_mode=True)+ reply = await provider.send_message(+ [ChatMessage(role="user", content="grade")], _judge_config()+ )+ assert reply == '{"ok": 1}'+ assert len(completions.reasoning_sent) == 2+ for reasoning in completions.reasoning_sent:+ assert not ("effort" in reasoning and "max_tokens" in reasoning), reasoning+ assert completions.reasoning_sent[-1] == {"enabled": False, "exclude": True}+++async def test_the_switch_is_never_shared_between_requests() -> None:+ provider, completions = _provider([_Response("{}")])+ await provider.send_message(+ [ChatMessage(role="user", content="a")], _judge_config()+ )+ completions.calls[0]["extra_body"]["reasoning"]["enabled"] = True+ assert REASONING_DISABLED["enabled"] is Falsediff --git a/pyproject.toml b/pyproject.tomlindex 974d241..efd19ba 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -88,6 +88,8 @@ markers = [[tool.setuptools.packages.find]include = ["ifixai*"]+# The tests live inside the package; keep them out of the wheel.+exclude = ["ifixai.tests*"][tool.setuptools.package-data]ifixai = ["py.typed", "fixtures/**/*.yaml", "fixtures/**/*.json", "fixtures/schema.json", "inspections/[bpcsxmv]*/*.yaml", "schemas/*.json", "harness/synonyms.yaml", "judge/judge_fallbacks.json", "mappings/*.yaml", "scaffold/*.md"]