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(brain): retry with max_completion_tokens when OpenAI rejects max_tokens

Ruben Lütkeb646e8b4e0c1
diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.py
index 66f8f65201..e44cc07acc 100644
--- a/jarvis/plugins/brain/_openai_base.py
+++ b/jarvis/plugins/brain/_openai_base.py
@@ -259,6 +259,7 @@ async def stream_complete(
# The same map must sanitize both declarations and reconstructed assistant
# tool history. Otherwise an MCP name such as ``github/search`` succeeds in
# the first round, then makes the provider reject the second-round history.
+ # (Token-limit param note: see _create_with_token_param_retry below.)
name_map = _openai_tool_name_map(req.tools) if req.tools else {}
messages = _to_openai_messages(
req.messages,
@@ -293,7 +294,7 @@ async def stream_complete(
tool_buffer: dict[int, dict[str, Any]] = {}
try:
- stream = await client.chat.completions.create(**kwargs)
+ stream = await _create_with_token_param_retry(client, kwargs)
except TypeError as exc:
# Belt-and-suspenders: if the detection above was wrong for whatever
# reason (mocked tests, monkey-patched SDK, exotic forks), retry once
@@ -306,7 +307,7 @@ async def stream_complete(
exc,
)
kwargs.pop("stream_options", None)
- stream = await client.chat.completions.create(**kwargs)
+ stream = await _create_with_token_param_retry(client, kwargs)
async for chunk in stream:
# Text-Content
choices = getattr(chunk, "choices", None) or []
@@ -355,3 +356,37 @@ async def stream_complete(
"input_tokens": int(getattr(usage, "prompt_tokens", 0) or 0),
"output_tokens": int(getattr(usage, "completion_tokens", 0) or 0),
})
+
+
+async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) -> Any:
+ """``chat.completions.create`` with a one-shot token-parameter retry.
+
+ Newer OpenAI models reject the legacy ``max_tokens`` with a 400
+ ``unsupported_parameter`` error ("Use 'max_completion_tokens' instead"),
+ while many OpenAI-COMPATIBLE servers (local runtimes, gateways) still only
+ accept ``max_tokens``. Sending the legacy name first and switching only on
+ 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.
+ """
+ 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:
+ 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)
diff --git a/tests/unit/plugins/brain/test_openai_token_param_retry.py b/tests/unit/plugins/brain/test_openai_token_param_retry.py
new file mode 100644
index 0000000000..5f692fcfb4
--- /dev/null
+++ b/tests/unit/plugins/brain/test_openai_token_param_retry.py
@@ -0,0 +1,60 @@
+"""OpenAI token-parameter retry (field bug: valid key read as "Not working").
+
+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.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.plugins.brain._openai_base import _create_with_token_param_retry
+
+_OPENAI_400 = (
+ "Error code: 400 - {'error': {'message': \"Unsupported parameter: "
+ "'max_tokens' is not supported with this model. Use "
+ "'max_completion_tokens' instead.\", 'type': 'invalid_request_error', "
+ "'param': 'max_tokens', 'code': 'unsupported_parameter'}}"
+)
+
+
+class _FakeClient:
+ def __init__(self, first_error: Exception | None) -> None:
+ self.calls: list[dict] = []
+ self._first_error = first_error
+ 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._first_error is not None and len(self.calls) == 1:
+ raise self._first_error
+ 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(
+ client, {"model": "m", "max_tokens": 8}
+ )
+ assert result == "stream"
+ assert len(client.calls) == 2
+ assert client.calls[0].get("max_tokens") == 8 # legacy first (compat servers)
+ assert "max_tokens" not in client.calls[1]
+ assert client.calls[1].get("max_completion_tokens") == 8
+
+
+async def test_unrelated_errors_are_not_retried() -> None:
+ client = _FakeClient(RuntimeError("Error code: 401 - invalid api key"))
+ with pytest.raises(RuntimeError, match="401"):
+ await _create_with_token_param_retry(client, {"model": "m", "max_tokens": 8})
+ 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"
+ assert len(client.calls) == 1