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.

perf(brain): implementation for the per-endpoint rejected-param memory (files unstaged by a concurrent session in 7f5429c5)

Personal Jarvis Maintainere7768dc0ac2a
diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.py
index 377ee27fc5..58c342a2dd 100644
--- a/jarvis/plugins/brain/_openai_base.py
+++ b/jarvis/plugins/brain/_openai_base.py
@@ -425,6 +425,34 @@ def _explicitly_rejects_parameter(exc: Exception, parameter: str) -> bool:
return parameter in message
+# (base_url, model) -> optional-param adaptations that endpoint has already
+# explicitly rejected in this process. Providers/models are few, so this
+# stays tiny; process-lifetime staleness is fine — the worst case after a
+# server-side change is one conservative omission, never a failure.
+_PARAM_ADAPTATION_CACHE: dict[tuple[str, str], set[str]] = {}
+
+
+def _apply_adaptation(kwargs: dict[str, Any], field: str) -> dict[str, Any] | None:
+ """Apply one remembered adaptation to *kwargs*; ``None`` when moot."""
+ if field == "max_tokens":
+ if "max_tokens" not in kwargs:
+ return None
+ adapted = dict(kwargs)
+ adapted["max_completion_tokens"] = adapted.pop("max_tokens")
+ return adapted
+ if field == "reasoning_effort:minimal":
+ if kwargs.get("reasoning_effort") != "none":
+ return None
+ adapted = dict(kwargs)
+ adapted["reasoning_effort"] = "minimal"
+ return adapted
+ if field in kwargs:
+ adapted = dict(kwargs)
+ adapted.pop(field, None)
+ return adapted
+ return None
+
+
def _compatible_retry_kwargs(
exc: Exception,
kwargs: dict[str, Any],
@@ -502,8 +530,23 @@ async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) ->
after the API explicitly rejects it, so authentication, billing, model,
tool-schema, and network failures are never hidden or retried.
"""
- current_kwargs = kwargs
+ # Remember which optional params one (endpoint, model) pair has already
+ # rejected, so a tool loop does not pay the same rejection round-trip on
+ # every single step (the CU path calls this dozens of times per mission;
+ # an xAI/NIM model that rejects ``reasoning_effort`` would otherwise eat
+ # up to two extra HTTP 400s per step, and ``max_tokens``-renaming models
+ # one). Keyed by base_url+model — never by provider name (AP-21).
+ cache_key = (
+ str(getattr(client, "base_url", "") or ""),
+ str(kwargs.get("model", "") or ""),
+ )
+ current_kwargs = dict(kwargs)
adaptations: set[str] = set()
+ for field in _PARAM_ADAPTATION_CACHE.get(cache_key, ()): # noqa: B007
+ adapted = _apply_adaptation(current_kwargs, field)
+ if adapted is not None:
+ current_kwargs = adapted
+ adaptations.add(field)
while True:
try:
return await client.chat.completions.create(**current_kwargs)
@@ -517,6 +560,7 @@ async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) ->
raise
current_kwargs, field = retry
adaptations.add(field)
+ _PARAM_ADAPTATION_CACHE.setdefault(cache_key, set()).add(field)
if field == "max_tokens":
log.info(
"provider rejected 'max_tokens' — retrying with "
diff --git a/tests/unit/plugins/brain/test_openai_reasoning_effort.py b/tests/unit/plugins/brain/test_openai_reasoning_effort.py
index 7b65f0bb3f..0b539762c3 100644
--- a/tests/unit/plugins/brain/test_openai_reasoning_effort.py
+++ b/tests/unit/plugins/brain/test_openai_reasoning_effort.py
@@ -19,12 +19,21 @@ from __future__ import annotations
from typing import Any
+import pytest
+
from jarvis.core.protocols import BrainMessage, BrainRequest
+from jarvis.plugins.brain import _openai_base
from jarvis.plugins.brain._openai_base import (
_create_with_token_param_retry,
stream_complete,
)
+
[email protected](autouse=True)
+def _fresh_adaptation_cache(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The rejected-param memory is process-global; isolate it per test."""
+ monkeypatch.setattr(_openai_base, "_PARAM_ADAPTATION_CACHE", {})
+
_REJECT_VALUE_400 = (
"Error code: 400 - {'error': {'message': \"Unsupported value: "
"'reasoning_effort' does not support 'none' with this model.\", "
@@ -123,6 +132,44 @@ async def test_parameter_rejection_drops_the_knob() -> None:
# ---------------------------------------------------------------------------
+async def test_rejections_are_remembered_per_endpoint_and_model() -> None:
+ """A tool loop calls the same endpoint+model dozens of times per mission;
+ the rejection round-trips must be paid once, not on every step."""
+ first = _SequenceClient(
+ [RuntimeError(_REJECT_VALUE_400), RuntimeError(_REJECT_PARAM_400)]
+ )
+ first.base_url = "https://api.x.ai/v1"
+ await _create_with_token_param_retry(
+ first, {"model": "m", "messages": [], "reasoning_effort": "none"}
+ )
+ assert len(first.calls) == 3
+
+ second = _SequenceClient()
+ second.base_url = "https://api.x.ai/v1"
+ await _create_with_token_param_retry(
+ second, {"model": "m", "messages": [], "reasoning_effort": "none"}
+ )
+ assert len(second.calls) == 1, "remembered adaptations must pre-apply"
+ assert "reasoning_effort" not in second.calls[0]
+
+
+async def test_adaptation_memory_is_scoped_to_the_endpoint() -> None:
+ first = _SequenceClient([RuntimeError(_REJECT_PARAM_400)])
+ first.base_url = "https://api.x.ai/v1"
+ await _create_with_token_param_retry(
+ first, {"model": "m", "messages": [], "reasoning_effort": "none"}
+ )
+
+ other = _SequenceClient()
+ other.base_url = "https://integrate.api.nvidia.com/v1"
+ await _create_with_token_param_retry(
+ other, {"model": "m", "messages": [], "reasoning_effort": "none"}
+ )
+ assert other.calls[0]["reasoning_effort"] == "none", (
+ "another endpoint's rejection must not strip the knob here"
+ )
+
+
async def test_sdk_typeerror_strips_reasoning_effort_and_retries() -> None:
client = _SequenceClient(
[TypeError("create() got an unexpected keyword argument 'reasoning_effort'")]
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 3cfa227666..b374774331 100644
--- a/tests/unit/plugins/brain/test_openai_token_param_retry.py
+++ b/tests/unit/plugins/brain/test_openai_token_param_retry.py
@@ -10,8 +10,15 @@ from __future__ import annotations
import pytest
+from jarvis.plugins.brain import _openai_base
from jarvis.plugins.brain._openai_base import _create_with_token_param_retry
+
[email protected](autouse=True)
+def _fresh_adaptation_cache(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The rejected-param memory is process-global; isolate it per test."""
+ monkeypatch.setattr(_openai_base, "_PARAM_ADAPTATION_CACHE", {})
+
_OPENAI_400 = (
"Error code: 400 - {'error': {'message': \"Unsupported parameter: "
"'max_tokens' is not supported with this model. Use "