The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): retry once without reasoning fields when a custom endpoint rejects them
teknium10b2b4fd8fa6e
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 32005c53a29..c75fb7d9e77 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3226,6 +3226,37 @@ def _without_structured_output_format(kwargs: dict) -> Optional[dict]:return retry_kwargs if changed else None+def _is_reasoning_field_rejection(exc: Exception) -> bool:+ """Provider 400 rejecting a reasoning wire control by name (``reasoning_effort``, ``reasoning``,+ ``thinking``/``think``). Chat-only models behind OpenAI-compatible relays reject the top-level+ ``reasoning_effort: none`` a disabled ``reasoning_config`` projects on the custom profile+ ("Unrecognized request argument supplied: reasoning_effort", #112781); the route default is+ the right answer for such a model, so the reaction is one retry without any reasoning field."""+ status = getattr(exc, "status_code", None)+ if status is not None and status not in {400, 422}:+ return False+ return any(_is_unsupported_parameter_error(exc, name) for name in ("reasoning", "think"))+++def _without_reasoning_fields(kwargs: dict) -> Optional[dict]:+ """Copy *kwargs* without reasoning wire controls (top-level ``reasoning_effort``, the adapter's+ private ``_reasoning_config`` and every ``extra_body`` reasoning key); None when nothing was+ removed, so call sites don't retry an unchanged request."""+ retry_kwargs = dict(kwargs)+ changed = retry_kwargs.pop("reasoning_effort", None) is not None+ changed = retry_kwargs.pop("_reasoning_config", None) is not None or changed+ extra_body = retry_kwargs.get("extra_body")+ if isinstance(extra_body, dict):+ remaining = {k: v for k, v in extra_body.items() if str(k).strip().lower() not in _PROFILE_REASONING_KEYS}+ if len(remaining) != len(extra_body):+ if remaining:+ retry_kwargs["extra_body"] = remaining+ else:+ retry_kwargs.pop("extra_body", None)+ changed = True+ return retry_kwargs if changed else None++def _is_model_not_found_error(exc: Exception) -> bool:""""Requested model doesn't exist" (404 / invalid model) — typically a long-lived process pinned asince-dropped model. Excludes billing keywords, which :func:`_is_payment_error` owns."""@@ -6980,7 +7011,7 @@ _LadderRoute = NamedTuple("_LadderRoute", [def _ladder_parameter_rungs(first_err: Exception, route: _LadderRoute, kwargs: Dict[str, Any], max_tokens: Optional[int],):- """Rungs 1-3: retry without temperature / structured-output format / max_tokens.+ """Rungs 1-4: retry without temperature / structured-output format / reasoning field / max_tokens.Returns ``(response, None, kwargs)`` or ``(None, narrowed_err, stripped_kwargs)``."""client, task, tag = route.client, route.task, route.tagif "temperature" in kwargs and _is_unsupported_parameter_error(first_err, "temperature"):@@ -7003,6 +7034,19 @@ def _ladder_parameter_rungs(if first_err is None:return resp, None, retry_kwargskwargs = retry_kwargs+ # A chat-only model on an OpenAI-compatible relay rejects the profile's thinking-off encoding+ # (top-level ``reasoning_effort: none``); the caller only wanted "no thinking", which is what+ # such a model does anyway, so retry once with every reasoning field omitted (#112781).+ if _is_reasoning_field_rejection(first_err):+ retry_kwargs = _without_reasoning_fields(kwargs)+ if retry_kwargs is not None:+ logger.info("Auxiliary %s%s: provider rejected the reasoning field; retrying once "+ "without it (route default applies): %s", task or "call", tag, first_err)+ resp, first_err = yield from _rung(+ _LadderStep("call", (client, retry_kwargs)), _param_rung_accepts)+ if first_err is None:+ return resp, None, retry_kwargs+ kwargs = retry_kwargserr_str = str(first_err)# ZAI vision models reject max_tokens with code 1210 and a message that never# mentions "max_tokens", so detect it explicitly.diff --git a/tests/agent/test_auxiliary_reasoning_field_rejection_retry.py b/tests/agent/test_auxiliary_reasoning_field_rejection_retry.pynew file mode 100644index 00000000000..2862ffa0771--- /dev/null+++ b/tests/agent/test_auxiliary_reasoning_field_rejection_retry.py@@ -0,0 +1,76 @@+"""Reasoning-field rejection retry in ``agent.auxiliary_client`` (#112781).++The title lane disables reasoning (``reasoning_config={"enabled": False}``); on+``provider=custom`` the profile encodes that as top-level ``reasoning_effort: "none"``+(the deliberate Ollama /v1 / vLLM / GLM thinking-off wire). A chat-only model behind an+OpenAI-compatible relay (gpt-4.1-mini on a one-api style relay) answers+``400 Unrecognized request argument supplied: reasoning_effort`` and, before the fix,+the title was lost with no retry. The recovery is reactive like the temperature and+``response_format`` rungs: strip every reasoning field and retry once. The custom+profile's encoding itself is untouched so Ollama/vLLM/GLM users keep thinking-off.+"""++import asyncio+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from agent.auxiliary_client import async_call_llm, call_llm++_RELAY_400 = (+ "Error code: 400 - {'error': {'message': 'Unrecognized request argument supplied: "+ "reasoning_effort', 'type': 'invalid_request_error', 'param': '', 'code': None}}"+)+++def _custom_route_patches(client):+ return (+ patch("agent.auxiliary_client._resolve_task_provider_model",+ return_value=("custom", "gpt-4.1-mini", "https://relay.example/v1", "sk-x", None)),+ patch("agent.auxiliary_client._get_cached_client", return_value=(client, "gpt-4.1-mini")),+ patch("agent.auxiliary_client._validate_llm_response", side_effect=lambda resp, _task, **_kw: resp),+ patch("agent.auxiliary_client._try_payment_fallback", return_value=None),+ )+++def _call(async_mode, client, **kw):+ common = dict(task="title_generation", messages=[{"role": "user", "content": "hi"}],+ extra_body={"response_format": {"type": "json_object"}},+ reasoning_config={"enabled": False}, **kw)+ p1, p2, p3, p4 = _custom_route_patches(client)+ with p1, p2, p3, p4:+ if async_mode:+ return asyncio.run(async_call_llm(**common))+ return call_llm(**common)++[email protected]("async_mode", [False, True], ids=["sync", "async"])+def test_reasoning_effort_rejection_retries_once_without_reasoning_fields(async_mode):+ """Relay 400 naming ``reasoning_effort`` → one retry with no reasoning field; title lands."""+ client = MagicMock()+ client.base_url = "https://relay.example/v1"+ side_effect = [RuntimeError(_RELAY_400), {"ok": True}]+ client.chat.completions.create = AsyncMock(side_effect=side_effect) if async_mode else MagicMock(side_effect=side_effect)++ assert _call(async_mode, client) == {"ok": True}++ calls = client.chat.completions.create.call_args_list+ assert len(calls) == 2+ first, retry = calls[0].kwargs, calls[1].kwargs+ assert first["reasoning_effort"] == "none" # the deliberate thinking-off encoding still goes out first+ assert "reasoning_effort" not in retry+ assert "reasoning" not in (retry.get("extra_body") or {})+ assert retry["extra_body"]["response_format"] == {"type": "json_object"} # unrelated fields survive+ assert retry["model"] == first["model"]+++def test_unrelated_400_does_not_strip_reasoning_fields():+ """A 400 that does not name a reasoning field must not silently drop the thinking-off encoding."""+ client = MagicMock()+ client.base_url = "https://relay.example/v1"+ client.chat.completions.create.side_effect = RuntimeError(+ "HTTP 400: Invalid value: 'tool'. Supported values are: 'assistant'")++ with pytest.raises(RuntimeError, match="Invalid value"):+ _call(False, client)+ assert client.chat.completions.create.call_count == 1diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex faf68cab5ce..5b0e5bdda0e 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1400,6 +1400,8 @@ Auxiliary task blocks additionally accept a `reasoning_effort` knob:This is the per-task counterpart of the global `agent.reasoning_effort`: run compression at `low` or vision at `none` to cut side-task latency and cost when your main model is an expensive reasoning model, without touching your main chat behavior. It applies to auxiliary-client tasks such as `vision`, `compression`, `title_generation`, and `curator`, across all three auxiliary wire formats (chat completions, Codex Responses, Anthropic Messages). An explicit `extra_body.reasoning` on the same task wins over the shorthand.+If the endpoint rejects the reasoning field outright (a chat-only model behind an OpenAI-compatible relay answering `400 Unrecognized request argument supplied: reasoning_effort`), the auxiliary call is retried once with every reasoning field omitted, so the task (for example the session title) still completes with the endpoint's default behaviour.+**Background review is different:** a same-model review fork always inherits the parent's reasoning effort. `auxiliary.background_review.reasoning_effort` is ignored on that path, including when the parent provider/model is explicitly selected. This preserves byte-identical reasoning settings, system prompt, full conversation snapshot, and tool definitions for prompt-cache parity; there is no independent-effort switch for same-model reviews. See [background review reasoning](/user-guide/features/memory#same-model-review-reasoning). When the review is routed to a different provider/model, `reasoning_effort` applies to that routed fork (unset = the routed provider's default). Hermes prints a one-time warning when the key is set but the review runs on the main model.**MoA also uses a different configuration:** reasoning depth for Mixture-of-Agents is configured **per slot** in the MoA preset (`moa.presets.<name>.reference_models[].reasoning_effort` / `aggregator.reasoning_effort`), not on the `moa_reference`/`moa_aggregator` auxiliary blocks — see [Mixture of Agents](/user-guide/features/mixture-of-agents).