Skip to content

The agent that grows with you

feat(gemini): Gemini 4 Argon support with long decode

Teknium7e85c68a0d93
diff --git a/agent/gemini_long_decode.py b/agent/gemini_long_decode.py
new file mode 100644
index 00000000000..ef540a2a0ac
--- /dev/null
+++ b/agent/gemini_long_decode.py
@@ -0,0 +1,78 @@
+"""Gemini long decode: one response spread over several generateContent hops.
+
+Gemini 4 caps each request (32,768 tokens unary, 65,536 streamed) but lets ``maxOutputTokens`` reach
+1,048,576 minus the input. A hop that hits the per-request cap with budget left ends with
+``finishReason: CONTINUATION`` plus a ``continuationToken``; the client resends the SAME request with
+that token (never the partial output) until any other finish reason. Each hop re-reads the prompt plus
+everything generated so far, so per-hop ``promptTokenCount`` grows: usage is summed for billing (what
+the google-genai SDK reports and Google bills) while the first hop's prompt is kept as the context size,
+because compaction fed the summed prompt would fire far too early.
+Docs: https://ai.google.dev/gemini-api/docs/generate-content/long-decode
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+# Effort above ``high`` (Gemini 4's top thinkingLevel) buys a larger total thinking+output budget.
+# 262,144 is Google's starting point for hard reasoning; the API caps 1,048,576 at the window minus input.
+_LONG_DECODE_BUDGETS = {"xhigh": 262_144, "max": 1_048_576, "ultra": 1_048_576}
+_USAGE_COUNT_KEYS = (
+ "promptTokenCount", "cachedContentTokenCount", "candidatesTokenCount", "thoughtsTokenCount",
+ "toolUsePromptTokenCount", "totalTokenCount",
+)
+
+
+def long_decode_max_output_tokens(model: str, reasoning_config: Any) -> Optional[int]:
+ """Total output budget a Gemini 4 request gets for its reasoning effort, or None (per-request cap)."""
+ name = (model or "").strip().lower().removeprefix("google/")
+ if not name.startswith("gemini-4") or not isinstance(reasoning_config, dict) or reasoning_config.get("enabled") is False:
+ return None
+ return _LONG_DECODE_BUDGETS.get(str(reasoning_config.get("effort") or "").strip().lower())
+
+
+def _candidate(payload: dict[str, Any]) -> dict[str, Any]:
+ candidates = payload.get("candidates") if isinstance(payload, dict) else None
+ first = candidates[0] if isinstance(candidates, list) and candidates else None
+ return first if isinstance(first, dict) else {}
+
+
+def continuation_token(payload: dict[str, Any]) -> Optional[str]:
+ """The token to resend with when this hop ended on CONTINUATION; None on any other finish."""
+ cand = _candidate(payload)
+ token = cand.get("continuationToken")
+ return token if str(cand.get("finishReason") or "").upper() == "CONTINUATION" and isinstance(token, str) and token else None
+
+
+def merge_hop_usage(hops: list[dict[str, Any]]) -> dict[str, Any]:
+ """Sum every count across hops; ``initialPromptTokenCount`` (the google-genai name) is hop 1's prompt."""
+ merged = {key: sum(int(h.get(key) or 0) for h in hops) for key in _USAGE_COUNT_KEYS if any(key in h for h in hops)}
+ merged["initialPromptTokenCount"] = int(hops[0].get("promptTokenCount") or 0) if hops else 0
+ return merged
+
+
+def merge_hop_responses(hops: list[dict[str, Any]]) -> dict[str, Any]:
+ """One generateContent response whose model turn joins every hop's parts, ending as the last hop did."""
+ parts = [part for hop in hops for part in ((_candidate(hop).get("content") or {}).get("parts") or [])]
+ last = _candidate(hops[-1])
+ candidate = {**last, "content": {**(last.get("content") or {}), "role": "model", "parts": parts}}
+ usage = merge_hop_usage([hop.get("usageMetadata") or {} for hop in hops])
+ return {**hops[-1], "candidates": [candidate], "usageMetadata": usage}
+
+
+def split_stream_continuation(event: dict[str, Any], hop_usage: list[dict[str, Any]]) -> tuple[dict[str, Any], Optional[str]]:
+ """``(event to translate, token)`` for one SSE event of a possibly multi-hop stream.
+
+ A CONTINUATION finish is not the end: its finish reason and (per-stream cumulative) usage are
+ held back in ``hop_usage`` and the token returned for the next hop. The real final event gets
+ the usage summed over every hop. Mid-stream checkpoint tokens are ignored: a dropped stream is
+ retried from the start by the caller, which is always valid (resuming is a cost optimisation).
+ """
+ token = continuation_token(event)
+ if token:
+ hop_usage.append(event.get("usageMetadata") or {})
+ cand = {k: v for k, v in _candidate(event).items() if k not in ("finishReason", "continuationToken")}
+ return {k: v for k, v in event.items() if k != "usageMetadata"} | {"candidates": [cand]}, token
+ if hop_usage and _candidate(event).get("finishReason"):
+ return {**event, "usageMetadata": merge_hop_usage([*hop_usage, event.get("usageMetadata") or {}])}, None
+ return event, None
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 53fe8905ee5..24287e022ee 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -20,6 +20,7 @@ from typing import Any, Dict, Iterator, List, Optional
import httpx
from agent.bounded_response import read_streaming_error_body
+from agent.gemini_long_decode import continuation_token, merge_hop_responses, split_stream_continuation
from agent.retry_utils import parse_retry_after_seconds
from agent.gemini_schema import prepare_gemini_tool_parameters, sanitize_gemini_tool_parameters
@@ -82,6 +83,7 @@ _END = object() # stream-exhausted marker for _advance_stream_iterator
_TOOL_CHOICE_MODES = {"auto": "AUTO", "required": "ANY", "none": "NONE"}
_FINISH_REASON_MAP = {
"STOP": "stop", "MAX_TOKENS": "length", "SAFETY": "content_filter", "RECITATION": "content_filter", "OTHER": "stop",
+ "CONTINUATION": "length", # only reachable without a continuationToken: the output was cut short
}
_HTTP_ERROR_CODES = {401: "gemini_unauthorized", 429: "gemini_rate_limited", 404: "gemini_model_not_found"}
_MISSING_KEY_ERROR = (
@@ -117,11 +119,12 @@ _API_VERSION_SEGMENT = re.compile(r"^v\d+(?:alpha|beta)?\d*$", re.IGNORECASE)
def is_vertex_express_base_url(base_url: str) -> bool:
- """An aiplatform host without a project path — the express surface. The OAuth Vertex provider's
- ``…/projects/{p}/locations/{r}/endpoints/openapi`` base is OpenAI-compatible and must stay off
+ """An aiplatform host speaking the native API with an API key: the bare express surface, or its
+ ``…/projects/{p}/locations/{l}`` form, which reaches models served only in ``global`` (Gemini 4).
+ The OAuth Vertex provider's ``…/endpoints/openapi`` base is OpenAI-compatible and must stay off
the native adapter."""
normalized = str(base_url or "").strip().lower()
- return "aiplatform.googleapis.com" in normalized and "/projects/" not in normalized
+ return "aiplatform.googleapis.com" in normalized and "/endpoints/" not in normalized
def normalize_gemini_base_url(base_url: Optional[str]) -> str:
@@ -145,7 +148,7 @@ def normalize_gemini_base_url(base_url: Optional[str]) -> str:
if is_vertex_express_base_url(trimmed):
if trimmed.lower().endswith("/publishers/google"):
return trimmed
- if not _API_VERSION_SEGMENT.match(trimmed.rsplit("/", 1)[-1]):
+ if "/projects/" not in trimmed.lower() and not _API_VERSION_SEGMENT.match(trimmed.rsplit("/", 1)[-1]):
trimmed = f"{trimmed}/v1beta1"
return f"{trimmed}/publishers/google"
if _API_VERSION_SEGMENT.match(trimmed.rsplit("/", 1)[-1]):
@@ -591,10 +594,12 @@ def _usage_from_metadata(usage_meta: dict[str, Any]) -> SimpleNamespace:
them. Absent on non-thinking/older responses, which keeps their numbers as-is."""
count = lambda key: int(usage_meta.get(key) or 0)
reasoning_tokens = count("thoughtsTokenCount")
+ # Multi-hop long decode: the counts are summed over hops (billing); the context size is hop 1's prompt.
+ initial = {"initial_prompt_tokens": count("initialPromptTokenCount")} if "initialPromptTokenCount" in usage_meta else {}
return SimpleNamespace(
prompt_tokens=count("promptTokenCount"), completion_tokens=count("candidatesTokenCount") + reasoning_tokens,
total_tokens=count("totalTokenCount"), prompt_tokens_details=SimpleNamespace(cached_tokens=count("cachedContentTokenCount")),
- completion_tokens_details=SimpleNamespace(reasoning_tokens=reasoning_tokens),
+ completion_tokens_details=SimpleNamespace(reasoning_tokens=reasoning_tokens), **initial,
)
@@ -849,7 +854,9 @@ class GeminiNativeClient:
self.base_url = normalize_gemini_base_url(base_url)
self._default_headers = dict(default_headers or {})
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))
- self._http = http_client or httpx.Client(timeout=timeout or httpx.Timeout(connect=15.0, read=600.0, write=30.0, pool=30.0))
+ # read=1200: Gemini 4 hops can think for minutes; Google asks for a >=20 min read timeout (its
+ # stream limit), and a shorter one cuts long-decode hops off mid-think.
+ self._http = http_client or httpx.Client(timeout=timeout or httpx.Timeout(connect=15.0, read=1200.0, write=30.0, pool=30.0))
def close(self) -> None:
self.is_closed = True
@@ -885,6 +892,10 @@ class GeminiNativeClient:
timeout: Any = None, **_: Any,
) -> Any:
extra = extra_body if isinstance(extra_body, dict) else {}
+ # Long-decode budget (Gemini 4, effort above high) raises the total cap; an explicit larger cap still wins.
+ budget = extra.get("max_output_tokens")
+ if isinstance(budget, int) and budget > int(max_tokens or 0):
+ max_tokens = budget
request = build_gemini_request(
messages=messages or [], tools=tools, tool_choice=tool_choice, temperature=temperature, max_tokens=max_tokens,
top_p=top_p, stop=stop, thinking_config=extra.get("thinking_config") or extra.get("thinkingConfig"),
@@ -895,26 +906,38 @@ class GeminiNativeClient:
url = f"{self.base_url}/models/{model}:"
if stream:
return self._stream_completion(model, f"{url}{self.STREAM_METHOD}?alt=sse", request, timeout)
- response = self._http.post(url + self.GENERATE_METHOD, json=request, headers=self._headers(), timeout=timeout)
+ hops = [self._generate(url + self.GENERATE_METHOD, request, timeout)]
+ while token := continuation_token(hops[-1]): # long decode: same request + token, never the partial output
+ hops.append(self._generate(url + self.GENERATE_METHOD, {**request, "continuationToken": token}, timeout))
+ return translate_gemini_response(merge_hop_responses(hops) if len(hops) > 1 else hops[0], model=model)
+
+ def _generate(self, url: str, request: dict[str, Any], timeout: Any) -> dict[str, Any]:
+ response = self._http.post(url, json=request, headers=self._headers(), timeout=timeout)
if response.status_code != 200:
raise self._http_error(response)
try:
- payload = response.json()
+ return response.json()
except ValueError as exc:
raise GeminiAPIError(
f"Invalid JSON from Gemini native API: {exc}", code="gemini_invalid_json", status_code=response.status_code, response=response,
) from exc
- return translate_gemini_response(payload, model=model)
def _stream_completion(self, model: str, url: str, request: dict[str, Any], timeout: Any) -> Iterator[_GeminiStreamChunk]:
+ tool_call_indices: dict[str, dict[str, Any]] = {} # shared across hops: they form one model turn
+ hop_usage: list[dict[str, Any]] = []
+ body: Optional[dict[str, Any]] = request
try:
- headers = {**self._headers(), "Accept": "text/event-stream"}
- with self._http.stream("POST", url, json=request, headers=headers, timeout=timeout) as response:
- if response.status_code != 200:
- raise self._http_error(response, read_streaming_error_body(response))
- tool_call_indices: dict[str, dict[str, Any]] = {}
- for event in _iter_sse_events(response):
- yield from translate_stream_event(event, model, tool_call_indices)
+ while body is not None:
+ headers = {**self._headers(), "Accept": "text/event-stream"}
+ with self._http.stream("POST", url, json=body, headers=headers, timeout=timeout) as response:
+ if response.status_code != 200:
+ raise self._http_error(response, read_streaming_error_body(response))
+ body = None
+ for event in _iter_sse_events(response):
+ event, token = split_stream_continuation(event, hop_usage)
+ if token:
+ body = {**request, "continuationToken": token}
+ yield from translate_stream_event(event, model, tool_call_indices)
except httpx.HTTPError as exc:
raise GeminiAPIError(f"Gemini streaming request failed: {exc}", code="gemini_stream_error") from exc
diff --git a/agent/reasoning_effort.py b/agent/reasoning_effort.py
index 3c119742aa6..550f77659ee 100644
--- a/agent/reasoning_effort.py
+++ b/agent/reasoning_effort.py
@@ -89,6 +89,10 @@ OLLAMA_CLOUD_OVERRIDES: dict[str, str] = {"xhigh": "max"}
#: Meta Model API (Muse): rejects ``none``.
META_AI_EFFORTS: tuple[str, ...] = ("minimal", "low", "medium", "high", "xhigh")
+#: Gemini 4 (``gemini-4-argon``) ``thinkingLevel``: thinking cannot be disabled, ``minimal`` and
+#: ``thinkingBudget`` 400 (live on Vertex global, 2026-10-13).
+GEMINI4_THINKING_LEVELS: tuple[str, ...] = ("low", "medium", "high")
+
def is_astra_model(model: Optional[str]) -> bool:
"""``gpt-6-astra`` or its Hermes-side ``-900k`` picker alias, with or without a ``vendor/`` prefix.
diff --git a/agent/reasoning_timeouts.py b/agent/reasoning_timeouts.py
index 40798da007b..d9dd8e02425 100644
--- a/agent/reasoning_timeouts.py
+++ b/agent/reasoning_timeouts.py
@@ -33,6 +33,9 @@ _REASONING_STALE_TIMEOUT_FLOORS: dict[int, tuple[str, ...]] = {
# Mythos-class named models (claude-fable-5): 1M ctx + 128K output, a heavier thinking
# phase than the numbered line — otherwise the stale detector trips the circuit breaker.
"claude-fable",
+ # Gemini 4 (gemini-4-argon): thinks longer than 3.x, and a long-decode turn re-prefills the
+ # whole output so far at every hop before the next token arrives.
+ "gemini-4",
),
300: (
"nemotron-3-nano", "nemotron-3.5-lightning", "qwq-32b", "o3-mini", "o4-mini",
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index e27180e5eb4..c84c7161caa 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -9,7 +9,7 @@ from typing import Any
from urllib.parse import urlparse
from agent.reasoning_effort import (
- KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES, OPENAI_COMPAT_WIRE_EFFORTS, clamp_effort,
+ GEMINI4_THINKING_LEVELS, KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES, OPENAI_COMPAT_WIRE_EFFORTS, clamp_effort,
clamp_reasoning_config, kimi_supported_efforts, requested_effort, tokenhub_effort,
)
from agent.message_metadata import MESSAGE_UID
@@ -174,6 +174,11 @@ def _build_gemini_thinking_config(model: str, reasoning_config: dict | None) ->
if not normalized_model.startswith("gemini"):
return None
effort = str(reasoning_config.get("effort", "medium") or "medium").strip().lower()
+ if normalized_model.startswith("gemini-4"):
+ # Gemini 4 always thinks: a disable request gets the floor level with thoughts hidden.
+ disabled = reasoning_config.get("enabled") is False or effort == "none"
+ level = "low" if disabled else clamp_effort(effort, GEMINI4_THINKING_LEVELS)
+ return {"includeThoughts": not disabled, "thinkingLevel": level if level in GEMINI4_THINKING_LEVELS else "medium"}
if reasoning_config.get("enabled") is False or effort == "none":
# ``includeThoughts: False`` only omits thought parts from the returned
# response; the model may still reason internally and bill thought
@@ -605,14 +610,14 @@ class ChatCompletionsTransport(ProviderTransport):
if extra_body:
# Native Gemini speaks Google's REST schema: OpenAI-style extra_body
# keys (tags, reasoning, provider, ...) are unknown fields -> HTTP 400.
- # The native client only reads thinking_config, so drop everything else.
+ # The native client reads only thinking_config and the long-decode budget.
try:
from agent.gemini_native_adapter import is_native_gemini_base_url
_native_gemini = is_native_gemini_base_url(params.get("base_url"))
except Exception:
_native_gemini = False
if _native_gemini:
- extra_body = {k: v for k, v in extra_body.items() if k in ("thinking_config", "thinkingConfig")}
+ extra_body = {k: v for k, v in extra_body.items() if k in ("thinking_config", "thinkingConfig", "max_output_tokens")}
if extra_body:
api_kwargs["extra_body"] = extra_body
return _finish_kwargs(
diff --git a/agent/turn_usage.py b/agent/turn_usage.py
index f86e715021e..e275e7ed4fc 100644
--- a/agent/turn_usage.py
+++ b/agent/turn_usage.py
@@ -107,11 +107,15 @@ def record_response_usage(
prompt_tokens = canonical_usage.prompt_tokens
completion_tokens = canonical_usage.output_tokens
total_tokens = canonical_usage.total_tokens
+ # Gemini long decode sums every hop's re-sent prefix into prompt_tokens (billing, session totals);
+ # the context actually in the window is the first hop's prompt: compaction and the meter read that.
+ _initial_prompt = getattr(response.usage, "initial_prompt_tokens", None)
+ context_prompt_tokens = _initial_prompt if isinstance(_initial_prompt, int) and _initial_prompt > 0 else None
# Canonical token + cache buckets for context engines; legacy keys stay for back-compat.
usage_dict = {
- "prompt_tokens": prompt_tokens,
+ "prompt_tokens": context_prompt_tokens or prompt_tokens,
"completion_tokens": completion_tokens,
- "total_tokens": total_tokens,
+ "total_tokens": (context_prompt_tokens + completion_tokens) if context_prompt_tokens else total_tokens,
"input_tokens": canonical_usage.input_tokens,
"output_tokens": canonical_usage.output_tokens,
"cache_read_tokens": canonical_usage.cache_read_tokens,
@@ -130,21 +134,21 @@ def record_response_usage(
# prompt_tokens with replayed thinking. Display-only; compression math uses real usage.
# The provider just priced this request exactly: if the delta since the previous anchor
# introduced images, the residual is their real per-image cost (learned before re-anchoring).
- calibrate_from_usage(agent, messages, aggregator_usage.prompt_tokens)
+ calibrate_from_usage(agent, messages, context_prompt_tokens or aggregator_usage.prompt_tokens)
_new_anchor = capture_usage_anchor(
- aggregator_usage.prompt_tokens, aggregator_usage.output_tokens, messages
+ context_prompt_tokens or aggregator_usage.prompt_tokens, aggregator_usage.output_tokens, messages
)
if _new_anchor is not None:
set_usage_anchor(agent, _new_anchor, turn_base=api_call_count == 1)
_compression_threshold = int(getattr(compressor, "threshold_tokens", 0) or 0)
if _loop_mod()._should_rearm_compression_budget(
compression_attempts, completed_compaction_pending=_completed_compaction_pending,
- prompt_tokens=prompt_tokens, threshold_tokens=_compression_threshold,
+ prompt_tokens=usage_dict["prompt_tokens"], threshold_tokens=_compression_threshold,
):
logger.info(
"Compression budget rearmed after provider-confirmed "
"recovery: prompt=%s < threshold=%s (attempts were %s/%s)",
- f"{prompt_tokens:,}",
+ f"{usage_dict['prompt_tokens']:,}",
f"{_compression_threshold:,}",
compression_attempts,
max_compression_attempts,
@@ -158,7 +162,7 @@ def record_response_usage(
agent._last_turn_usage = dict(usage_dict)
# The parent's CURRENT prompt size for headroom math (delegate summary budgets): the
# aggregator's own prompt, never the MoA-folded total (advisor prompts are not in this context).
- agent._last_prompt_size_tokens = int(aggregator_usage.prompt_tokens or 0)
+ agent._last_prompt_size_tokens = int(context_prompt_tokens or aggregator_usage.prompt_tokens or 0)
# Persist only provider-confirmed context lengths, not probe tiers.
if getattr(compressor, "_context_probed", False):
diff --git a/agent/usage_pricing.py b/agent/usage_pricing.py
index f6ce5af6315..c439022f0e8 100644
--- a/agent/usage_pricing.py
+++ b/agent/usage_pricing.py
@@ -208,6 +208,10 @@ _SNAPSHOTS: tuple[tuple[str, Optional[str], str, dict], ...] = (
("deepseek-flash", "deepseek-v4-flash", "deepseek-chat", "deepseek-reasoner"): ("0.15", "0.60", "0.003"),
"deepseek-v4-pro": ("0.66", "1.98", "0.022"),
}),
+ # Introductory rates through 2026-11-30; from 2026-12-01 they double ($4 / $20 / $0.20).
+ ("google", "https://ai.google.dev/gemini-api/docs/pricing", "google-pricing-2026-10-13", {
+ "gemini-4-argon": ("2.00", "10.00", "0.10"),
+ }),
("google", "https://ai.google.dev/gemini-api/docs/pricing", "google-pricing-2026-09-02", {
("gemini-3.8-flash", "gemini-3.7-flash"): ("0.75", "3.75", "0.075"),
}),
diff --git a/hermes_cli/models_catalog_static.py b/hermes_cli/models_catalog_static.py
index 78714f63a95..1b6327d7362 100644
--- a/hermes_cli/models_catalog_static.py
+++ b/hermes_cli/models_catalog_static.py
@@ -42,7 +42,8 @@ OPENROUTER_MODELS: list[tuple[str, str]] = [
"openai/gpt-6-astra-pro-fast", "openai/gpt-6-astra-pro-flex",
"openai/gpt-6.1-sol", "openai/gpt-6.1-sol-pro", "openai/gpt-6-sol", "openai/gpt-6-sol-pro",
"openai/gpt-6-luna", "openai/gpt-6-luna-pro",
- "openai/gpt-5.5", "openai/gpt-5.5-pro", "openai/gpt-5.4-mini", "google/gemini-3.1-pro-preview",
+ "openai/gpt-5.5", "openai/gpt-5.5-pro", "openai/gpt-5.4-mini", "google/gemini-4-argon",
+ "google/gemini-3.1-pro-preview",
"google/gemini-3.8-flash", "google/gemini-3.7-flash", "x-ai/grok-4.7", "x-ai/grok-4.6",
"deepseek/deepseek-v4-pro",
"deepseek/deepseek-v4-pro-0813", "deepseek/deepseek-v4.1-flash", "deepseek/deepseek-v4-flash-0731",
@@ -187,7 +188,7 @@ _PROVIDER_MODELS: dict[str, list[str]] = {
"gemini-3.1-pro-preview", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro",
],
"gemini": [
- "gemini-3.8-flash", "gemini-3.7-flash",
+ "gemini-4-argon", "gemini-3.8-flash", "gemini-3.7-flash",
"gemini-3.1-pro-preview", "gemini-3-pro-preview", "gemini-3.6-flash", "gemini-3.1-flash-lite-preview",
],
"zai": [
@@ -296,7 +297,7 @@ _PROVIDER_MODELS: dict[str, list[str]] = {
# only shows the configured model. IDs carry the "google/" publisher prefix Vertex expects
# (see hermes_cli/model_setup_flows.py); validated live against a GCP project (global region).
"vertex": [
- "google/gemini-3.8-flash", "google/gemini-3.7-flash",
+ "google/gemini-4-argon", "google/gemini-3.8-flash", "google/gemini-3.7-flash",
"google/gemini-3.1-pro-preview", "google/gemini-3-pro-preview", "google/gemini-3.6-flash",
"google/gemini-3.5-flash", "google/gemini-3.5-flash-lite", "google/gemini-3-flash-preview",
"google/gemini-3.1-flash-lite-preview", "google/gemini-3.1-flash-lite",
diff --git a/plugins/model-providers/gemini/__init__.py b/plugins/model-providers/gemini/__init__.py
index ad99a7b3f36..aa0c2294372 100644
--- a/plugins/model-providers/gemini/__init__.py
+++ b/plugins/model-providers/gemini/__init__.py
@@ -25,10 +25,16 @@ class GeminiProfile(ProviderProfile):
raw = _build_gemini_thinking_config(context.get("model") or "", context.get("reasoning_config"))
if not raw:
return {}
- if self.name == "gemini" and _is_gemini_openai_compat_base_url(context.get("base_url") or self.base_url):
+ base_url = context.get("base_url") or self.base_url
+ if self.name == "gemini" and _is_gemini_openai_compat_base_url(base_url):
thinking_config = _snake_case_gemini_thinking_config(raw)
return {"extra_body": {"google": {"thinking_config": thinking_config}}} if thinking_config else {}
- return {"thinking_config": raw}
+ from agent.gemini_long_decode import long_decode_max_output_tokens
+ from agent.gemini_native_adapter import is_native_gemini_base_url
+
+ # Long decode exists only on native generateContent (not /openai, not proxies).
+ budget = long_decode_max_output_tokens(context.get("model") or "", context.get("reasoning_config"))
+ return {"thinking_config": raw, **({"max_output_tokens": budget} if budget and is_native_gemini_base_url(base_url) else {})}
gemini = GeminiProfile(
diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.py
index 71300354527..c9a8b1a41f8 100644
--- a/tests/agent/test_gemini_native_adapter.py
+++ b/tests/agent/test_gemini_native_adapter.py
@@ -916,3 +916,64 @@ def test_build_gemini_request_tools_plus_json_output_only_on_gemini3(model, keep
tool_choice="auto", model=model, response_format={"type": "json_object"}, tools_as_json_schema=True,
)["generationConfig"]
assert ("responseMimeType" in generation) is keeps_json
+
+
+def test_long_decode_continues_across_hops_and_reports_first_hop_prompt(monkeypatch):
+ """A CONTINUATION hop resends the SAME request plus the token (never the partial output); the hops
+ join into one turn whose usage is summed for billing, with hop 1's prompt kept as the context size."""
+ from agent.gemini_native_adapter import GeminiNativeClient
+
+ def hop(text, finish, token, prompt, out):
+ cand = {"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": finish}
+ return {"candidates": [{**cand, **({"continuationToken": token} if token else {})}],
+ "usageMetadata": {"promptTokenCount": prompt, "candidatesTokenCount": out, "totalTokenCount": prompt + out}}
+
+ hops = [hop("part one ", "CONTINUATION", "tok-1", 100, 32768), hop("part two", "STOP", None, 32868, 500)]
+ sent = []
+
+ class _Stream:
+ def __init__(self, payload):
+ self.status_code, self._payload = 200, payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def iter_text(self):
+ # A mid-stream checkpoint (token, no finish) precedes the hop's final event.
+ checkpoint = {"candidates": [{"content": {"parts": [{"text": ""}]}, "continuationToken": "ckpt"}]}
+ yield f"data: {json.dumps(checkpoint)}\n\ndata: {json.dumps(self._payload)}\n\n"
+
+ class DummyHTTP:
+ def post(self, url, json=None, headers=None, timeout=None):
+ sent.append(json)
+ return DummyResponse(payload=hops[len(sent) - 1])
+
+ def stream(self, method, url, json=None, headers=None, timeout=None):
+ sent.append(json)
+ return _Stream(hops[len(sent) - 1])
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr("agent.gemini_native_adapter.httpx.Client", lambda *a, **k: DummyHTTP())
+ client = GeminiNativeClient(api_key="AQ.test", base_url="https://generativelanguage.googleapis.com/v1beta")
+ kwargs = {"model": "gemini-4-argon", "messages": [{"role": "user", "content": "prove it"}], "max_tokens": 262_144}
+
+ response = client.chat.completions.create(**kwargs)
+ assert sent[1] == {**sent[0], "continuationToken": "tok-1"}
+ assert sent[0]["generationConfig"]["maxOutputTokens"] == 262_144 # not clamped to the per-request cap
+ assert response.choices[0].message.content == "part one part two"
+ assert response.choices[0].finish_reason == "stop"
+ usage = response.usage
+ assert (usage.prompt_tokens, usage.completion_tokens, usage.initial_prompt_tokens) == (32968, 33268, 100)
+
+ sent.clear()
+ chunks = list(client.chat.completions.create(**kwargs, stream=True))
+ assert sent[1] == {**sent[0], "continuationToken": "tok-1"} # the hop's final token, not the checkpoint
+ finishes = [c for c in chunks if c.choices[0].finish_reason]
+ assert [c.choices[0].finish_reason for c in finishes] == ["stop"] # CONTINUATION is not the end
+ assert "".join(c.choices[0].delta.content or "" for c in chunks) == "part one part two"
+ assert (finishes[0].usage.prompt_tokens, finishes[0].usage.initial_prompt_tokens) == (32968, 100)
diff --git a/tests/agent/test_gemini_thinking_config.py b/tests/agent/test_gemini_thinking_config.py
index bf4594abfdc..91169643b1c 100644
--- a/tests/agent/test_gemini_thinking_config.py
+++ b/tests/agent/test_gemini_thinking_config.py
@@ -51,3 +51,29 @@ def test_snake_case_translation_carries_thinking_budget():
assert translated == {"include_thoughts": False, "thinking_budget": 0}
translated = _snake_case_gemini_thinking_config({"includeThoughts": False})
assert translated == {"include_thoughts": False}
+
+
+ "reasoning,level,shown,budget",
+ [
+ ({"effort": "none"}, "low", False, None), # Gemini 4 cannot stop thinking: floor level, hidden
+ ({"effort": "minimal"}, "low", True, None), # "minimal" 400s on Gemini 4
+ ({"effort": "medium"}, "medium", True, None),
+ ({"effort": "high"}, "high", True, None),
+ ({"effort": "xhigh"}, "high", True, 262_144), # above high buys long-decode budget instead
+ ({"effort": "max"}, "high", True, 1_048_576),
+ ],
+)
+def test_gemini4_maps_effort_to_thinking_level_and_long_decode_budget(reasoning, level, shown, budget):
+ from providers import get_provider_profile
+
+ config = _build_gemini_thinking_config("gemini-4-argon", reasoning)
+ assert config == {"includeThoughts": shown, "thinkingLevel": level} # never thinkingBudget (400 with a level)
+ profile = get_provider_profile("gemini")
+ native = profile.build_extra_body(model="gemini-4-argon", reasoning_config=reasoning,
+ base_url="https://generativelanguage.googleapis.com/v1beta")
+ assert native.get("max_output_tokens") == budget
+ # The OpenAI-compat subpath has no long decode: no budget rides there.
+ 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
diff --git a/website/docs/guides/google-gemini.md b/website/docs/guides/google-gemini.md
index d486aa7b2a1..2eb6be2af90 100644
--- a/website/docs/guides/google-gemini.md
+++ b/website/docs/guides/google-gemini.md
@@ -128,6 +128,12 @@ A base URL on any other host (a proxy) is never rewritten. Express keys are
separate from the OAuth-based
[Vertex AI provider](./google-vertex.md), which needs no API key.
+Models served only in the `global` location (Gemini 4 Argon) are not reachable on
+the bare express host, which routes to `us-central1`. For those, set the base URL
+to the project-scoped form,
+`https://aiplatform.googleapis.com/v1beta1/projects/<project>/locations/global`,
+and Hermes completes it to `…/publishers/google` the same way.
+
:::warning Upgrade note for existing express-key users
Earlier Hermes releases detected the `AQ.` prefix and rerouted such keys to
`aiplatform.googleapis.com` automatically, so the documented setup was "set
@@ -144,6 +150,7 @@ The `hermes model` picker shows Gemini models maintained in Hermes' provider reg
| Model | ID | Notes |
|-------|----|-------|
+| Gemini 4 Argon | `gemini-4-argon` | Flagship reasoning model; shared 1M input+output window, long decode up to 1M output tokens |
| Gemini 3.8 Flash | `gemini-3.8-flash` | Most capable Flash model for long-horizon agentic and coding work |
| Gemini 3.7 Flash | `gemini-3.7-flash` | Recommended default balance of speed, capability, and multimodal understanding |
| Gemini 3.1 Pro Preview | `gemini-3.1-pro-preview` | Most capable reasoning, math, and coding model |
@@ -157,6 +164,33 @@ Model availability changes over time. If a model disappears or is not enabled fo
Use Gemini's native model IDs such as `gemini-3.7-flash`, not OpenRouter-style IDs like `google/gemini-3.7-flash`, when `provider: gemini`.
:::
+### Gemini 4 Argon: Reasoning Effort and Long Decode
+
+Gemini 4 Argon always thinks; Hermes maps the reasoning effort (`/reasoning`,
+`agent.reasoning_effort`) onto its `thinkingLevel`:
+
+| Hermes effort | `thinkingLevel` | Total output budget |
+|---------------|-----------------|---------------------|
+| `none`, `minimal`, `low` | `low` (thoughts hidden for `none`) | Per-request cap |
+| `medium` (Google's default) | `medium` | Per-request cap |
+| `high` | `high` | Per-request cap |
+| `xhigh` | `high` | 262,144 tokens (long decode) |
+| `max`, `ultra` | `high` | 1,048,576 tokens minus the input (long decode) |
+
+Without long decode a single request stops at 65,536 output tokens when streaming
+(32,768 non-streaming), thinking included. With `xhigh` or `max`, Hermes raises
+`maxOutputTokens` and, when a request reaches the per-request cap with budget left
+(`finishReason: CONTINUATION`), resends the same request with Google's
+`continuationToken` until the model finishes. The hops are joined into one reply.
+
+Usage across hops is reported the way Google bills it: every hop re-reads the
+prompt plus the output so far, so the summed input count is far larger than the
+real context. Hermes prices the summed counts but feeds context compaction and the
+context meter the first hop's prompt size, so a long-decode turn does not trigger
+an early compaction. Long decode runs only on the native endpoints (AI Studio and
+Vertex AI express); Google's `/openai` compatibility endpoint, OpenRouter and the
+OAuth [Vertex AI provider](./google-vertex.md) stop at the per-request cap.
+
### Latest Aliases
Google publishes moving aliases for the Pro and Flash Gemini families. `gemini-pro-latest` and `gemini-flash-latest` are useful when you want Google to advance the model automatically without changing your Hermes config. Note that your usage charges may be affected if newer models introduce different rates.
diff --git a/website/static/api/model-catalog.json b/website/static/api/model-catalog.json
index 0eea9e5743f..caf47315b25 100644
--- a/website/static/api/model-catalog.json
+++ b/website/static/api/model-catalog.json
@@ -1,6 +1,6 @@
{
"version": 1,
- "updated_at": "2026-10-12T13:47:23Z",
+ "updated_at": "2026-10-13T18:12:26Z",
"metadata": {
"source": "hermes-agent repo",
"docs": "https://hermes-agent.nousresearch.com/docs/reference/model-catalog"
@@ -116,6 +116,10 @@
"id": "openai/gpt-5.4-mini",
"description": ""
},
+ {
+ "id": "google/gemini-4-argon",
+ "description": ""
+ },
{
"id": "google/gemini-3.1-pro-preview",
"description": ""
@@ -377,6 +381,9 @@
{
"id": "openai/gpt-5.4-mini"
},
+ {
+ "id": "google/gemini-4-argon"
+ },
{
"id": "google/gemini-3.1-pro-preview"
},