The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: chain auxiliary parameter-rejection retries on primary and fallback requests
teknium11d1c4ac7303e
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex d4eda237371..7816c3ad0b4 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3187,6 +3187,8 @@ def _is_unsupported_parameter_error(exc: Exception, param: str) -> bool:"unsupported parameter", "unsupported_parameter", "not supported", "does not support","doesn't support", "is deprecated for this model","unknown parameter", "unrecognized request argument", "unrecognized parameter", "invalid parameter",+ # Strict pydantic-validated gateways (Fireworks) name the unknown field this way (#109774).+ "extra inputs are not permitted",))@@ -3885,8 +3887,13 @@ def _call_fallback_candidate_sync(),task,)+ from agent.auxiliary_fallback_recovery import send_with_parameter_rungs++ def _send_recovering(client: Any, request_kwargs: Dict[str, Any], dest: _FallbackDestination) -> Any:+ return send_with_parameter_rungs(+ lambda c, kw: _send(c, kw, dest), client, request_kwargs, task=task)try:- return _send(fb_client, fb_kwargs, destination)+ return _send_recovering(fb_client, fb_kwargs, destination)except Exception as fb_err:if not _is_auth_error(fb_err):raise@@ -3896,7 +3903,7 @@ def _call_fallback_candidate_sync(if retry is not None:failed_destination = retry[2]try:- return _send(*retry)+ return _send_recovering(*retry)except Exception as retry_err:if not _is_auth_error(retry_err):raise@@ -3924,8 +3931,13 @@ async def _call_fallback_candidate_async(await _relay_async_completion(client, request_kwargs, provider=dest.provider, api_mode=dest.api_mode),task,)+ from agent.auxiliary_fallback_recovery import send_with_parameter_rungs_async++ async def _send_recovering(client: Any, request_kwargs: Dict[str, Any], dest: _FallbackDestination) -> Any:+ return await send_with_parameter_rungs_async(+ lambda c, kw: _send(c, kw, dest), client, request_kwargs, task=task)try:- return await _send(fb_client, fb_kwargs, destination)+ return await _send_recovering(fb_client, fb_kwargs, destination)except Exception as fb_err:if not _is_auth_error(fb_err):raise@@ -3935,7 +3947,7 @@ async def _call_fallback_candidate_async(if retry is not None:failed_destination = retry[2]try:- return await _send(*retry)+ return await _send_recovering(*retry)except Exception as retry_err:if not _is_auth_error(retry_err):raise@@ -7010,8 +7022,10 @@ def _param_rung_accepts(exc: Exception) -> bool:chains with the stripped kwargs; re-raise anything those chains won't handle."""return (_is_payment_error(exc) or _is_connection_error(exc) or _is_auth_error(exc)or "max_tokens" in str(exc) or "unsupported_parameter" in str(exc)- # Parameter rungs chain (temperature-strip retry 400s on reasoning_effort / response_format),- # and a route-gating 400 after a strip still reaches the provider-fallback rung.+ # Parameter rungs chain in any order (a reasoning-strip retry can 400 on temperature,+ # a temperature-strip retry on max_tokens), and a route-gating 400 after a strip still+ # reaches the provider-fallback rung.+ or _is_unsupported_parameter_error(exc, "temperature")or _is_reasoning_field_rejection(exc) or _is_structured_output_rejection(exc)or _is_model_incompatible_error(exc))@@ -7030,61 +7044,70 @@ _LadderRoute = NamedTuple("_LadderRoute", [])+def _without_temperature(kwargs: dict) -> Optional[dict]:+ """Copy *kwargs* without ``temperature``; None when it was not sent."""+ return {k: v for k, v in kwargs.items() if k != "temperature"} if "temperature" in kwargs else None+++def _without_max_tokens(kwargs: dict) -> Optional[dict]:+ """Copy *kwargs* without either output cap; None when neither was sent."""+ retry_kwargs = {k: v for k, v in kwargs.items() if k not in ("max_tokens", "max_completion_tokens")}+ return retry_kwargs if len(retry_kwargs) != len(kwargs) else None+++def _is_max_tokens_rejection(exc: Exception, client: Any) -> bool:+ err_str = str(exc)+ # ZAI vision models reject max_tokens with code 1210 and a message that never+ # mentions "max_tokens", so detect it explicitly.+ is_zai_param_error = "1210" in err_str and "bigmodel" in str(getattr(client, "base_url", ""))+ return ("max_tokens" in err_str or "unsupported_parameter" in err_str+ or _is_unsupported_parameter_error(exc, "max_tokens") or is_zai_param_error)+++def _parameter_rungs(client: Any, max_tokens: Optional[int]) -> tuple:+ """Ordered ``(matches, strip, log message)`` parameter rungs; ``strip`` returns None when the+ field was not on the wire, so an unchanged request is never re-sent."""+ return (+ (lambda exc: _is_unsupported_parameter_error(exc, "temperature"), _without_temperature,+ "provider rejected temperature; retrying without it"),+ (_is_structured_output_rejection, _without_structured_output_format,+ "provider rejected the structured-output format field; retrying without it "+ "(schema enforcement degrades to prompt compliance)"),+ # A chat-only model on an OpenAI-compatible relay rejects the profile's thinking-off encoding+ # (top-level ``reasoning_effort: none``), and strict-schema gateways reject the generic+ # ``extra_body.reasoning`` fallback outright (#109774); the caller only wanted "no thinking",+ # so retry with every reasoning field omitted and let the route default apply (#112781).+ (_is_reasoning_field_rejection, _without_reasoning_fields,+ "provider rejected the reasoning field; retrying without it (route default applies)"),+ (lambda exc: max_tokens is not None and _is_max_tokens_rejection(exc, client), _without_max_tokens,+ "provider rejected the output cap; retrying without it"),+ )++def _ladder_parameter_rungs(first_err: Exception, route: _LadderRoute, kwargs: Dict[str, Any], max_tokens: Optional[int],):- """Rungs 1-4: retry without temperature / structured-output format / reasoning field / max_tokens.+ """Parameter rungs: retry without temperature / structured-output format / reasoning field /+ max_tokens. Rungs chain in whichever order the provider raises them (reasoning models reject+ temperature AND max_tokens; a reasoning-strip retry can then trip temperature, #78273), each+ field stripped at most once, so a request with N rejected fields recovers in N retries.Returns ``(response, None, kwargs)`` or ``(None, narrowed_err, stripped_kwargs)``."""client, task, tag = route.client, route.task, route.tag- if "temperature" in kwargs and _is_unsupported_parameter_error(first_err, "temperature"):- retry_kwargs = {k: v for k, v in kwargs.items() if k != "temperature"}- logger.info("Auxiliary %s%s: provider rejected temperature; retrying once without it",- task or "call", tag)+ rungs = list(_parameter_rungs(client, max_tokens))+ while rungs:+ hit = next(((matches, strip, message) for matches, strip, message in rungs+ if matches(first_err) and strip(kwargs) is not None), None)+ if hit is None:+ break+ rungs.remove(hit)+ matches, strip, message = hit+ retry_kwargs = strip(kwargs)+ logger.info("Auxiliary %s%s: %s: %s", task or "call", tag, message, 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_kwargskwargs = retry_kwargs- if _is_structured_output_rejection(first_err):- retry_kwargs = _without_structured_output_format(kwargs)- if retry_kwargs is not None:- logger.info("Auxiliary %s%s: provider rejected the structured-output "- "format field; retrying once without it (schema "- "enforcement degrades to prompt compliance): %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_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_kwargs- err_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.- _is_zai_param_error = "1210" in err_str and "bigmodel" in str(getattr(client, "base_url", ""))- if max_tokens is not None and (- "max_tokens" in err_str or "unsupported_parameter" in err_str- or _is_unsupported_parameter_error(first_err, "max_tokens") or _is_zai_param_error- ):- kwargs.pop("max_tokens", None)- kwargs.pop("max_completion_tokens", None)- resp, first_err = yield from _rung(- _LadderStep("call", (client, kwargs)),- lambda exc: _is_payment_error(exc) or _is_connection_error(exc) or _is_rate_limit_error(exc),- )- if first_err is None:- return resp, None, kwargsreturn None, first_err, kwargsdiff --git a/agent/auxiliary_fallback_recovery.py b/agent/auxiliary_fallback_recovery.pynew file mode 100644index 00000000000..12371d7d68a--- /dev/null+++ b/agent/auxiliary_fallback_recovery.py@@ -0,0 +1,46 @@+"""Parameter-rejection recovery for auxiliary fallback candidates.++The primary auxiliary request runs the full recovery ladder in ``auxiliary_client``; a fallback+candidate (per-task chain, main fallback chain, discovery) used to get a single shot, so a fallback+model that rejects ``temperature``, ``max_tokens`` or a reasoning field failed the whole task even+though the same parameter rungs would have recovered it on the primary path (#78273, #72351).+This module runs those rungs — and only those — around a candidate's request.+"""+from typing import Any, Awaitable, Callable, Dict, Optional+++def _parameter_ladder(first_err: Exception, client: Any, kwargs: Dict[str, Any], *,+ task: Optional[str], tag: str):+ from agent.auxiliary_client import _LadderRoute, _ladder_parameter_rungs+ route = _LadderRoute(client, task, tag, bool(tag), "", "", None, None, None, None, None, None, None)+ max_tokens = kwargs.get("max_tokens") or kwargs.get("max_completion_tokens")+ resp, err, _ = yield from _ladder_parameter_rungs(first_err, route, kwargs, max_tokens)+ if err is None:+ return resp+ raise err+++def send_with_parameter_rungs(+ send: Callable[[Any, Dict[str, Any]], Any], client: Any, kwargs: Dict[str, Any], *, task: Optional[str],+) -> Any:+ """``send(client, kwargs)``; on a parameter 400, retry through the parameter rungs. Any other+ error (auth, payment, connection) propagates unchanged for the caller's own handling."""+ from agent.auxiliary_client import _drive_ladder+ try:+ return send(client, kwargs)+ except Exception as first_err:+ ladder = _parameter_ladder(first_err, client, kwargs, task=task, tag="")+ return _drive_ladder(ladder, lambda step: send(*step.args))+++async def send_with_parameter_rungs_async(+ send: Callable[[Any, Dict[str, Any]], Awaitable[Any]], client: Any, kwargs: Dict[str, Any], *,+ task: Optional[str],+) -> Any:+ """Async twin of :func:`send_with_parameter_rungs`."""+ from agent.auxiliary_client import _drive_ladder_async+ try:+ return await send(client, kwargs)+ except Exception as first_err:+ ladder = _parameter_ladder(first_err, client, kwargs, task=task, tag=" (async)")+ return await _drive_ladder_async(ladder, lambda step: send(*step.args))diff --git a/tests/agent/test_auxiliary_parameter_rung_chaining.py b/tests/agent/test_auxiliary_parameter_rung_chaining.pynew file mode 100644index 00000000000..7ebae5d0642--- /dev/null+++ b/tests/agent/test_auxiliary_parameter_rung_chaining.py@@ -0,0 +1,79 @@+"""Auxiliary parameter-rejection rungs chain in any order, on the primary AND the fallback path.++Reasoning models reject several request fields at once (``temperature`` and ``max_tokens`` on+gpt-5, #78273), a reasoning-strip retry can then 400 on ``temperature`` (#72351), and strict-schema+gateways phrase an unknown ``reasoning`` field as "Extra inputs are not permitted" (#109774).+Each rejected field must be stripped in whatever order the provider raises them, and a fallback+candidate must get the same recovery as the primary request.+"""+from types import SimpleNamespace+from unittest.mock import MagicMock++from agent.auxiliary_client import (+ _call_fallback_candidate_sync,+ _drive_ladder,+ _is_reasoning_field_rejection,+ _ladder_parameter_rungs,+ _LadderRoute,+)+++class _Bad400(Exception):+ status_code = 400+++def _ok(text="ok"):+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=text), finish_reason="stop")])+++def _rejecting_client(*rejected_fields):+ """Fake OpenAI client that 400s while any of ``rejected_fields`` is still on the wire."""+ client = MagicMock(base_url="https://api.example/v1")++ def create(**kwargs):+ body = dict(kwargs)+ body.update(body.pop("extra_body", None) or {})+ for field in rejected_fields:+ if field in body:+ phrase = {+ "reasoning": "Extra inputs are not permitted, field: 'reasoning'",+ "reasoning_effort": "Unsupported value: 'reasoning_effort' does not support 'none' with this model.",+ "temperature": "Unsupported value: 'temperature' does not support 0.3 with this model.",+ "max_tokens": "Unsupported parameter: 'max_tokens' is not supported with this model.",+ }[field]+ raise _Bad400(f"Error code: 400 - {phrase}")+ return _ok()++ client.chat.completions.create.side_effect = create+ return client+++def test_primary_rungs_chain_in_provider_order_and_strip_each_field_once():+ client = _rejecting_client("reasoning_effort", "temperature", "max_tokens")+ kwargs = {"model": "m", "messages": [], "temperature": 0.3, "max_tokens": 64, "reasoning_effort": "none"}+ route = _LadderRoute(client, "title_generation", "", False, "", "", None, None, None, None, None, None, None)+ first_err = _Bad400("Error code: 400 - Unsupported value: 'reasoning_effort' does not support 'none'")++ def perform(step):+ step_client, step_kwargs = step.args+ return step_client.chat.completions.create(**step_kwargs)++ resp, err, final_kwargs = _drive_ladder(_ladder_parameter_rungs(first_err, route, kwargs, 64), perform)++ assert err is None and resp.choices[0].message.content == "ok"+ assert not {"temperature", "max_tokens", "reasoning_effort"} & set(final_kwargs)+ # One retry per rejected field: reasoning_effort → temperature → max_tokens, nothing re-sent unchanged.+ assert client.chat.completions.create.call_count == 3+ assert _is_reasoning_field_rejection(_Bad400("Extra inputs are not permitted, field: 'reasoning'"))+++def test_fallback_candidate_recovers_from_rejected_temperature():+ client = _rejecting_client("temperature")+ resp = _call_fallback_candidate_sync(+ client, "gpt-5-mini", "fallback_chain[0](openai)", task="title_generation",+ messages=[{"role": "user", "content": "hi"}], temperature=0.3, max_tokens=16, tools=None,+ effective_timeout=30.0, effective_extra_body={}, reasoning_config=None,+ )+ assert resp.choices[0].message.content == "ok"+ sent = [c.kwargs for c in client.chat.completions.create.call_args_list]+ assert [("temperature" in k) for k in sent] == [True, False]