The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gemini): gate thinkingLevel and sampling on Gemini version >= 3, not a "gemini-3" prefix
kshitijk4poor4ec52fc9586d
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 9a0c21fc4e7..5f90dd890f2 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -32,7 +32,7 @@ from agent.error_classifier import (is_reasoning_required_rejection,)from agent.auxiliary_reasoning_floor import remember_reasoning_floor, with_reasoning_floor-from agent.auxiliary_structured_output import remember_structured_output_rejection+from agent.auxiliary_structured_output import _route_key, remember_structured_output_rejectionfrom agent.codex_headers import (CODEX_AUX_BASE_URL as _CODEX_AUX_BASE_URL,apply_required_codex_headers as _apply_required_codex_headers,@@ -641,19 +641,6 @@ def _is_openai_default_temperature_only(model: Optional[str]) -> bool:return bare.startswith(("gpt-5", "o1", "o3", "o4")) and not bare.startswith("gpt-5-chat")-def _is_gemini_sampling_deprecated(model: Optional[str]) -> bool:- """True for Gemini 3.6+ models, where Google deprecated the sampling controls- (``temperature``, ``top_p``, ``top_k``): the backend ignores them today and they are- slated for removal. Omit ``temperature`` up front rather than send a dead (or, on some- surfaces, rejected) parameter. Older Gemini families (2.x, 3.0–3.5) keep it."""- bare = _bare_model(model)- match = re.match(r"^gemini-(\d+)(?:\.(\d+))?", bare)- if not match:- return False- major, minor = int(match.group(1)), int(match.group(2) or 0)- return major > 3 or (major == 3 and minor >= 6)--# Routes (host + model) that rejected ``temperature`` at runtime; the next call omits it up front# instead of paying the 400 round-trip again (the retry alone left #51083's first call to time out)._TEMPERATURE_REJECTED_ROUTES: set = set()@@ -662,25 +649,21 @@ _TEMPERATURE_REJECTED_ROUTES: set = set()def remember_temperature_rejection(provider: Optional[str], base_url: Optional[str], rejected_kwargs: dict[str, Any], error: BaseException,) -> None:- from agent.auxiliary_structured_output import _route_key_TEMPERATURE_REJECTED_ROUTES.add((_route_key(provider, base_url), _bare_model(rejected_kwargs.get("model"))))def _fixed_temperature_for_model(model: Optional[str], base_url: Optional[str] = None, provider: Optional[str] = None,) -> Optional[float] | object:- """``OMIT_TEMPERATURE`` (drop the key; Kimi/Moonshot, OpenAI reasoning families, routes that- already rejected it), a fixed ``float``, or ``None``."""+ """``OMIT_TEMPERATURE`` (drop the key; Kimi/Moonshot, OpenAI reasoning families, Gemini 3.6+, routes+ that already rejected it), a fixed ``float``, or ``None``."""if _is_kimi_model(model):logger.debug("Omitting temperature for Kimi model %r (server-managed)", model)return OMIT_TEMPERATURE- if _is_openai_default_temperature_only(model):- logger.debug("Omitting temperature for %r (accepts only the default)", model)- return OMIT_TEMPERATURE- if _is_gemini_sampling_deprecated(model):- logger.debug("Omitting temperature for %r (Gemini 3.6+ deprecated sampling)", model)+ from agent.gemini_native_adapter import gemini_sampling_deprecated+ if _is_openai_default_temperature_only(model) or gemini_sampling_deprecated(_bare_model(model)):+ logger.debug("Omitting temperature for %r (default-only, or Gemini 3.6+ ignores sampling)", model)return OMIT_TEMPERATURE- from agent.auxiliary_structured_output import _route_keyif (_route_key(provider, base_url), _bare_model(model)) in _TEMPERATURE_REJECTED_ROUTES:logger.debug("Omitting temperature for %r (route rejected it earlier)", model)return OMIT_TEMPERATUREdiff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex 61e7e56966e..1a5f75c4145 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -112,8 +112,29 @@ def gemini_requires_tool_call_ids(model: str) -> bool:on the major version. Mirrors earendil-works/pi#7494 (their fix for the same class of bug in thegoogle-shared converter)."""- match = re.match(r"gemini-(\d+)", bare_gemini_model_id(model).lower())- return match is not None and int(match.group(1)) >= 3+ return _gemini_version(model) >= (3, 0)+++def _gemini_version(model: str) -> tuple[int, int]:+ """(major, minor) of a Gemini model id: ``gemini-4-argon`` -> (4, 0), ``google/gemini-3.8-flash`` ->+ (3, 8); (0, 0) for non-Gemini and unversioned ids (``gemini-flash-latest``, ``gemini-exp-1206``)."""+ match = re.match(r"gemini-(\d+)(?:\.(\d+))?", bare_gemini_model_id(model).lower())+ return (int(match.group(1)), int(match.group(2) or 0)) if match else (0, 0)+++def gemini_uses_thinking_level(model: str) -> bool:+ """Gemini 3 and every later generation steer thinking with the ``thinkingLevel`` enum (``thinkingBudget``+ is deprecated there), as do the ``gemini-*-latest`` aliases, which Google hot-swaps to the newest+ release of each variant. A version-number gate, not a ``gemini-3`` prefix, so a new generation+ (``gemini-4-argon``) isn't silently treated as legacy."""+ bare = bare_gemini_model_id(model).lower()+ return (bare.startswith("gemini-") and bare.endswith("-latest")) or _gemini_version(bare) >= (3, 0)+++def gemini_sampling_deprecated(model: str) -> bool:+ """Gemini 3.6+ (Gemini 4 Argon included) ignores ``temperature``/``top_p``/``top_k`` and Google+ slated them for removal; older families (2.x, 3.0-3.5) keep them."""+ return _gemini_version(model) >= (3, 6)_API_VERSION_SEGMENT = re.compile(r"^v\d+(?:alpha|beta)?\d*$", re.IGNORECASE)diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex d4032305c12..971ead9b650 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -163,6 +163,8 @@ def _reasoning_config_for_model(model: str, reasoning_config: dict | None) -> didef _build_gemini_thinking_config(model: str, reasoning_config: dict | None) -> dict | None:"""Translate Hermes/OpenRouter-style reasoning config to Gemini thinkingConfig."""+ from agent.gemini_native_adapter import gemini_uses_thinking_level+if not isinstance(reasoning_config, dict):return Nonenormalized_model = (model or "").strip().lower().removeprefix("google/")@@ -193,7 +195,7 @@ def _build_gemini_thinking_config(model: str, reasoning_config: dict | None) ->config: dict[str, Any] = {"includeThoughts": False}if normalized_model.startswith("gemini-2.5-"):config["thinkingBudget"] = 0- elif normalized_model == "gemini-flash-latest" or normalized_model.startswith("gemini-3"):+ elif gemini_uses_thinking_level(normalized_model):config["thinkingLevel"] = "low"return configthinking_config: dict[str, Any] = {"includeThoughts": True}@@ -202,16 +204,16 @@ def _build_gemini_thinking_config(model: str, reasoning_config: dict | None) ->return thinking_configif effort not in {"minimal", "low", "medium", "high", "xhigh", "max", "ultra"}:effort = "medium"- # Gemini 3 Flash documents low/medium/high thinking levels; Gemini 3 Pro- # is stricter (low/high). Clamp Hermes' wider effort set to what each- # family accepts so we never forward an undocumented level verbatim.- if normalized_model.startswith("gemini-3"):- if "flash" in normalized_model:+ # Gemini 3 Pro is strict (low/high); every other thinking-level model (3.x Flash, Gemini 4 Argon)+ # documents low/medium/high, and "minimal" is not universal (Argon 400s on it). Clamp Hermes' wider+ # effort set to what each family accepts so we never forward an undocumented level verbatim.+ if gemini_uses_thinking_level(normalized_model):+ if "pro" in normalized_model:+ thinking_config["thinkingLevel"] = "high" if effort in _HIGH_EFFORTS else "low"+ else:thinking_config["thinkingLevel"] = ("low" if effort in {"minimal", "low"} else "high" if effort in _HIGH_EFFORTS else "medium")- elif "pro" in normalized_model:- thinking_config["thinkingLevel"] = "high" if effort in _HIGH_EFFORTS else "low"return thinking_configdiff --git a/tests/agent/test_gemini_thinking_config.py b/tests/agent/test_gemini_thinking_config.pyindex 3b95049b3dc..598ee999e62 100644--- a/tests/agent/test_gemini_thinking_config.py+++ b/tests/agent/test_gemini_thinking_config.py@@ -22,6 +22,9 @@ from agent.transports.chat_completions import (("gemini-2.5-flash", ("thinkingBudget", 0)), # 2.5 still documents thinkingBudget("gemini-3.6-flash", ("thinkingLevel", "low")), # 3+ deprecated thinkingBudget → thinkingLevel("gemini-3.1-pro", ("thinkingLevel", "low")),+ ("gemini-4-argon", ("thinkingLevel", "low")), # a new generation is not treated as legacy+ ("google/gemini-4-argon", ("thinkingLevel", "low")),+ ("gemini-flash-lite-latest", ("thinkingLevel", "low")), # every -latest alias, not just flash("gemini-flash-latest", ("thinkingLevel", "low")),("gemini-1.5-flash", None), # pre-2.5: thinking control undocumented],@@ -87,3 +90,29 @@ def test_gemini4_maps_effort_to_thinking_level_and_long_decode_budget(reasoning,compat = profile.build_extra_body(model="gemini-4-argon", reasoning_config=reasoning,base_url="https://generativelanguage.googleapis.com/v1beta/openai")assert "max_output_tokens" not in compat+++ "model,effort,level",+ [+ # Argon documents low/medium/high and 400s on "minimal" — clamp, never forward it.+ ("gemini-4-argon", "minimal", "low"),+ ("gemini-4-argon", "low", "low"),+ ("gemini-4-argon", "medium", "medium"),+ ("gemini-4-argon", "xhigh", "high"),+ ("google/gemini-4-argon", "high", "high"),+ ("gemini-3.8-flash", "medium", "medium"),+ ("gemini-3.1-pro", "medium", "low"), # 3 Pro stays strict (low/high)+ ("gemini-3.1-pro", "high", "high"),+ ("gemini-pro-latest", "high", "high"),+ ],+)+def test_enabled_reasoning_maps_effort_to_thinking_level_on_gemini_3_and_later(model, effort, level):+ config = _build_gemini_thinking_config(model, {"enabled": True, "effort": effort})+ assert config == {"includeThoughts": True, "thinkingLevel": level}+++def test_unversioned_non_alias_gemini_ids_get_no_thinking_level():+ # Only a version >= 3 or a -latest alias earns a level; unknown ids keep the no-guess default.+ assert _build_gemini_thinking_config("gemini-exp-1206", {"effort": "high"}) == {"includeThoughts": True}+ assert _build_gemini_thinking_config("gemini-1.5-pro", {"effort": "high"}) == {"includeThoughts": True}diff --git a/tests/agent/test_unsupported_temperature_retry.py b/tests/agent/test_unsupported_temperature_retry.pyindex 41d7d54b195..b6e15b49200 100644--- a/tests/agent/test_unsupported_temperature_retry.py+++ b/tests/agent/test_unsupported_temperature_retry.py@@ -56,7 +56,7 @@ def test_openai_default_only_families_omit_temperature_up_front(model):assert _build_call_kwargs("openai-api", accepts, [], temperature=0.1)["temperature"] == 0.1[email protected]("model", ["gemini-3.6-flash", "google/gemini-3.7-flash", "gemini-3.8-flash", "gemini-4.0-flash"])[email protected]("model", ["gemini-3.6-flash", "google/gemini-3.7-flash", "gemini-3.8-flash", "gemini-4.0-flash", "gemini-4-argon", "google/gemini-4-argon"])def test_gemini_36_plus_omits_temperature_up_front(model):"""Gemini 3.6+ deprecated the sampling controls (temperature/top_p/top_k); omit temperature upfront instead of sending a dead (or, on some surfaces, rejected) parameter. Older Gemini