Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(brain): Gemini 3.7 Flash briefs use thinking_level LOW, not budget 0

Haraldecc32607691c
diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.py
index 83d1b05cab..9f5033ffc8 100644
--- a/jarvis/agentic_ide/prompt_composer.py
+++ b/jarvis/agentic_ide/prompt_composer.py
@@ -661,7 +661,8 @@ async def _llm_compose(
stream=True,
# Maintainer 2026-08-18: writing this brief is "what was said, plus
# the neighbouring @files". Medium effort was the 10-30 s wait. Gemini
- # maps "none" to thinking_budget=0; providers without a knob ignore it.
+ # maps "none" to thinking_level=LOW on Gemini 3 (3.7-flash has no
+ # off switch and 400s on budget=0); providers without a knob ignore it.
reasoning_effort="none",
)
chunks: list[str] = []
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index 46eaa22ca5..b7ec7ba096 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -69,6 +69,21 @@ _MIN_CACHE_TOKENS = 4096
# after an SDK or remote-model change. Keys include the budget so rejecting
# the router's zero budget never disables a positive budget in another tier.
_REJECTED_THINKING_BUDGETS: set[tuple[str, int]] = set()
+# Models that rejected ``thinking_level`` (Gemini 2.5 and earlier: the
+# parameter is Gemini-3-only). Next call on the same model skips the level
+# and uses ``thinking_budget`` instead — one doomed 400 per process, not
+# per turn (AP-21: capability memory, never a model-name pin).
+_REJECTED_THINKING_LEVELS: set[str] = set()
+
+# Gemini 3 discrete levels. ``none`` maps to LOW, not MINIMAL: gemini-3.7-flash
+# 400s on MINIMAL (docs 2026-08-17) and its default is MEDIUM — which is the
+# 10-30 s wait the composer is trying to kill. LOW is the lowest 3.7 accepts.
+_EFFORT_TO_THINKING_LEVEL: dict[str, str] = {
+ "none": "LOW",
+ "low": "LOW",
+ "medium": "MEDIUM",
+ "high": "HIGH",
+}
def _is_stale_context_cache_error(exc: Exception) -> bool:
@@ -98,6 +113,60 @@ def _is_stale_context_cache_error(exc: Exception) -> bool:
return False
+def _thinking_config_for(
+ *,
+ model: str,
+ ctor_budget: int | None,
+ effort: str | None,
+ rejected_budgets: set[int],
+) -> tuple[Any | None, str]:
+ """The ThinkingConfig for this call, and whether it is a ``level`` or ``budget``.
+
+ Gemini 3 wants ``thinking_level``; Gemini 2.5 wants ``thinking_budget``.
+ Sending both 400s on Gemini 3. Sending ``thinking_budget=0`` on
+ gemini-3.7-flash either 400s or is ignored, after which the model
+ thinks at its default MEDIUM — the 10-30 s composer wait. ``none``
+ and an explicit constructor budget of 0 therefore prefer LOW. A model
+ that already rejected the level (remembered in ``_REJECTED_THINKING_LEVELS``)
+ falls through to the budget. Never raises: an old SDK without the
+ field degrades to the budget path.
+ """
+ from google.genai import types as _genai_types
+
+ def _budget_cfg(value: int) -> Any | None:
+ if (
+ value in rejected_budgets
+ or (model, value) in _REJECTED_THINKING_BUDGETS
+ ):
+ return None
+ try:
+ return _genai_types.ThinkingConfig(thinking_budget=value)
+ except (TypeError, AttributeError, ValueError):
+ return None
+
+ # A positive or dynamic constructor budget is an explicit cap — keep
+ # the 2.5-style field. Zero means "off", which Gemini 3 does not have.
+ if ctor_budget is not None and ctor_budget != 0:
+ cfg = _budget_cfg(ctor_budget)
+ return (cfg, "budget") if cfg is not None else (None, "")
+
+ wants_off = ctor_budget == 0 or effort == "none"
+ level = _EFFORT_TO_THINKING_LEVEL.get(effort or "")
+ if level is None and wants_off:
+ level = "LOW"
+
+ if level and model not in _REJECTED_THINKING_LEVELS:
+ try:
+ return _genai_types.ThinkingConfig(thinking_level=level), "level"
+ except (TypeError, AttributeError, ValueError):
+ pass
+
+ if wants_off:
+ cfg = _budget_cfg(0)
+ return (cfg, "budget") if cfg is not None else (None, "")
+ return None, ""
+
+
def _is_thinking_config_rejected_error(exc: Exception) -> bool:
"""True when the API rejected the ``thinking_config`` BY NAME — definitive.
@@ -848,38 +917,23 @@ class GeminiBrain:
except Exception: # noqa: BLE001 — never break the brain call over an SDK shape change
log.debug("could not disable Gemini automatic_function_calling", exc_info=True)
- # Latency-Sprint-1: thinking budget. Only when explicitly set —
- # otherwise we leave the choice to the SDK default (previous
- # behavior). ``ThinkingConfig`` is available from google-genai >= 0.7;
- # older SDK versions don't have the field and raise AttributeError. In
- # that case we ignore the value instead of killing the whole brain
- # call (best-effort optimization).
- effective_thinking_budget = self._thinking_budget
- if (
- effective_thinking_budget is None
- and getattr(req, "reasoning_effort", None) == "none"
- ):
- # The caller asked for minimal internal reasoning (small
- # structured-output calls: Computer-Use actions/judges). A
- # thinking-by-default model otherwise spends the whole
- # ``max_output_tokens`` budget on thoughts and the visible reply
- # arrives truncated mid-JSON — live forensic 2026-07-16: every CU
- # step failed "unterminated JSON" with thoughts=304 of
- # max_tokens=320. An explicit constructor budget always wins.
- effective_thinking_budget = 0
- if (
- effective_thinking_budget is not None
- and effective_thinking_budget not in self._rejected_thinking_budgets
- and (self._model, effective_thinking_budget)
- not in _REJECTED_THINKING_BUDGETS
- ):
- try:
- from google.genai import types as _genai_types
- config_dict["thinking_config"] = _genai_types.ThinkingConfig(
- thinking_budget=effective_thinking_budget,
- )
- except (ImportError, AttributeError):
- pass
+ # Latency-Sprint-1: thinking. Gemini 3 wants ``thinking_level``;
+ # Gemini 2.5 wants ``thinking_budget``. ``none`` / budget 0 prefer
+ # LOW — gemini-3.7-flash's default is MEDIUM, and budget=0 is not a
+ # Gemini-3 off switch (it 400s or is ignored, then the model thinks
+ # at MEDIUM for 10-30 s). See ``_thinking_config_for``.
+ thinking_kind = ""
+ try:
+ thinking_cfg, thinking_kind = _thinking_config_for(
+ model=self._model,
+ ctor_budget=self._thinking_budget,
+ effort=getattr(req, "reasoning_effort", None),
+ rejected_budgets=self._rejected_thinking_budgets,
+ )
+ except Exception: # noqa: BLE001 — old SDK / unexpected shape
+ thinking_cfg, thinking_kind = None, ""
+ if thinking_cfg is not None:
+ config_dict["thinking_config"] = thinking_cfg
# ╔══════════════════════════════════════════════════════════════╗
# ║ BUG-019 ROOT CAUSE — STALE GEMINI CONTEXT-CACHE REFERENCE ║
@@ -1140,7 +1194,37 @@ class GeminiBrain:
"thinking_budget",
None,
)
+ cache_on_wire = bool(cache_name and "cached_content" in config_dict)
+ if (
+ thinking_kind == "level"
+ and not (not thinking_config_blamed and cache_on_wire)
+ ):
+ # Gemini 2.5 400s on thinking_level. Fall through to
+ # the budget path instead of dropping the knob —
+ # dropping it on 3.7-flash is how MEDIUM thinking
+ # comes back and the composer waits 10-30 s. Skip
+ # this hop when a cache reference is also on the
+ # wire: a generic 400 then has two suspects and
+ # the two-variable retry must not blame either.
+ _REJECTED_THINKING_LEVELS.add(self._model)
+ from google.genai import types as _retry_types
+ fallback = None
+ if (
+ 0 not in self._rejected_thinking_budgets
+ and (self._model, 0) not in _REJECTED_THINKING_BUDGETS
+ ):
+ try:
+ fallback = _retry_types.ThinkingConfig(
+ thinking_budget=0
+ )
+ except (TypeError, AttributeError, ValueError):
+ fallback = None
+ if fallback is not None:
+ config_dict["thinking_config"] = fallback
+ thinking_kind = "budget"
+ continue
config_dict.pop("thinking_config", None)
+ thinking_kind = ""
# A generic 400 while a context-cache reference is on the
# wire could ALSO be a differently-worded dead-cache
# rejection this branch would otherwise consume — and the
diff --git a/tests/unit/brain/test_gemini_reasoning_effort.py b/tests/unit/brain/test_gemini_reasoning_effort.py
index c7b340f796..035c9c6a8c 100644
--- a/tests/unit/brain/test_gemini_reasoning_effort.py
+++ b/tests/unit/brain/test_gemini_reasoning_effort.py
@@ -10,13 +10,14 @@ every CU step failed "unterminated JSON" and the mission aborted.
Contract pinned here:
* ``reasoning_effort="none"`` on the request → ``thinking_config`` with
- ``thinking_budget=0`` goes on the wire (thinking disabled for this call).
-* An explicit constructor ``thinking_budget`` always wins over the hint.
+ ``thinking_level=LOW`` (Gemini 3). gemini-3.7-flash has no off switch,
+ 400s on MINIMAL, and its default is MEDIUM — budget=0 is not the knob.
+* A model that rejects ``thinking_level`` (Gemini 2.5) is recovered by a
+ retry with ``thinking_budget=0``, then without the field if that 400s
+ too — capability probe, not a model-name pin (AP-21).
+* An explicit constructor ``thinking_budget`` other than 0 always wins
+ over the hint.
* No hint, no constructor budget → no ``thinking_config`` (SDK default).
-* A model that REJECTS budget=0 (thinking-mandatory Pro class answers 400
- "Budget 0 is invalid. This model only works in thinking mode.") is
- recovered by ONE retry without the field — capability probe, not a
- model-name pin (AP-21).
Uses the same fake-client shape as ``test_gemini_stale_cache_bug019.py``;
``google.genai`` must be importable for ``ThinkingConfig`` to be attached,
@@ -33,6 +34,7 @@ import pytest
from jarvis.core.protocols import BrainMessage, BrainRequest
from jarvis.plugins.brain.gemini import (
_REJECTED_THINKING_BUDGETS,
+ _REJECTED_THINKING_LEVELS,
GeminiBrain,
)
@@ -43,8 +45,10 @@ pytest.importorskip("google.genai")
def _clear_process_capability_memory() -> Iterator[None]:
"""Keep process-wide production capability memory isolated per test."""
_REJECTED_THINKING_BUDGETS.clear()
+ _REJECTED_THINKING_LEVELS.clear()
yield
_REJECTED_THINKING_BUDGETS.clear()
+ _REJECTED_THINKING_LEVELS.clear()
class _FakeGeminiClient:
@@ -110,6 +114,14 @@ async def _drain(stream: AsyncIterator[Any]) -> list[Any]:
return out
+def _level_name(tc: object | None) -> str:
+ """``ThinkingLevel.LOW`` and the string ``"LOW"`` both count as LOW."""
+ raw = getattr(tc, "thinking_level", None) if tc is not None else None
+ if raw is None:
+ return ""
+ return str(getattr(raw, "value", raw) or "").upper().rsplit(".", 1)[-1]
+
+
def _request(reasoning_effort: str | None) -> BrainRequest:
return BrainRequest(
messages=(BrainMessage(role="user", content="ping"),),
@@ -132,7 +144,66 @@ async def test_reasoning_effort_none_disables_thinking() -> None:
"reasoning_effort='none' must attach a thinking_config — without it "
"a thinking-by-default model eats the 320-token output budget"
)
- assert getattr(tc, "thinking_budget", None) == 0
+ # Gemini 3.7 Flash: LOW is the lowest accepted level. Budget=0 is not
+ # an off switch there, and sending both fields 400s.
+ assert _level_name(tc) == "LOW"
+ assert getattr(tc, "thinking_budget", None) is None
+
+
+async def test_constructor_budget_zero_uses_thinking_level_low() -> None:
+ """The router cap is thinking_budget=0. On Gemini 3 that is not an off
+ switch — LOW is the closest the model accepts."""
+ provider = GeminiBrain(model="gemini-3.7-flash", thinking_budget=0)
+ fake = _FakeGeminiClient()
+ provider._client = fake # type: ignore[assignment]
+
+ await _drain(provider.complete(_request(None)))
+
+ tc = fake.calls[0].get("thinking_config")
+ assert _level_name(tc) == "LOW"
+ assert getattr(tc, "thinking_budget", None) is None
+
+
+async def test_thinking_level_rejection_falls_back_to_budget_zero() -> None:
+ """Gemini 2.5 400s on thinking_level and accepts thinking_budget=0."""
+
+ class _LevelThenBudget(_FakeGeminiClient):
+ async def generate_content_stream( # type: ignore[override]
+ self, *, model: str, contents: list[Any], config: dict[str, Any]
+ ) -> AsyncIterator[Any]:
+ self.calls.append(dict(config))
+ tc = config.get("thinking_config")
+ if tc is not None and getattr(tc, "thinking_level", None):
+ raise RuntimeError(
+ "400 INVALID_ARGUMENT. thinking_level is not supported "
+ "for this model."
+ )
+
+ async def _stream() -> AsyncIterator[Any]:
+ yield SimpleNamespace(
+ text='{"action": "done"}',
+ candidates=[],
+ usage_metadata=None,
+ )
+
+ return _stream()
+
+ provider = GeminiBrain(model="gemini-2.5-flash")
+ fake = _LevelThenBudget()
+ provider._client = fake # type: ignore[assignment]
+
+ deltas = await _drain(provider.complete(_request("none")))
+
+ assert len(fake.calls) == 2
+ assert _level_name(fake.calls[0].get("thinking_config")) == "LOW"
+ assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
+ assert any(d.content for d in deltas)
+
+ await _drain(provider.complete(_request("none")))
+ assert len(fake.calls) == 3
+ assert getattr(fake.calls[2].get("thinking_config"), "thinking_budget", None) == 0
@pytest.mark.asyncio
@@ -169,9 +240,10 @@ async def test_thinking_mandatory_model_recovers_without_the_field() -> None:
deltas = await _drain(provider.complete(_request("none")))
- assert len(fake.calls) == 2
- assert fake.calls[0].get("thinking_config") is not None
- assert "thinking_config" not in fake.calls[1]
+ assert len(fake.calls) == 3
+ assert _level_name(fake.calls[0].get("thinking_config")) == "LOW"
+ assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
+ assert "thinking_config" not in fake.calls[2]
assert any(d.content for d in deltas), "recovered stream must yield text"
@@ -196,12 +268,12 @@ async def test_generic_invalid_argument_recovers_without_the_field() -> None:
deltas = await _drain(provider.complete(_request("none")))
- assert len(fake.calls) == 2, (
- "the generic INVALID_ARGUMENT 400 must trigger exactly one retry "
- "without thinking_config"
+ assert len(fake.calls) == 3, (
+ "level rejected → budget=0 → drop the field; three attempts, then text"
)
assert fake.calls[0].get("thinking_config") is not None
- assert "thinking_config" not in fake.calls[1]
+ assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
+ assert "thinking_config" not in fake.calls[2]
assert any(d.content for d in deltas), "recovered stream must yield text"
@@ -219,15 +291,16 @@ async def test_parameterless_400_recovers_and_is_remembered() -> None:
deltas = await _drain(provider.complete(_request("none")))
- assert len(fake.calls) == 2
+ assert len(fake.calls) == 3
assert fake.calls[0].get("thinking_config") is not None
- assert "thinking_config" not in fake.calls[1]
+ assert getattr(fake.calls[1].get("thinking_config"), "thinking_budget", None) == 0
+ assert "thinking_config" not in fake.calls[2]
assert any(d.content for d in deltas), "recovered stream must yield text"
- # Second turn: the blame is proven — no thinking_config, no extra 400.
+ # Second turn: both knobs are proven rejected — no thinking_config.
await _drain(provider.complete(_request("none")))
- assert len(fake.calls) == 3
- assert "thinking_config" not in fake.calls[2]
+ assert len(fake.calls) == 4
+ assert "thinking_config" not in fake.calls[3]
@pytest.mark.asyncio
@@ -243,7 +316,7 @@ async def test_parameterless_400_is_remembered_across_instances() -> None:
first._client = first_fake # type: ignore[assignment]
await _drain(first.complete(_request("none")))
- assert len(first_fake.calls) == 2
+ assert len(first_fake.calls) == 3
second = GeminiBrain(model="gemini-short-lived-curator")
second_fake = _FakeGeminiClient(reject_thinking_generic=True)
@@ -267,14 +340,18 @@ async def test_unrelated_400_still_propagates_and_forgets_nothing() -> None:
with pytest.raises(RuntimeError, match="invalid argument"):
await _drain(provider.complete(_request("none")))
- # One original attempt + one blame-probe retry, then the error surfaced.
- assert len(fake.calls) == 2
+ # level → budget → drop, then the error surfaced. Budget blame is not
+ # proven because the retry without the field also 400'd.
+ assert len(fake.calls) == 3
fake.reject_everything_generic = False
await _drain(provider.complete(_request("none")))
- assert fake.calls[2].get("thinking_config") is not None, (
- "an unproven blame must not permanently disable thinking_config"
+ # The level was proven rejected (the hop happened). The budget was
+ # not: the no-config retry 400'd too, so the next turn still sends it.
+ assert fake.calls[3].get("thinking_config") is not None, (
+ "an unproven budget blame must not permanently disable thinking_config"
)
+ assert getattr(fake.calls[3].get("thinking_config"), "thinking_budget", None) == 0
@pytest.mark.asyncio