Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix: negotiate tool model probe parameters

Ruben Lütkea1dfe506a643
diff --git a/jarvis/brain/healthcheck.py b/jarvis/brain/healthcheck.py
index 6236a646e0..8d4a64d353 100644
--- a/jarvis/brain/healthcheck.py
+++ b/jarvis/brain/healthcheck.py
@@ -42,7 +42,10 @@ class HealthResult:
_PROBE_REQUEST = BrainRequest(
messages=(BrainMessage(role="user", content="hi"),),
max_tokens=8,
- temperature=0.0,
+ # A connectivity probe does not need deterministic sampling. Some current
+ # reasoning/tool models accept only their default temperature of 1, so
+ # forcing 0 here turns a healthy provider into a false integration error.
+ temperature=1.0,
stream=True,
)
diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.py
index e44cc07acc..1300f3eb77 100644
--- a/jarvis/plugins/brain/_openai_base.py
+++ b/jarvis/plugins/brain/_openai_base.py
@@ -358,8 +358,91 @@ async def stream_complete(
})
+_UNSUPPORTED_ERROR_MARKERS = (
+ "unsupported_parameter",
+ "unsupported_value",
+ "unsupported parameter",
+ "unsupported value",
+ "does not support",
+ "not supported",
+)
+
+
+def _error_metadata(exc: Exception) -> tuple[str, str, str]:
+ """Return normalized ``(parameter, code, message)`` without SDK coupling."""
+ parameter = str(getattr(exc, "param", "") or "").strip().lower()
+ code = str(getattr(exc, "code", "") or "").strip().lower()
+ body = getattr(exc, "body", None)
+ if isinstance(body, dict):
+ error = body.get("error", body)
+ if isinstance(error, dict):
+ parameter = str(error.get("param") or parameter).strip().lower()
+ code = str(error.get("code") or code).strip().lower()
+ return parameter, code, str(exc).lower()
+
+
+def _explicitly_rejects_parameter(exc: Exception, parameter: str) -> bool:
+ """Whether an API error explicitly rejects one request parameter.
+
+ OpenAI SDK errors expose ``param``/``code`` on some versions and only an
+ embedded response body on others. OpenAI-compatible gateways often expose
+ neither, so the message fallback remains intentionally narrow: the field
+ name and an explicit unsupported marker must both be present.
+ """
+ rejected_parameter, code, message = _error_metadata(exc)
+ unsupported = code in {"unsupported_parameter", "unsupported_value"} or any(
+ marker in message for marker in _UNSUPPORTED_ERROR_MARKERS
+ )
+ if not unsupported:
+ return False
+ if rejected_parameter:
+ return rejected_parameter == parameter
+ return parameter in message
+
+
+def _compatible_retry_kwargs(
+ exc: Exception,
+ kwargs: dict[str, Any],
+ adaptations: set[str],
+) -> tuple[dict[str, Any], str] | None:
+ """Build one safe retry after an explicit model/API capability rejection."""
+ message = str(exc).lower()
+ if "max_tokens" in kwargs and "max_tokens" not in adaptations:
+ rejected_max_tokens = (
+ "max_completion_tokens" in message
+ or _explicitly_rejects_parameter(exc, "max_tokens")
+ )
+ if rejected_max_tokens:
+ retry_kwargs = dict(kwargs)
+ retry_kwargs["max_completion_tokens"] = retry_kwargs.pop("max_tokens")
+ return retry_kwargs, "max_tokens"
+
+ # Sampling is optional. If a model accepts only its own default, omission
+ # is the capability-safe fallback and preserves the provider's chosen value.
+ if (
+ "temperature" in kwargs
+ and "temperature" not in adaptations
+ and _explicitly_rejects_parameter(exc, "temperature")
+ ):
+ retry_kwargs = dict(kwargs)
+ retry_kwargs.pop("temperature", None)
+ return retry_kwargs, "temperature"
+
+ # Inline usage accounting is optional and not implemented by every
+ # OpenAI-compatible server even when the installed SDK accepts the kwarg.
+ if (
+ "stream_options" in kwargs
+ and "stream_options" not in adaptations
+ and _explicitly_rejects_parameter(exc, "stream_options")
+ ):
+ retry_kwargs = dict(kwargs)
+ retry_kwargs.pop("stream_options", None)
+ return retry_kwargs, "stream_options"
+ return None
+
+
async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) -> Any:
- """``chat.completions.create`` with a one-shot token-parameter retry.
+ """Create a chat stream with bounded, rejection-driven compatibility retries.
Newer OpenAI models reject the legacy ``max_tokens`` with a 400
``unsupported_parameter`` error ("Use 'max_completion_tokens' instead"),
@@ -368,25 +451,34 @@ async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) ->
the server's EXPLICIT rejection keeps both families working without
pinning model names (AP-21). Field-found: a valid OpenAI key read as
"Not working" in the provider test because of this 400.
+
+ The same capability negotiation applies to optional ``temperature`` and
+ ``stream_options`` fields. Each field is adapted at most once and only
+ after the API explicitly rejects it, so authentication, billing, model,
+ tool-schema, and network failures are never hidden or retried.
"""
- try:
- return await client.chat.completions.create(**kwargs)
- except TypeError:
- # SDK-level kwarg problems belong to the caller's stream_options
- # handling — never ours.
- raise
- except Exception as exc: # noqa: BLE001 — inspect the API error, re-raise unrelated
- message = str(exc)
- rejected_max_tokens = "max_tokens" in kwargs and (
- "max_completion_tokens" in message
- or ("unsupported_parameter" in message and "'max_tokens'" in message)
- )
- if not rejected_max_tokens:
+ current_kwargs = kwargs
+ adaptations: set[str] = set()
+ while True:
+ try:
+ return await client.chat.completions.create(**current_kwargs)
+ except TypeError:
+ # SDK-level kwarg problems belong to the caller's stream_options
+ # handling — never ours.
raise
- log.info(
- "provider rejected 'max_tokens' — retrying once with "
- "'max_completion_tokens'."
- )
- retry_kwargs = dict(kwargs)
- retry_kwargs["max_completion_tokens"] = retry_kwargs.pop("max_tokens")
- return await client.chat.completions.create(**retry_kwargs)
+ except Exception as exc: # noqa: BLE001 — inspect, adapt, or re-raise
+ retry = _compatible_retry_kwargs(exc, current_kwargs, adaptations)
+ if retry is None:
+ raise
+ current_kwargs, field = retry
+ adaptations.add(field)
+ if field == "max_tokens":
+ log.info(
+ "provider rejected 'max_tokens' — retrying with "
+ "'max_completion_tokens'."
+ )
+ else:
+ log.info(
+ "provider rejected optional '%s' — retrying without it.",
+ field,
+ )
diff --git a/tests/unit/brain/test_healthcheck_request_compatibility.py b/tests/unit/brain/test_healthcheck_request_compatibility.py
new file mode 100644
index 0000000000..63914e2a03
--- /dev/null
+++ b/tests/unit/brain/test_healthcheck_request_compatibility.py
@@ -0,0 +1,36 @@
+"""Compatibility properties of the provider-agnostic brain health probe."""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from typing import Any
+
+import pytest
+
+from jarvis.brain.healthcheck import BrainHealthChecker
+from jarvis.core.protocols import BrainDelta, BrainRequest
+
+
+class _CapturingBrain:
+ requests: list[BrainRequest] = []
+
+ async def complete(self, request: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(request)
+ yield BrainDelta(content="ok")
+
+
+class _Registry:
+ def instantiate(self, _provider: str, **_kwargs: Any) -> _CapturingBrain:
+ return _CapturingBrain()
+
+
+async def test_probe_does_not_force_zero_temperature() -> None:
+ """Connectivity checks must remain valid for default-only tool models."""
+ _CapturingBrain.requests.clear()
+ checker = BrainHealthChecker(_Registry()) # type: ignore[arg-type]
+
+ result = await checker.probe("provider", "tool-model")
+
+ assert result.ok is True
+ assert len(_CapturingBrain.requests) == 1
+ assert _CapturingBrain.requests[0].temperature == 1.0
diff --git a/tests/unit/plugins/brain/test_openai_token_param_retry.py b/tests/unit/plugins/brain/test_openai_token_param_retry.py
index 5f692fcfb4..3cfa227666 100644
--- a/tests/unit/plugins/brain/test_openai_token_param_retry.py
+++ b/tests/unit/plugins/brain/test_openai_token_param_retry.py
@@ -1,9 +1,10 @@
-"""OpenAI token-parameter retry (field bug: valid key read as "Not working").
+"""OpenAI-compatible parameter retries for explicit API capability rejections.
Newer OpenAI models 400-reject the legacy ``max_tokens`` ("Use
'max_completion_tokens' instead"); OpenAI-compatible servers often only know
-``max_tokens``. The shared base must send the legacy name first and switch
-exactly once on the server's explicit rejection — never on unrelated errors.
+``max_tokens``. Some reasoning/tool models also accept only their default
+temperature. The shared base adapts each field only after an explicit rejection
+and never retries unrelated errors.
"""
from __future__ import annotations
@@ -18,6 +19,19 @@ _OPENAI_400 = (
"'param': 'max_tokens', 'code': 'unsupported_parameter'}}"
)
+_OPENAI_TEMPERATURE_400 = (
+ "Error code: 400 - {'error': {'message': \"Unsupported value: 'temperature' "
+ "does not support 0 with this model. Only the default (1) value is "
+ "supported.\", 'type': 'invalid_request_error', 'param': 'temperature', "
+ "'code': 'unsupported_value'}}"
+)
+
+_OPENAI_STREAM_OPTIONS_400 = (
+ "Error code: 400 - {'error': {'message': \"Unsupported parameter: "
+ "'stream_options'.\", 'type': 'invalid_request_error', "
+ "'param': 'stream_options', 'code': 'unsupported_parameter'}}"
+)
+
class _FakeClient:
def __init__(self, first_error: Exception | None) -> None:
@@ -35,6 +49,22 @@ class _FakeClient:
return "stream"
+class _SequenceClient:
+ def __init__(self, errors: list[Exception]) -> None:
+ self.calls: list[dict] = []
+ self._errors = list(errors)
+ chat = type("Chat", (), {})()
+ chat.completions = type("Completions", (), {})()
+ chat.completions.create = self._create
+ self.chat = chat
+
+ async def _create(self, **kwargs):
+ self.calls.append(kwargs)
+ if self._errors:
+ raise self._errors.pop(0)
+ return "stream"
+
+
async def test_max_tokens_rejection_retries_with_max_completion_tokens() -> None:
client = _FakeClient(RuntimeError(_OPENAI_400))
result = await _create_with_token_param_retry(
@@ -47,6 +77,52 @@ async def test_max_tokens_rejection_retries_with_max_completion_tokens() -> None
assert client.calls[1].get("max_completion_tokens") == 8
+async def test_default_only_temperature_rejection_retries_without_temperature() -> None:
+ client = _FakeClient(RuntimeError(_OPENAI_TEMPERATURE_400))
+ result = await _create_with_token_param_retry(
+ client, {"model": "m", "max_tokens": 8, "temperature": 0.0}
+ )
+
+ assert result == "stream"
+ assert len(client.calls) == 2
+ assert client.calls[0]["temperature"] == 0.0
+ assert "temperature" not in client.calls[1]
+ assert client.calls[1]["max_tokens"] == 8
+
+
+async def test_api_rejected_stream_options_retries_without_usage_option() -> None:
+ client = _FakeClient(RuntimeError(_OPENAI_STREAM_OPTIONS_400))
+ result = await _create_with_token_param_retry(
+ client,
+ {
+ "model": "m",
+ "max_tokens": 8,
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ },
+ )
+
+ assert result == "stream"
+ assert len(client.calls) == 2
+ assert "stream_options" not in client.calls[1]
+
+
+async def test_multiple_explicit_rejections_are_adapted_once_each() -> None:
+ client = _SequenceClient(
+ [RuntimeError(_OPENAI_400), RuntimeError(_OPENAI_TEMPERATURE_400)]
+ )
+ result = await _create_with_token_param_retry(
+ client, {"model": "m", "max_tokens": 8, "temperature": 0.0}
+ )
+
+ assert result == "stream"
+ assert len(client.calls) == 3
+ assert client.calls[1]["max_completion_tokens"] == 8
+ assert client.calls[1]["temperature"] == 0.0
+ assert client.calls[2]["max_completion_tokens"] == 8
+ assert "temperature" not in client.calls[2]
+
+
async def test_unrelated_errors_are_not_retried() -> None:
client = _FakeClient(RuntimeError("Error code: 401 - invalid api key"))
with pytest.raises(RuntimeError, match="401"):
@@ -54,6 +130,15 @@ async def test_unrelated_errors_are_not_retried() -> None:
assert len(client.calls) == 1
+async def test_temperature_validation_error_is_not_misread_as_unsupported() -> None:
+ client = _FakeClient(RuntimeError("temperature must be between 0 and 2"))
+ with pytest.raises(RuntimeError, match="between 0 and 2"):
+ await _create_with_token_param_retry(
+ client, {"model": "m", "temperature": 3.0}
+ )
+ assert len(client.calls) == 1
+
+
async def test_success_path_calls_once() -> None:
client = _FakeClient(None)
assert await _create_with_token_param_retry(client, {"max_tokens": 8}) == "stream"