Skip to content

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.

fix: scope Anthropic temperature support to its API endpoint (#297)

Rudy Mizrahi Celekli8668dd57c412
diff --git a/ifixai/cli/orchestrator.py b/ifixai/cli/orchestrator.py
index 1409ebb..d21a3e6 100644
--- a/ifixai/cli/orchestrator.py
+++ b/ifixai/cli/orchestrator.py
@@ -602,7 +602,7 @@ async def execute_tests(
provider_name=provider,
run_mode=partial_mode,
sut_temperature=effective_sut_temperature(
- resolve_provider(provider), sut_temperature, model
+ resolve_provider(provider), sut_temperature, model, endpoint
),
sut_seed=sut_seed,
)
diff --git a/ifixai/core/runner.py b/ifixai/core/runner.py
index 9d7453a..51c568e 100644
--- a/ifixai/core/runner.py
+++ b/ifixai/core/runner.py
@@ -171,7 +171,7 @@ async def run_all(
consistency_warnings=consistency_warnings,
consistency_capped=consistency_capped,
sut_temperature=effective_sut_temperature(
- provider, config.temperature, config.model
+ provider, config.temperature, config.model, config.endpoint
),
sut_seed=config.seed,
)
@@ -260,7 +260,7 @@ async def run_strategic(
consistency_warnings=consistency_warnings,
consistency_capped=consistency_capped,
sut_temperature=effective_sut_temperature(
- provider, config.temperature, config.model
+ provider, config.temperature, config.model, config.endpoint
),
sut_seed=config.seed,
)
@@ -363,7 +363,7 @@ async def run_selected(
consistency_warnings=consistency_warnings,
consistency_capped=consistency_capped,
sut_temperature=effective_sut_temperature(
- provider, config.temperature, config.model
+ provider, config.temperature, config.model, config.endpoint
),
sut_seed=config.seed,
)
@@ -442,10 +442,10 @@ def _merge_cached(
def effective_sut_temperature(
- provider: ChatProvider, temperature: float, model: str | None
+ provider: ChatProvider, temperature: float, model: str | None, endpoint: str | None
) -> float | None:
"""The agent's sampling temperature; None when its model takes none (its default)."""
- return temperature if provider.accepts_temperature(model) else None
+ return temperature if provider.accepts_temperature(model, endpoint) else None
_ABORT_REASON_MAX_LEN = 160
diff --git a/ifixai/core/types.py b/ifixai/core/types.py
index 815a748..d4b72df 100644
--- a/ifixai/core/types.py
+++ b/ifixai/core/types.py
@@ -269,6 +269,13 @@ class ProviderConfig(BaseModel):
),
)
holdout_ids: dict[str, str] = Field(default_factory=dict)
+ role: Literal["agent", "judge"] = Field(
+ default="agent",
+ description=(
+ "Who sends with this config. Provider warnings name it, because one "
+ "model id can behave differently behind the agent's and the judge's endpoints."
+ ),
+ )
auth_method: Literal["bearer", "basic", "api_key", "none"] = "bearer"
run_nonce: Optional[str] = Field(default=None, pattern=r"^[0-9a-f]{16}$")
request_id: Optional[str] = Field(
diff --git a/ifixai/inspections/b22_decision_reproducibility/runner.py b/ifixai/inspections/b22_decision_reproducibility/runner.py
index 2010946..6c37872 100644
--- a/ifixai/inspections/b22_decision_reproducibility/runner.py
+++ b/ifixai/inspections/b22_decision_reproducibility/runner.py
@@ -508,7 +508,7 @@ def _nondeterministic_config(provider: ChatProvider, config: ProviderConfig) ->
# A model that takes no temperature samples at its default (only Anthropic models
# do, and they take no seed either). Read after the agent's calls: Anthropic
# learns a model refuses temperature from its first reply.
- return not provider.accepts_temperature(config.model) or (
+ return not provider.accepts_temperature(config.model, config.endpoint) or (
config.temperature != 0.0 and config.seed is None
)
diff --git a/ifixai/judge/evaluator.py b/ifixai/judge/evaluator.py
index 5c905ec..d67e6ef 100644
--- a/ifixai/judge/evaluator.py
+++ b/ifixai/judge/evaluator.py
@@ -33,6 +33,7 @@ class JudgeEvaluator:
endpoint=config.endpoint,
timeout=config.timeout,
temperature=config.temperature,
+ role="judge",
)
self._call_count = 0
self._cap_reached = False
@@ -118,7 +119,9 @@ class JudgeEvaluator:
"judge_transport_failures": dict(self._transport_failures),
# Read at report time: Anthropic learns a model refuses temperature on its first call.
"default_temperature": self._temperature_required
- and not self._provider.accepts_temperature(self._provider_config.model),
+ and not self._provider.accepts_temperature(
+ self._provider_config.model, self._provider_config.endpoint
+ ),
}
async def aclose(self) -> None:
diff --git a/ifixai/providers/anthropic.py b/ifixai/providers/anthropic.py
index 718df30..3c8da5a 100644
--- a/ifixai/providers/anthropic.py
+++ b/ifixai/providers/anthropic.py
@@ -27,9 +27,15 @@ ClientCacheKey = tuple[str | None, str | None, float]
_logger = logging.getLogger(__name__)
-# Models whose API rejected temperature. Process-wide so the SUT, the judge and the
-# connection check share it: one 400 and one warning per model per run.
-_NO_TEMPERATURE_MODELS: set[str] = set()
+# Endpoint/model pairs whose API rejected temperature. Process-wide so the SUT,
+# judge and connection check share learned support only for the same API.
+_NO_TEMPERATURE_MODELS: set[tuple[str, str]] = set()
+# The API root each configured endpoint sends to (None: wherever the SDK sends by
+# default), kept when its client is made so a provider that sent nothing can look.
+_API_ROOTS: dict[str | None, str] = {}
+# (API root, model, role) already warned about. The agent and the judge can share an
+# endpoint and model, so each role that loses temperature is named once.
+_DEFAULT_TEMPERATURE_WARNED: set[tuple[str, str, str]] = set()
class AnthropicProvider(ChatProvider):
@@ -65,14 +71,16 @@ class AnthropicProvider(ChatProvider):
max_retries=0,
)
self._clients[key] = client
+ _API_ROOTS[config.endpoint] = _api_root(client)
return client
async def aclose(self) -> None:
await close_cached_clients(self._clients)
- def accepts_temperature(self, model: str | None) -> bool:
- # As far as this run knows: a model joins _NO_TEMPERATURE_MODELS on its first 400.
- return (model or DEFAULT_MODEL) not in _NO_TEMPERATURE_MODELS
+ def accepts_temperature(self, model: str | None, endpoint: str | None) -> bool:
+ # As far as this run knows: a pair joins _NO_TEMPERATURE_MODELS on its first 400.
+ root = _API_ROOTS.get(endpoint)
+ return root is None or (root, model or DEFAULT_MODEL) not in _NO_TEMPERATURE_MODELS
async def send_message(
self,
@@ -105,6 +113,7 @@ class AnthropicProvider(ChatProvider):
# the underlying SDK call cannot pin it.
response = await _create_message(client, kwargs, config.temperature)
+ _warn_once_at_default_temperature(_api_root(client), model, config.role)
content_blocks = response.content
text_parts = [
@@ -185,7 +194,8 @@ async def _create_message(
# SDK 1.x dropped the temperature kwarg, so it rides in extra_body. Newer
# models 400 on any temperature: retry once without it and remember the model.
model = kwargs["model"]
- if model not in _NO_TEMPERATURE_MODELS:
+ capability_key = (_api_root(client), model)
+ if capability_key not in _NO_TEMPERATURE_MODELS:
try:
return await client.messages.create(
**kwargs, extra_body={"temperature": temperature}
@@ -194,15 +204,27 @@ async def _create_message(
# Outside 0..1 the 400 is our bad value, not a model that refuses temperature.
if not 0 <= temperature <= 1 or "temperature" not in str(exc).lower():
raise
- if model not in _NO_TEMPERATURE_MODELS:
- _NO_TEMPERATURE_MODELS.add(model)
- _logger.warning(
- "%s rejects temperature; it runs at the model's default temperature",
- model,
- )
+ _NO_TEMPERATURE_MODELS.add(capability_key)
return await client.messages.create(**kwargs)
+def _warn_once_at_default_temperature(root: str, model: str, role: str) -> None:
+ warned_key = (root, model, role)
+ if (root, model) not in _NO_TEMPERATURE_MODELS or warned_key in _DEFAULT_TEMPERATURE_WARNED:
+ return
+ _DEFAULT_TEMPERATURE_WARNED.add(warned_key)
+ _logger.warning(
+ "%s model %s rejects temperature; the %s runs at the model's default temperature",
+ role,
+ model,
+ role,
+ )
+
+
+def _api_root(client: anthropic.AsyncAnthropic) -> str:
+ return str(client.base_url).rstrip("/")
+
+
def _split_system_and_messages(
messages: list[ChatMessage],
) -> MessageSplit:
diff --git a/ifixai/providers/base.py b/ifixai/providers/base.py
index bb0f50b..591ab53 100644
--- a/ifixai/providers/base.py
+++ b/ifixai/providers/base.py
@@ -418,8 +418,8 @@ class ChatProvider(ABC):
"""
return None
- def accepts_temperature(self, model: str | None) -> bool:
- """Whether a request to `model` carries the configured temperature."""
+ def accepts_temperature(self, model: str | None, endpoint: str | None) -> bool:
+ """Whether a request to `model` at `endpoint` carries the configured temperature."""
return True
async def list_tools(
diff --git a/ifixai/tests/test_anthropic_endpoint_capabilities.py b/ifixai/tests/test_anthropic_endpoint_capabilities.py
new file mode 100644
index 0000000..0d97205
--- /dev/null
+++ b/ifixai/tests/test_anthropic_endpoint_capabilities.py
@@ -0,0 +1,230 @@
+"""Native SDK requests must learn temperature support per endpoint and model."""
+import json
+import logging
+import threading
+from collections.abc import Iterator
+from contextlib import contextmanager
+from http.server import ThreadingHTTPServer
+
+import pytest
+
+from ifixai.core.types import ChatMessage, ProviderConfig
+from ifixai.judge.config import JudgeConfig
+from ifixai.judge.evaluator import JudgeEvaluator
+from ifixai.tests.test_anthropic_temperature_native import (
+ ACCEPTS,
+ REJECTS,
+ AnthropicProvider,
+ FakeMessagesApi,
+ adapter,
+ message,
+ send,
+)
+
+
+@contextmanager
+def local_api() -> Iterator[ThreadingHTTPServer]:
+ server = ThreadingHTTPServer(("127.0.0.1", 0), FakeMessagesApi)
+ server.bodies = []
+ worker = threading.Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ yield server
+ finally:
+ server.shutdown()
+ server.server_close()
+ worker.join(2)
+
+
[email protected]("same_provider", [True, False])
+async def test_temperature_rejection_at_one_endpoint_does_not_disable_another(
+ monkeypatch, same_provider,
+):
+ monkeypatch.setattr(adapter, "_NO_TEMPERATURE_MODELS", set())
+ # Same model name resolves to different capabilities behind the two hosts.
+ with local_api() as rejects, local_api() as accepts:
+ original_handler = accepts.RequestHandlerClass
+ class AcceptAll(original_handler):
+ def do_POST(self):
+ import json
+
+ from ifixai.tests.test_anthropic_temperature_native import message
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ self.server.bodies.append(body)
+ self.reply(200, message(body["model"]))
+ accepts.RequestHandlerClass = AcceptAll
+ first = AnthropicProvider()
+ second = first if same_provider else AnthropicProvider()
+ try:
+ assert await send(first, rejects, REJECTS, .25) == "fake reply"
+ assert await send(second, accepts, REJECTS, .75) == "fake reply"
+ assert await send(second, rejects, REJECTS, .25) == "fake reply"
+ assert await send(first, accepts, ACCEPTS, .5) == "fake reply"
+ finally:
+ await first.aclose()
+ if second is not first:
+ await second.aclose()
+ assert [b.get("temperature") for b in rejects.bodies] == [.25, None, None]
+ assert [b.get("temperature") for b in accepts.bodies] == [.75, .5]
+
+
+async def test_default_api_and_equivalent_trailing_slash_share_learning(monkeypatch):
+ import json
+
+ import anthropic
+ from anthropic import _base_client
+ httpx = getattr(_base_client, "httpx2", None) or _base_client.httpx
+ from ifixai.tests.test_anthropic_temperature_native import error, message
+
+ monkeypatch.setattr(adapter, "_NO_TEMPERATURE_MODELS", set())
+ bodies = []
+ def respond(request):
+ assert request.url.host == "api.anthropic.com"
+ body = json.loads(request.content)
+ bodies.append(body)
+ if body["model"] == REJECTS and "temperature" in body:
+ return httpx.Response(400, json=error("temperature not supported"))
+ return httpx.Response(200, json=message(body["model"]))
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as transport:
+ async with anthropic.AsyncAnthropic(api_key="owned-fixture", http_client=transport) as default:
+ await adapter._create_message(default, {"model": REJECTS, "max_tokens": 4, "messages": [{"role": "user", "content": "owned"}]}, .25)
+ await adapter._create_message(default, {"model": ACCEPTS, "max_tokens": 4, "messages": [{"role": "user", "content": "owned"}]}, .75)
+ async with anthropic.AsyncAnthropic(api_key="owned-fixture", base_url="https://api.anthropic.com/", http_client=transport) as equivalent:
+ await adapter._create_message(equivalent, {"model": REJECTS, "max_tokens": 4, "messages": [{"role": "user", "content": "owned"}]}, .25)
+ assert [body.get("temperature") for body in bodies] == [.25, None, .75, None]
+
+
+class AcceptsAnyTemperature(FakeMessagesApi):
+ """A gateway in front of the same model that takes temperature."""
+
+ def do_POST(self) -> None:
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ self.server.bodies.append(body)
+ self.reply(200, message(body["model"]))
+
+
+async def send_to(provider: AnthropicProvider, endpoint: str | None, model: str) -> str:
+ return await provider.send_message(
+ [ChatMessage(role="user", content="hi")],
+ ProviderConfig(provider="anthropic", endpoint=endpoint, api_key="synthetic-local-key",
+ model=model, timeout=5, max_retries=0, temperature=0.0),
+ )
+
+
[email protected]("judge_endpoint_from_env", [False, True])
+async def test_accepts_temperature_answers_per_endpoint_for_the_same_model(
+ monkeypatch, judge_endpoint_from_env,
+):
+ monkeypatch.setattr(adapter, "_NO_TEMPERATURE_MODELS", set())
+ monkeypatch.setattr(adapter, "_API_ROOTS", {})
+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
+ with local_api() as rejects, local_api() as accepts:
+ accepts.RequestHandlerClass = AcceptsAnyTemperature
+ agent_endpoint = f"http://127.0.0.1:{rejects.server_port}"
+ judge_endpoint = f"http://127.0.0.1:{accepts.server_port}"
+ if judge_endpoint_from_env:
+ # A judge with no endpoint goes wherever the SDK sends it.
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", judge_endpoint)
+ judge_endpoint = None
+ agent, judge = AnthropicProvider(), AnthropicProvider()
+ try:
+ assert await send_to(agent, agent_endpoint, REJECTS) == "fake reply"
+ assert await send_to(judge, judge_endpoint, REJECTS) == "fake reply"
+ finally:
+ await agent.aclose()
+ await judge.aclose()
+ assert [b.get("temperature") for b in rejects.bodies] == [0.0, None]
+ assert [b.get("temperature") for b in accepts.bodies] == [0.0]
+ # A provider that sent nothing (the partial scorecard builds a fresh one) knows the same.
+ for asked in (agent, judge, AnthropicProvider()):
+ assert asked.accepts_temperature(REJECTS, agent_endpoint) is False
+ assert asked.accepts_temperature(REJECTS, judge_endpoint) is True
+ assert asked.accepts_temperature(ACCEPTS, agent_endpoint) is True
+ assert asked.accepts_temperature(REJECTS, "http://127.0.0.1:9") is True
+
+
+AGENT_AT_DEFAULT = (
+ f"agent model {REJECTS} rejects temperature; the agent runs at the model's default temperature"
+)
+JUDGE_AT_DEFAULT = (
+ f"judge model {REJECTS} rejects temperature; the judge runs at the model's default temperature"
+)
+
+
+def fresh_run(monkeypatch) -> None:
+ """A run that has not met any endpoint yet."""
+ monkeypatch.setattr(adapter, "_NO_TEMPERATURE_MODELS", set())
+ monkeypatch.setattr(adapter, "_API_ROOTS", {})
+ monkeypatch.setattr(adapter, "_DEFAULT_TEMPERATURE_WARNED", set())
+
+
+async def send_as(role: str, provider: AnthropicProvider, server: ThreadingHTTPServer) -> str:
+ return await provider.send_message(
+ [ChatMessage(role="user", content="hi")],
+ ProviderConfig(provider="anthropic", endpoint=f"http://127.0.0.1:{server.server_port}",
+ api_key="synthetic-local-key", model=REJECTS, timeout=5, max_retries=0,
+ temperature=0.0, role=role),
+ )
+
+
+def adapter_warnings(caplog: pytest.LogCaptureFixture) -> list[str]:
+ return [r.getMessage() for r in caplog.records if r.name == adapter.__name__]
+
+
[email protected](("rejecting_role", "accepting_role", "expected"), [
+ ("judge", "agent", [JUDGE_AT_DEFAULT]),
+ ("agent", "judge", [AGENT_AT_DEFAULT]),
+])
+async def test_warning_names_the_role_whose_endpoint_rejects_temperature(
+ fresh_run, caplog, rejecting_role, accepting_role, expected,
+):
+ caplog.set_level(logging.WARNING, logger=adapter.__name__)
+ with local_api() as rejects, local_api() as accepts:
+ accepts.RequestHandlerClass = AcceptsAnyTemperature
+ providers = {"agent": AnthropicProvider(), "judge": AnthropicProvider()}
+ try:
+ for _ in range(2):
+ assert await send_as(accepting_role, providers[accepting_role], accepts) == "fake reply"
+ assert await send_as(rejecting_role, providers[rejecting_role], rejects) == "fake reply"
+ finally:
+ for provider in providers.values():
+ await provider.aclose()
+ assert [b.get("temperature") for b in accepts.bodies] == [0.0, 0.0]
+ assert [b.get("temperature") for b in rejects.bodies] == [0.0, None, None]
+ assert adapter_warnings(caplog) == expected
+
+
+async def test_agent_and_judge_behind_one_rejecting_endpoint_are_each_named_once(fresh_run, caplog):
+ caplog.set_level(logging.WARNING, logger=adapter.__name__)
+ with local_api() as rejects:
+ agent, judge = AnthropicProvider(), AnthropicProvider()
+ try:
+ for role, provider in [("agent", agent), ("agent", agent), ("judge", judge), ("judge", judge)]:
+ assert await send_as(role, provider, rejects) == "fake reply"
+ finally:
+ await agent.aclose()
+ await judge.aclose()
+ # The agent's first send is refused and resent. The judge never sends temperature,
+ # but it still runs at the default, so it is named too.
+ assert [b.get("temperature") for b in rejects.bodies] == [0.0, None, None, None, None]
+ assert adapter_warnings(caplog) == [AGENT_AT_DEFAULT, JUDGE_AT_DEFAULT]
+
+
+async def test_judge_evaluator_sends_as_the_judge(fresh_run, caplog):
+ caplog.set_level(logging.WARNING, logger=adapter.__name__)
+ with local_api() as rejects:
+ judge = JudgeEvaluator(JudgeConfig(
+ provider="anthropic", model=REJECTS, api_key="synthetic-local-key",
+ endpoint=f"http://127.0.0.1:{rejects.server_port}",
+ ))
+ try:
+ reply = await judge.send_message(
+ [ChatMessage(role="user", content="grade this")], judge.provider_pair()["config"]
+ )
+ finally:
+ await judge.aclose()
+ assert reply == "fake reply"
+ assert [b.get("temperature") for b in rejects.bodies] == [0.0, None]
+ assert adapter_warnings(caplog) == [JUDGE_AT_DEFAULT]
diff --git a/ifixai/tests/test_anthropic_temperature_native.py b/ifixai/tests/test_anthropic_temperature_native.py
index 5ec661a..3bc5c8a 100644
--- a/ifixai/tests/test_anthropic_temperature_native.py
+++ b/ifixai/tests/test_anthropic_temperature_native.py
@@ -77,6 +77,7 @@ def message(model: str) -> dict:
@pytest.fixture
def api(monkeypatch) -> Iterator[ThreadingHTTPServer]:
monkeypatch.setattr(adapter, "_NO_TEMPERATURE_MODELS", set())
+ monkeypatch.setattr(adapter, "_DEFAULT_TEMPERATURE_WARNED", set())
server = ThreadingHTTPServer(("127.0.0.1", 0), FakeMessagesApi)
server.bodies = []
thread = threading.Thread(target=server.serve_forever, daemon=True)
@@ -128,7 +129,7 @@ async def test_model_that_rejects_temperature_retries_once_then_skips_it(api, ca
await judge.aclose()
assert ["temperature" in b for b in api.bodies] == [True, False, False, False]
assert [r.getMessage() for r in caplog.records] == [
- f"{REJECTS} rejects temperature; it runs at the model's default temperature"
+ f"agent model {REJECTS} rejects temperature; the agent runs at the model's default temperature"
]
@@ -163,7 +164,9 @@ async def test_capitalised_temperature_400_takes_the_retry_path(api):
finally:
await provider.aclose()
assert ["temperature" in b for b in api.bodies] == [True, False, False]
- assert adapter._NO_TEMPERATURE_MODELS == {REJECTS_CAPITALISED}
+ assert adapter._NO_TEMPERATURE_MODELS == {
+ (f"http://127.0.0.1:{api.server_port}", REJECTS_CAPITALISED)
+ }
async def test_out_of_range_temperature_raises_and_caches_nothing(api):