The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gemini): raise maxOutputTokens when thinking is enabled
lextiz95190e4544b7
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex 0fb31b7aa34..9477b2f7160 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -515,6 +515,49 @@ def _normalize_thinking_config(config: Any) -> Optional[Dict[str, Any]]:return normalized or None+def _thinking_requests_output_headroom(thinking_config: Any) -> bool:+ """Return True when Gemini will spend output tokens on thinking.++ Gemini bills thought tokens against ``maxOutputTokens``. A global+ Hermes ``max_tokens`` of 4096/16384 is enough for visible text, but+ Ultra/high thinking can consume the entire budget and leave+ ``finishReason=MAX_TOKENS`` with no complete answer. Continuations+ then abort after 4 retries.+ """+ normalized = _normalize_thinking_config(thinking_config)+ if not normalized:+ return False+ if normalized.get("includeThoughts") is False:+ return "thinkingLevel" in normalized or bool(normalized.get("thinkingBudget"))+ budget = normalized.get("thinkingBudget")+ if isinstance(budget, int) and budget <= 0 and "thinkingLevel" not in normalized:+ return False+ return True+++def _effective_gemini_max_output_tokens(+ max_tokens: Optional[int], thinking_config: Any+) -> int:+ """Resolve native ``maxOutputTokens``.++ Gemini's generateContent API does not treat an omitted cap as+ unlimited — it applies a low internal default and truncates. When+ thinking is enabled, also raise a too-small explicit cap to the+ published 65,535 ceiling so thought tokens do not starve the answer.+ """+ if max_tokens is None:+ return GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ try:+ requested = int(max_tokens)+ except (TypeError, ValueError):+ return GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ if requested <= 0:+ return GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ if _thinking_requests_output_headroom(thinking_config):+ return max(requested, GEMINI_DEFAULT_MAX_OUTPUT_TOKENS)+ return requested++def build_gemini_request(*,messages: List[Dict[str, Any]],@@ -542,20 +585,9 @@ def build_gemini_request(generation_config: Dict[str, Any] = {}if temperature is not None:generation_config["temperature"] = temperature- if max_tokens is not None:- generation_config["maxOutputTokens"] = max_tokens- else:- # Gemini's native generateContent does NOT treat an omitted- # maxOutputTokens as "use the model's full output budget" — it applies- # a low internal default and the model stops early with- # finishReason=MAX_TOKENS, truncating tool calls mid-stream (Hermes- # then retries 3× and refuses the incomplete call). Every current- # Gemini text model (2.5 + 3.x, flash / flash-lite / pro) caps at- # 65,535 output tokens, so default to that ceiling when the caller- # passes None ("unlimited"). See the OpenAI-compat path where omitting- # the field genuinely means full budget — that assumption does not- # hold on the native API.- generation_config["maxOutputTokens"] = GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ generation_config["maxOutputTokens"] = _effective_gemini_max_output_tokens(+ max_tokens, thinking_config+ )if top_p is not None:generation_config["topP"] = top_pif stop:diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex f6f0cd51842..d568da1d6a0 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -168,6 +168,26 @@ def _snake_case_gemini_thinking_config(config: dict | None) -> dict | None:return translated or None+def _raise_gemini_thinking_max_tokens(+ model: str,+ reasoning_config: dict | None,+ requested: Any,+) -> Any:+ """Raise Gemini output caps that thinking tokens would otherwise consume.++ Gemini bills thought tokens against maxOutputTokens / max_tokens. A+ global Hermes cap of 4096 is enough for visible text, but Ultra/high+ thinking can exhaust it on the first request and abort after four+ length-continuations.+ """+ thinking_config = _build_gemini_thinking_config(model, reasoning_config)+ if not thinking_config:+ return requested+ from agent.gemini_native_adapter import _effective_gemini_max_output_tokens++ return _effective_gemini_max_output_tokens(requested, thinking_config)++def _is_gemini_openai_compat_base_url(base_url: Any) -> bool:normalized = str(base_url or "").strip().rstrip("/").lower()if not normalized:@@ -517,9 +537,17 @@ class ChatCompletionsTransport(ProviderTransport):reasoning_config = _reasoning_config_for_model(model, params.get("reasoning_config"))if ephemeral is not None and max_tokens_fn:- api_kwargs.update(max_tokens_fn(ephemeral))+ api_kwargs.update(+ max_tokens_fn(+ _raise_gemini_thinking_max_tokens(model, reasoning_config, ephemeral)+ )+ )elif max_tokens is not None and max_tokens_fn:- api_kwargs.update(max_tokens_fn(max_tokens))+ api_kwargs.update(+ max_tokens_fn(+ _raise_gemini_thinking_max_tokens(model, reasoning_config, max_tokens)+ )+ )elif anthropic_max_out is not None:api_kwargs["max_tokens"] = anthropic_max_out@@ -711,18 +739,30 @@ class ChatCompletionsTransport(ProviderTransport):# they front several backends with different completion-token limits# (e.g. opencode-go: mimo-v2.5-pro = 131072).profile_max = profile.get_max_tokens(model)+ reasoning_config = _reasoning_config_for_model(model, params.get("reasoning_config"))if ephemeral is not None and max_tokens_fn:- api_kwargs.update(max_tokens_fn(ephemeral))+ api_kwargs.update(+ max_tokens_fn(+ _raise_gemini_thinking_max_tokens(model, reasoning_config, ephemeral)+ )+ )elif user_max is not None and max_tokens_fn:- api_kwargs.update(max_tokens_fn(user_max))+ api_kwargs.update(+ max_tokens_fn(+ _raise_gemini_thinking_max_tokens(model, reasoning_config, user_max)+ )+ )elif profile_max and max_tokens_fn:- api_kwargs.update(max_tokens_fn(profile_max))+ api_kwargs.update(+ max_tokens_fn(+ _raise_gemini_thinking_max_tokens(model, reasoning_config, profile_max)+ )+ )elif anthropic_max is not None:api_kwargs["max_tokens"] = anthropic_max# Provider-specific api_kwargs extras (reasoning_effort, metadata, etc.)- reasoning_config = _reasoning_config_for_model(model, params.get("reasoning_config"))extra_body_from_profile, top_level_from_profile = (profile.build_api_kwargs_extras(reasoning_config=reasoning_config,diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.pyindex ab98fed3719..dd291cad9e8 100644--- a/tests/agent/test_gemini_native_adapter.py+++ b/tests/agent/test_gemini_native_adapter.py@@ -290,6 +290,47 @@ def test_stream_event_translation_emits_tool_call_delta_with_stable_index():assert first[-1].choices[0].finish_reason == "tool_calls"+def test_build_gemini_request_preserves_explicit_max_tokens_without_thinking():+ from agent.gemini_native_adapter import build_gemini_request++ request = build_gemini_request(+ messages=[{"role": "user", "content": "hi"}],+ max_tokens=4096,+ )++ assert request["generationConfig"]["maxOutputTokens"] == 4096+ assert "thinkingConfig" not in request["generationConfig"]+++def test_build_gemini_request_raises_max_output_when_thinking_is_enabled():+ from agent.gemini_native_adapter import (+ GEMINI_DEFAULT_MAX_OUTPUT_TOKENS,+ build_gemini_request,+ )++ request = build_gemini_request(+ messages=[{"role": "user", "content": "hi"}],+ max_tokens=4096,+ thinking_config={"includeThoughts": True, "thinkingLevel": "high"},+ )++ assert request["generationConfig"]["maxOutputTokens"] == GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ assert request["generationConfig"]["thinkingConfig"]["thinkingLevel"] == "high"+++def test_build_gemini_request_does_not_raise_when_thinking_is_disabled():+ from agent.gemini_native_adapter import build_gemini_request++ request = build_gemini_request(+ messages=[{"role": "user", "content": "hi"}],+ max_tokens=4096,+ thinking_config={"includeThoughts": False},+ )++ assert request["generationConfig"]["maxOutputTokens"] == 4096+ assert request["generationConfig"]["thinkingConfig"]["includeThoughts"] is False++diff --git a/tests/agent/transports/test_chat_completions.py b/tests/agent/transports/test_chat_completions.pyindex d401d6d9587..ba36a0d8d60 100644--- a/tests/agent/transports/test_chat_completions.py+++ b/tests/agent/transports/test_chat_completions.py@@ -252,6 +252,40 @@ class TestChatCompletionsBuildKwargs:"thinking_level": "high",}+ def test_gemini_ultra_thinking_raises_first_request_max_tokens(self, transport):+ from agent.gemini_native_adapter import GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ from providers import get_provider_profile++ profile = get_provider_profile("gemini")+ kw = transport.build_kwargs(+ model="gemini-3.7-flash",+ messages=[{"role": "user", "content": "Hi"}],+ provider_profile=profile,+ provider_name="gemini",+ base_url=profile.base_url,+ max_tokens=4096,+ max_tokens_param_fn=lambda n: {"max_tokens": n},+ reasoning_config={"enabled": True, "effort": "ultra"},+ )+ assert kw["max_tokens"] == GEMINI_DEFAULT_MAX_OUTPUT_TOKENS+ assert kw["extra_body"]["thinking_config"]["thinkingLevel"] == "high"++ def test_gemini_without_thinking_keeps_explicit_max_tokens(self, transport):+ from providers import get_provider_profile++ profile = get_provider_profile("gemini")+ kw = transport.build_kwargs(+ model="gemini-3.7-flash",+ messages=[{"role": "user", "content": "Hi"}],+ provider_profile=profile,+ provider_name="gemini",+ base_url=profile.base_url,+ max_tokens=4096,+ max_tokens_param_fn=lambda n: {"max_tokens": n},+ )+ assert kw["max_tokens"] == 4096++