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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(brain): tool models actually honor reasoning_effort — OpenAI empty-output and OpenRouter TypeError crash
Personal Jarvis Maintainerf9404eab85c8
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex d61b18e699..dd8d46647c 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -220,6 +220,11 @@ def set_tool_model_selection(block = tomlkit.table()providers[provider] = blockblock["tool_model"] = model+ # Keep the legacy Computer-Use pin in lockstep: the route layer+ # sets both fields in memory, and resolution falls back to+ # ``cu_model`` when ``tool_model`` is ever cleared — persisting+ # only one lets the pair drift apart across a restart.+ block["cu_model"] = modelout = tomlkit.dumps(doc)if had_bom:diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.pyindex 1300f3eb77..377ee27fc5 100644--- a/jarvis/plugins/brain/_openai_base.py+++ b/jarvis/plugins/brain/_openai_base.py@@ -287,27 +287,52 @@ async def stream_complete(reverse_name_map = {safe: original for original, safe in name_map.items()}if req.tools:kwargs["tools"] = _tools_openai_format(req.tools, name_map)+ # Reasoning-by-default models (GPT-5.x class) otherwise burn the small+ # deterministic tool-step budget (CU: 256 tokens) on hidden thought and+ # stream back empty/truncated JSON — "OpenAI never works as the Tool+ # Model". Skipped when the caller's extra_body already carries a gateway+ # reasoning directive (OpenRouter's unified ``reasoning`` object), so the+ # two knobs never conflict. Models/SDKs that reject the parameter are+ # recovered by the graded retry in _compatible_retry_kwargs and the+ # TypeError strip below.+ effort = getattr(req, "reasoning_effort", None)+ if effort is not None and not (extra_body and "reasoning" in extra_body):+ kwargs["reasoning_effort"] = effortif extra_body:- kwargs.update(extra_body)+ # As ``extra_body`` — merged into the request JSON by the SDK. A+ # top-level ``kwargs.update(extra_body)`` raises TypeError on every+ # modern SDK (create() takes no **kwargs), which killed each+ # OpenRouter call that carried the reasoning opt-out.+ kwargs["extra_body"] = dict(extra_body)# Accumulator for tool-call partials (OpenAI streams per tool_call index)tool_buffer: dict[int, dict[str, Any]] = {}- try:- 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- # without stream_options. Saves a hard fail when the live API rejects- # an unexpected kwarg.- if "stream_options" not in kwargs or "stream_options" not in str(exc):- raise- log.warning(- "openai SDK rejected 'stream_options' (%s) — retrying without the kwarg.",- exc,- )- kwargs.pop("stream_options", None)- stream = await _create_with_token_param_retry(client, kwargs)+ # Belt-and-suspenders for SDK-level kwarg gaps: old SDKs know neither+ # ``stream_options`` (added ~1.30) nor ``reasoning_effort`` (added ~1.58)+ # and raise TypeError before any request is sent. Strip exactly the kwarg+ # the SDK named and retry — an ancient SDK may need both stripped.+ _sdk_optional_kwargs = ("stream_options", "reasoning_effort")+ stream = None+ for _ in range(len(_sdk_optional_kwargs) + 1):+ try:+ stream = await _create_with_token_param_retry(client, kwargs)+ break+ except TypeError as exc:+ offender = next(+ (k for k in _sdk_optional_kwargs if k in kwargs and k in str(exc)),+ None,+ )+ if offender is None:+ raise+ log.warning(+ "openai SDK rejected '%s' (%s) — retrying without the kwarg.",+ offender,+ exc,+ )+ kwargs.pop(offender, None)+ if stream is None: # pragma: no cover -- loop always breaks or raises+ raise RuntimeError("openai stream creation retry loop exhausted")async for chunk in stream:# Text-Contentchoices = getattr(chunk, "choices", None) or []@@ -428,6 +453,26 @@ def _compatible_retry_kwargs(retry_kwargs.pop("temperature", None)return retry_kwargs, "temperature"+ # Reasoning effort degrades in two steps: a model that knows the knob but+ # not the value "none" (o-series, gpt-5 base) still honors "minimal" —+ # keeping the thought budget capped, which is the caller's whole intent —+ # and only a model that rejects the parameter itself loses the cap.+ if (+ kwargs.get("reasoning_effort") is not None+ and _explicitly_rejects_parameter(exc, "reasoning_effort")+ ):+ if (+ kwargs["reasoning_effort"] == "none"+ and "reasoning_effort:minimal" not in adaptations+ ):+ retry_kwargs = dict(kwargs)+ retry_kwargs["reasoning_effort"] = "minimal"+ return retry_kwargs, "reasoning_effort:minimal"+ if "reasoning_effort" not in adaptations:+ retry_kwargs = dict(kwargs)+ retry_kwargs.pop("reasoning_effort", None)+ return retry_kwargs, "reasoning_effort"+# Inline usage accounting is optional and not implemented by every# OpenAI-compatible server even when the installed SDK accepts the kwarg.if (@@ -477,6 +522,11 @@ async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) ->"provider rejected 'max_tokens' — retrying with ""'max_completion_tokens'.")+ elif field == "reasoning_effort:minimal":+ log.info(+ "provider rejected reasoning_effort='none' — retrying "+ "with the lowest supported effort 'minimal'."+ )else:log.info("provider rejected optional '%s' — retrying without it.",diff --git a/tests/unit/plugins/brain/test_openai_reasoning_effort.py b/tests/unit/plugins/brain/test_openai_reasoning_effort.pynew file mode 100644index 0000000000..7b65f0bb3f--- /dev/null+++ b/tests/unit/plugins/brain/test_openai_reasoning_effort.py@@ -0,0 +1,154 @@+"""Direct-provider handling of the ``reasoning_effort`` request hint.++CU steps and delegated voice turns send ``reasoning_effort="none"`` with a+small ``max_tokens`` budget (256): a reasoning-by-default GPT-5.x model that+never receives the hint burns the whole budget on hidden thought and streams+back empty/truncated JSON — the field report was "OpenAI does not work at+all as the Tool Model". The shared OpenAI-compatible base must:++ 1. forward ``reasoning_effort`` on the wire call,+ 2. degrade gradually on explicit rejection ("none" → "minimal" → omitted),+ 3. strip the kwarg when an old SDK raises ``TypeError`` for it,+ 4. pass gateway ``extra_body`` AS ``extra_body`` — a top-level+ ``kwargs.update(extra_body)`` raises ``TypeError`` on every modern SDK+ (``create()`` accepts no ``**kwargs``), which killed every OpenRouter+ call that carried the reasoning opt-out — and never double-send the+ native param next to a gateway reasoning directive.+"""+from __future__ import annotations++from typing import Any++from jarvis.core.protocols import BrainMessage, BrainRequest+from jarvis.plugins.brain._openai_base import (+ _create_with_token_param_retry,+ stream_complete,+)++_REJECT_VALUE_400 = (+ "Error code: 400 - {'error': {'message': \"Unsupported value: "+ "'reasoning_effort' does not support 'none' with this model.\", "+ "'type': 'invalid_request_error', 'param': 'reasoning_effort', "+ "'code': 'unsupported_value'}}"+)++_REJECT_PARAM_400 = (+ "Error code: 400 - {'error': {'message': \"Unsupported parameter: "+ "'reasoning_effort'.\", 'type': 'invalid_request_error', "+ "'param': 'reasoning_effort', 'code': 'unsupported_parameter'}}"+)+++class _EmptyStream:+ def __aiter__(self) -> _EmptyStream:+ return self++ async def __anext__(self) -> Any:+ raise StopAsyncIteration+++class _SequenceClient:+ """create() raises the queued errors first, then returns an empty stream."""++ def __init__(self, errors: list[Exception] | None = None) -> None:+ self.calls: list[dict[str, Any]] = []+ self._errors = list(errors or [])+ chat = type("Chat", (), {})()+ chat.completions = type("Completions", (), {})()+ chat.completions.create = self._create+ self.chat = chat++ async def _create(self, **kwargs: Any):+ self.calls.append(kwargs)+ if self._errors:+ raise self._errors.pop(0)+ return _EmptyStream()+++def _req(**kw: Any) -> BrainRequest:+ return BrainRequest(messages=(BrainMessage(role="user", content="hi"),), **kw)+++async def _drain(client: _SequenceClient, req: BrainRequest, **kw: Any) -> None:+ async for _ in stream_complete(client, "some-model", req, **kw):+ pass+++# ---------------------------------------------------------------------------+# 1. The hint reaches the wire call.+# ---------------------------------------------------------------------------+++async def test_reasoning_effort_none_is_forwarded() -> None:+ client = _SequenceClient()+ await _drain(client, _req(reasoning_effort="none"))+ assert client.calls[0]["reasoning_effort"] == "none"+++async def test_no_hint_sends_no_reasoning_parameter() -> None:+ client = _SequenceClient()+ await _drain(client, _req())+ assert "reasoning_effort" not in client.calls[0]+++# ---------------------------------------------------------------------------+# 2. Graded server-side degradation.+# ---------------------------------------------------------------------------+++async def test_value_rejection_downgrades_to_minimal() -> None:+ client = _SequenceClient([RuntimeError(_REJECT_VALUE_400)])+ await _create_with_token_param_retry(+ client, {"model": "m", "messages": [], "reasoning_effort": "none"}+ )+ assert client.calls[0]["reasoning_effort"] == "none"+ assert client.calls[1]["reasoning_effort"] == "minimal", (+ "a model that knows the knob but not 'none' must keep the thought "+ "budget capped via 'minimal', not lose the cap entirely"+ )+++async def test_parameter_rejection_drops_the_knob() -> None:+ client = _SequenceClient(+ [RuntimeError(_REJECT_VALUE_400), RuntimeError(_REJECT_PARAM_400)]+ )+ await _create_with_token_param_retry(+ client, {"model": "m", "messages": [], "reasoning_effort": "none"}+ )+ assert "reasoning_effort" not in client.calls[2]+++# ---------------------------------------------------------------------------+# 3. Old SDKs without the kwarg (TypeError before any request).+# ---------------------------------------------------------------------------+++async def test_sdk_typeerror_strips_reasoning_effort_and_retries() -> None:+ client = _SequenceClient(+ [TypeError("create() got an unexpected keyword argument 'reasoning_effort'")]+ )+ await _drain(client, _req(reasoning_effort="none"))+ assert "reasoning_effort" in client.calls[0]+ assert "reasoning_effort" not in client.calls[1]+++# ---------------------------------------------------------------------------+# 4. Gateway extra_body stays extra_body; no double-send.+# ---------------------------------------------------------------------------+++async def test_extra_body_is_passed_as_extra_body_not_top_level() -> None:+ client = _SequenceClient()+ body = {"reasoning": {"enabled": False}}+ await _drain(client, _req(reasoning_effort="none"), extra_body=body)+ call = client.calls[0]+ assert call["extra_body"] == body+ assert "reasoning" not in call, (+ "a top-level 'reasoning' kwarg is a guaranteed TypeError on the real "+ "SDK (create() accepts no **kwargs) — the OpenRouter reasoning "+ "opt-out crash this test pins"+ )+ assert "reasoning_effort" not in call, (+ "the native knob must not be double-sent next to a gateway "+ "reasoning directive"+ )