Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Give Google reasoning controls one owner (#1211)

Ali Khokharfe40548a30ea
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 381482d1..97e4e0d4 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -590,8 +590,14 @@ or untyped provider backchannel remains.
[providers/google_openai/](src/free_claude_code/providers/google_openai/) owns the
Google-specific protocol behavior shared by AI Studio and Vertex AI: literal
-Google `extra_body` construction, thought-signature replay, and thinking-budget
-encoding. Neither concrete provider imports from the other. AI Studio owns its
+Google `extra_body` construction, exclusive reasoning serialization, and
+thought-signature replay. Each concrete profile selects one Google reasoning
+encoder, and that encoder is the sole writer of `reasoning_effort` or
+`extra_body.google.thinking_config` for its request. Caller-provided Google
+thinking configuration is preserved only for provider-default reasoning;
+combining it with FCC reasoning controls fails during deterministic preflight.
+Thought-signature replay is a separate component and never mutates reasoning
+controls. Neither concrete provider imports from the other. AI Studio owns its
API-key endpoint; [providers/vertex/](src/free_claude_code/providers/vertex/)
owns project/location endpoint composition, renewable Application Default
Credentials, and translation of Google's native publisher-model catalog. The
@@ -671,7 +677,7 @@ profile explicitly chooses native `reasoning_content`, native `reasoning`,
for the next generation does not silently erase prior assistant state required
for a valid continuation.
-The boundary has four hard rules:
+The boundary has five hard rules:
1. Never inspect an upstream model name or version to select reasoning behavior.
2. Prefer a provider's named effort vocabulary; use FCC's documented numeric
@@ -682,6 +688,9 @@ The boundary has four hard rules:
4. Provider-default intent emits no compute-control field. Explicit off requests
an upstream disable where supported and always suppresses reasoning output at
the FCC protocol boundary.
+5. Each provider profile has exactly one reasoning encoder. That encoder alone
+ writes the provider's computation and reasoning-output request fields;
+ unrelated request postprocessors never add, repair, or remove those fields.
Shared provider responsibilities include upstream rate limiting, model listing,
SDK/HTTP failure classification, safe diagnostic construction, HTTP resource
diff --git a/pyproject.toml b/pyproject.toml
index 154d9e5e..5f4cad5f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "4.11.1"
+version = "4.11.2"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/src/free_claude_code/providers/gemini/client.py b/src/free_claude_code/providers/gemini/client.py
index 46a55889..1dee808d 100644
--- a/src/free_claude_code/providers/gemini/client.py
+++ b/src/free_claude_code/providers/gemini/client.py
@@ -1,12 +1,14 @@
"""Google AI Studio Gemini provider (OpenAI-compatible chat completions)."""
from free_claude_code.core.anthropic import ReasoningReplayMode
-from free_claude_code.core.reasoning import ReasoningEffort
from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
-from free_claude_code.providers.google_openai import GoogleOpenAIProvider
+from free_claude_code.providers.google_openai import (
+ GeminiReasoningEncoder,
+ GoogleOpenAIProvider,
+ validate_google_extra_body,
+)
from free_claude_code.providers.openai_chat import (
- NamedEffortReasoning,
OpenAIChatProfile,
OpenAIChatRequestPolicy,
)
@@ -14,20 +16,12 @@ from free_claude_code.providers.openai_chat import (
_REQUEST_POLICY = OpenAIChatRequestPolicy(
provider_name="GEMINI",
reasoning_replay=ReasoningReplayMode.REASONING_CONTENT,
+ include_extra_body=True,
+ extra_body_validator=validate_google_extra_body,
)
_PROFILE = OpenAIChatProfile(
_REQUEST_POLICY,
- NamedEffortReasoning(
- (
- (ReasoningEffort.MINIMAL, "minimal"),
- (ReasoningEffort.LOW, "low"),
- (ReasoningEffort.MEDIUM, "medium"),
- (ReasoningEffort.HIGH, "high"),
- (ReasoningEffort.XHIGH, "high"),
- (ReasoningEffort.MAX, "high"),
- ),
- disabled_value="none",
- ),
+ GeminiReasoningEncoder(),
)
diff --git a/src/free_claude_code/providers/google_openai/__init__.py b/src/free_claude_code/providers/google_openai/__init__.py
index 01d21937..25f329ae 100644
--- a/src/free_claude_code/providers/google_openai/__init__.py
+++ b/src/free_claude_code/providers/google_openai/__init__.py
@@ -1,10 +1,17 @@
"""Shared Google OpenAI-compatible provider family."""
-from .provider import GoogleOpenAIProvider, GoogleThinkingBudgetReasoning
-from .quirks import GOOGLE_SKIP_THOUGHT_SIGNATURE_VALIDATOR
+from .provider import GoogleOpenAIProvider
+from .reasoning import (
+ GeminiReasoningEncoder,
+ VertexReasoningEncoder,
+ validate_google_extra_body,
+)
+from .thought_signatures import GOOGLE_SKIP_THOUGHT_SIGNATURE_VALIDATOR
__all__ = [
"GOOGLE_SKIP_THOUGHT_SIGNATURE_VALIDATOR",
+ "GeminiReasoningEncoder",
"GoogleOpenAIProvider",
- "GoogleThinkingBudgetReasoning",
+ "VertexReasoningEncoder",
+ "validate_google_extra_body",
]
diff --git a/src/free_claude_code/providers/google_openai/provider.py b/src/free_claude_code/providers/google_openai/provider.py
index 554a7ae6..09a71fe8 100644
--- a/src/free_claude_code/providers/google_openai/provider.py
+++ b/src/free_claude_code/providers/google_openai/provider.py
@@ -2,13 +2,11 @@
from collections.abc import Mapping
from copy import deepcopy
-from dataclasses import dataclass
from typing import Any
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.reasoning import (
DEFAULT_REASONING_POLICY,
- ReasoningControl,
ReasoningPolicy,
)
from free_claude_code.providers.admission import ProviderAdmissionController
@@ -20,29 +18,11 @@ from free_claude_code.providers.openai_chat import (
build_openai_chat_request_body,
)
-from .quirks import apply_google_request_quirks, google_thinking_config
+from .thought_signatures import apply_google_thought_signatures
_MAX_TOOL_CALL_EXTRA_CONTENT_CACHE = 4096
-@dataclass(frozen=True, slots=True)
-class GoogleThinkingBudgetReasoning:
- """Encode FCC reasoning intent in Google's model-neutral thinking budget."""
-
- def encode(self, body: dict[str, Any], policy: ReasoningPolicy) -> None:
- if policy.control is ReasoningControl.OFF:
- thinking = google_thinking_config(body)
- thinking["thinking_budget"] = 0
- thinking["include_thoughts"] = False
- return
- budget = policy.numeric_budget_tokens
- if budget is None:
- return
- thinking = google_thinking_config(body)
- thinking.setdefault("thinking_budget", budget)
- thinking.setdefault("include_thoughts", True)
-
-
class GoogleOpenAIProvider(OpenAIChatProvider):
"""Shared thought-signature and request behavior for Google Gemini APIs."""
@@ -88,12 +68,10 @@ class GoogleOpenAIProvider(OpenAIChatProvider):
reasoning=reasoning,
policy=self._profile.request_policy,
postprocessors=(
- lambda body, request_data, policy: apply_google_request_quirks(
+ lambda body, _request_data, _policy: apply_google_thought_signatures(
body,
- request_data,
- policy,
tool_call_extra_content_by_id=(self._tool_call_extra_content_by_id),
),
- self._profile.apply_reasoning,
+ *self._profile.request_postprocessors,
),
)
diff --git a/src/free_claude_code/providers/google_openai/reasoning.py b/src/free_claude_code/providers/google_openai/reasoning.py
new file mode 100644
index 00000000..bfeff191
--- /dev/null
+++ b/src/free_claude_code/providers/google_openai/reasoning.py
@@ -0,0 +1,146 @@
+"""Exclusive reasoning encoders for Google OpenAI-compatible endpoints."""
+
+from dataclasses import dataclass
+from typing import Any, cast
+
+from free_claude_code.application.errors import InvalidRequestError
+from free_claude_code.core.reasoning import (
+ DEFAULT_REASONING_POLICY,
+ ReasoningControl,
+ ReasoningEffort,
+ ReasoningPolicy,
+)
+from free_claude_code.providers.openai_chat import (
+ validate_extra_body_does_not_override_reasoning_fields,
+)
+
+_GEMINI_EFFORTS = {
+ ReasoningEffort.MINIMAL: "minimal",
+ ReasoningEffort.LOW: "low",
+ ReasoningEffort.MEDIUM: "medium",
+ ReasoningEffort.HIGH: "high",
+ ReasoningEffort.XHIGH: "high",
+ ReasoningEffort.MAX: "high",
+}
+_THINKING_CONFIG_CONFLICT = (
+ "Google extra_body.google.thinking_config cannot be combined with FCC "
+ "reasoning controls. Use either thinking/output_config or the provider-native "
+ "thinking_config."
+)
+
+
+@dataclass(frozen=True, slots=True)
+class GeminiReasoningEncoder:
+ """Choose one Gemini API reasoning channel for each resolved policy."""
+
+ def encode(self, body: dict[str, Any], policy: ReasoningPolicy) -> None:
+ if _preserve_caller_thinking_config(body, policy):
+ return
+
+ if policy.control is ReasoningControl.OFF:
+ body["reasoning_effort"] = "none"
+ return
+
+ if policy.budget_tokens is not None:
+ thinking = _thinking_config(body)
+ thinking["thinking_budget"] = policy.budget_tokens
+ thinking["include_thoughts"] = True
+ return
+
+ if effort := _GEMINI_EFFORTS.get(policy.effort):
+ body["reasoning_effort"] = effort
+ return
+
+ if policy.control is ReasoningControl.ON:
+ _thinking_config(body)["include_thoughts"] = True
+
+
+@dataclass(frozen=True, slots=True)
+class VertexReasoningEncoder:
+ """Encode Vertex reasoning through one Google thinking-config object."""
+
+ def encode(self, body: dict[str, Any], policy: ReasoningPolicy) -> None:
+ if _preserve_caller_thinking_config(body, policy):
+ return
+
+ if policy.control is ReasoningControl.OFF:
+ thinking = _thinking_config(body)
+ thinking["thinking_budget"] = 0
+ thinking["include_thoughts"] = False
+ return
+
+ budget = policy.numeric_budget_tokens
+ if budget is not None:
+ thinking = _thinking_config(body)
+ thinking["thinking_budget"] = budget
+ thinking["include_thoughts"] = True
+ return
+
+ if policy.control is ReasoningControl.ON:
+ _thinking_config(body)["include_thoughts"] = True
+
+
+def validate_google_extra_body(extra: dict[str, Any]) -> None:
+ """Validate caller extensions before a Google encoder takes ownership."""
+
+ validate_extra_body_does_not_override_reasoning_fields(extra)
+ literal_extra = _optional_object(extra, "extra_body", "extra_body.extra_body")
+ if literal_extra is None:
+ return
+ google = _optional_object(literal_extra, "google", "extra_body.google")
+ if google is None:
+ return
+ _optional_object(
+ google,
+ "thinking_config",
+ "extra_body.google.thinking_config",
+ )
+
+
+def _preserve_caller_thinking_config(
+ body: dict[str, Any], policy: ReasoningPolicy
+) -> bool:
+ if _existing_thinking_config(body) is None:
+ return False
+ if policy != DEFAULT_REASONING_POLICY:
+ raise InvalidRequestError(_THINKING_CONFIG_CONFLICT)
+ return True
+
+
+def _existing_thinking_config(body: dict[str, Any]) -> dict[str, Any] | None:
+ sdk_extra = body.get("extra_body")
+ if not isinstance(sdk_extra, dict):
+ return None
+ literal_extra = sdk_extra.get("extra_body")
+ if not isinstance(literal_extra, dict):
+ return None
+ google = literal_extra.get("google")
+ if not isinstance(google, dict):
+ return None
+ thinking = google.get("thinking_config")
+ return cast(dict[str, Any], thinking) if isinstance(thinking, dict) else None
+
+
+def _thinking_config(body: dict[str, Any]) -> dict[str, Any]:
+ sdk_extra = _object(body, "extra_body")
+ literal_extra = _object(sdk_extra, "extra_body")
+ google = _object(literal_extra, "google")
+ return _object(google, "thinking_config")
+
+
+def _object(container: dict[str, Any], key: str) -> dict[str, Any]:
+ value = container.setdefault(key, {})
+ if not isinstance(value, dict):
+ raise TypeError(f"{key} must be an object.")
+ return cast(dict[str, Any], value)
+
+
+def _optional_object(
+ container: dict[str, Any], key: str, path: str
+) -> dict[str, Any] | None:
+ if key not in container:
+ return None
+ value = container[key]
+ if not isinstance(value, dict):
+ raise ValueError(f"{path} must be an object.")
+ return cast(dict[str, Any], value)
diff --git a/src/free_claude_code/providers/google_openai/quirks.py b/src/free_claude_code/providers/google_openai/thought_signatures.py
similarity index 67%
rename from src/free_claude_code/providers/google_openai/quirks.py
rename to src/free_claude_code/providers/google_openai/thought_signatures.py
index fb241296..9eba08ad 100644
--- a/src/free_claude_code/providers/google_openai/quirks.py
+++ b/src/free_claude_code/providers/google_openai/thought_signatures.py
@@ -1,60 +1,23 @@
-"""Google Gemini extensions shared by Google OpenAI-compatible endpoints."""
+"""Google thought-signature replay for OpenAI-compatible tool calls."""
from copy import deepcopy
-from typing import Any, cast
-
-from free_claude_code.core.anthropic.models import MessagesRequest
-from free_claude_code.core.reasoning import ReasoningPolicy
+from typing import Any
GOOGLE_SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator"
-def apply_google_request_quirks(
+def apply_google_thought_signatures(
body: dict[str, Any],
- request_data: MessagesRequest,
- reasoning: ReasoningPolicy,
*,
tool_call_extra_content_by_id: dict[str, dict[str, Any]] | None = None,
) -> None:
- """Apply Google-specific request extensions after common OpenAI conversion."""
- extra_body: dict[str, Any] = {}
- request_extra = request_data.extra_body
- if isinstance(request_extra, dict):
- extra_body.update(deepcopy(request_extra))
-
- if reasoning.requests_reasoning:
- _thinking_config(extra_body).setdefault("include_thoughts", True)
-
- if extra_body:
- body["extra_body"] = extra_body
-
- _apply_google_tool_call_signatures(
- body,
- tool_call_extra_content_by_id=tool_call_extra_content_by_id,
- )
-
-
-def google_thinking_config(body: dict[str, Any]) -> dict[str, Any]:
- """Return Google's literal ``extra_body.google.thinking_config`` object."""
- extra_body = _ensure_dict(body, "extra_body")
- return _thinking_config(extra_body)
+ """Restore Google tool-call signatures required for conversation replay."""
-
-def _thinking_config(extra_body: dict[str, Any]) -> dict[str, Any]:
- # OpenAI's SDK merges its ``extra_body`` argument into the request JSON.
- # Google expects its extension fields under a literal JSON ``extra_body`` key.
- literal_extra_body = _ensure_dict(extra_body, "extra_body")
- google_section = _ensure_dict(literal_extra_body, "google")
- return _ensure_dict(google_section, "thinking_config")
-
-
-def _ensure_dict(container: dict[str, Any], key: str) -> dict[str, Any]:
- value = container.get(key)
- if isinstance(value, dict):
- return cast(dict[str, Any], value)
- nested: dict[str, Any] = {}
- container[key] = nested
- return nested
+ messages = body.get("messages")
+ if not isinstance(messages, list):
+ return
+ _apply_cached_tool_call_signatures(messages, tool_call_extra_content_by_id or {})
+ _apply_missing_current_turn_signatures(messages)
def _thought_signature_from_extra_content(extra_content: Any) -> str | None:
@@ -152,15 +115,3 @@ def _apply_missing_current_turn_signatures(messages: list[Any]) -> None:
_set_tool_call_thought_signature(
first_tool_call, GOOGLE_SKIP_THOUGHT_SIGNATURE_VALIDATOR
)
-
-
-def _apply_google_tool_call_signatures(
- body: dict[str, Any],
- *,
- tool_call_extra_content_by_id: dict[str, dict[str, Any]] | None,
-) -> None:
- messages = body.get("messages")
- if not isinstance(messages, list):
- return
- _apply_cached_tool_call_signatures(messages, tool_call_extra_content_by_id or {})
- _apply_missing_current_turn_signatures(messages)
diff --git a/src/free_claude_code/providers/openai_chat/__init__.py b/src/free_claude_code/providers/openai_chat/__init__.py
index 48be7343..b4ccf3a1 100644
--- a/src/free_claude_code/providers/openai_chat/__init__.py
+++ b/src/free_claude_code/providers/openai_chat/__init__.py
@@ -4,7 +4,10 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from .base_url import openai_v1_base_url
-from .extra_body import validate_extra_body_does_not_override_canonical_fields
+from .extra_body import (
+ validate_extra_body_does_not_override_canonical_fields,
+ validate_extra_body_does_not_override_reasoning_fields,
+)
from .profiles import OPENAI_CHAT_PROFILES, OpenAIChatProfile
from .provider import OpenAIAsyncCredentialProvider, OpenAIChatProvider
from .reasoning import (
@@ -51,4 +54,5 @@ __all__ = [
"openai_v1_base_url",
"usage_int",
"validate_extra_body_does_not_override_canonical_fields",
+ "validate_extra_body_does_not_override_reasoning_fields",
]
diff --git a/src/free_claude_code/providers/vertex/client.py b/src/free_claude_code/providers/vertex/client.py
index 14d34b55..79d5ed96 100644
--- a/src/free_claude_code/providers/vertex/client.py
+++ b/src/free_claude_code/providers/vertex/client.py
@@ -10,7 +10,8 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.google_openai import (
GoogleOpenAIProvider,
- GoogleThinkingBudgetReasoning,
+ VertexReasoningEncoder,
+ validate_google_extra_body,
)
from free_claude_code.providers.http import maybe_await_aclose
from free_claude_code.providers.model_listing import ModelListResponseError
@@ -26,8 +27,10 @@ from .models import extract_vertex_model_page
_REQUEST_POLICY = OpenAIChatRequestPolicy(
provider_name="VERTEX",
reasoning_replay=ReasoningReplayMode.REASONING_CONTENT,
+ include_extra_body=True,
+ extra_body_validator=validate_google_extra_body,
)
-_PROFILE = OpenAIChatProfile(_REQUEST_POLICY, GoogleThinkingBudgetReasoning())
+_PROFILE = OpenAIChatProfile(_REQUEST_POLICY, VertexReasoningEncoder())
class VertexProvider(GoogleOpenAIProvider):
diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.py
index ce904329..f192c5c4 100644
--- a/tests/contracts/test_import_boundaries.py
+++ b/tests/contracts/test_import_boundaries.py
@@ -197,6 +197,35 @@ def test_openai_chat_collaborators_have_explicit_ownership_boundaries() -> None:
assert _provider_backchannel_offenders(provider_root) == []
+def test_google_reasoning_wire_fields_have_one_owner() -> None:
+ owner = _PACKAGE_ROOT / "providers" / "google_openai" / "reasoning.py"
+ roots = [
+ _PACKAGE_ROOT / "providers" / "gemini",
+ _PACKAGE_ROOT / "providers" / "google_openai",
+ _PACKAGE_ROOT / "providers" / "vertex",
+ ]
+ owned_fields = {
+ "include_thoughts",
+ "reasoning_effort",
+ "thinking_budget",
+ "thinking_config",
+ }
+ offenders: list[str] = []
+
+ for root in roots:
+ for path in root.rglob("*.py"):
+ if path == owner:
+ continue
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ offenders.extend(
+ f"{path.relative_to(_REPO_ROOT).as_posix()}:{node.lineno}: {node.value}"
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Constant) and node.value in owned_fields
+ )
+
+ assert sorted(offenders) == []
+
+
def test_provider_backchannel_detector_reports_untyped_private_access(
tmp_path: Path,
) -> None:
diff --git a/tests/providers/test_gemini.py b/tests/providers/test_gemini.py
index 37414601..2cf64b90 100644
--- a/tests/providers/test_gemini.py
+++ b/tests/providers/test_gemini.py
@@ -4,7 +4,9 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.config.provider_catalog import GEMINI_DEFAULT_BASE
+from free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicy
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.gemini import GeminiProvider
from free_claude_code.providers.google_openai import (
@@ -26,6 +28,17 @@ def _simulate_openai_sdk_wire_json(body: dict) -> dict:
return wire
+def _google_thinking_config(wire: dict) -> dict | None:
+ literal_extra_body = wire.get("extra_body")
+ if not isinstance(literal_extra_body, dict):
+ return None
+ google = literal_extra_body.get("google")
+ if not isinstance(google, dict):
+ return None
+ thinking_config = google.get("thinking_config")
+ return thinking_config if isinstance(thinking_config, dict) else None
+
+
@pytest.fixture
def gemini_config():
return ProviderConfig(
@@ -118,6 +131,70 @@ def test_build_request_body_reasoning_off_sets_reasoning_none():
assert "assistant_reasoning_content" not in roles
+ ("reasoning", "expected_effort", "expected_thinking_config"),
+ [
+ (ReasoningPolicy.provider_default(), None, None),
+ (ReasoningPolicy.off(), "none", None),
+ (ReasoningPolicy.on(), None, {"include_thoughts": True}),
+ (
+ ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
+ "high",
+ None,
+ ),
+ (
+ ReasoningPolicy.on(budget_tokens=777),
+ None,
+ {"thinking_budget": 777, "include_thoughts": True},
+ ),
+ (
+ ReasoningPolicy.on(
+ effort=ReasoningEffort.HIGH,
+ budget_tokens=777,
+ ),
+ None,
+ {"thinking_budget": 777, "include_thoughts": True},
+ ),
+ ],
+)
+def test_gemini_reasoning_uses_exactly_one_wire_channel(
+ gemini_provider: GeminiProvider,
+ reasoning: ReasoningPolicy,
+ expected_effort: str | None,
+ expected_thinking_config: dict | None,
+) -> None:
+ body = gemini_provider._build_request_body(
+ make_request(thinking=None),
+ reasoning=reasoning,
+ )
+ wire = _simulate_openai_sdk_wire_json(body)
+
+ assert wire.get("reasoning_effort") == expected_effort
+ assert _google_thinking_config(wire) == expected_thinking_config
+ assert not (
+ "reasoning_effort" in wire and _google_thinking_config(wire) is not None
+ )
+
+
+def test_gemini_adaptive_thinking_with_effort_does_not_emit_custom_config(
+ gemini_provider: GeminiProvider,
+) -> None:
+ request = make_messages_request(
+ "models/gemini-3.5-flash",
+ thinking={"type": "adaptive"},
+ output_config={"effort": "high"},
+ )
+
+ body = gemini_provider._build_request_body(
+ request,
+ reasoning=reasoning_for(request),
+ )
+ wire = _simulate_openai_sdk_wire_json(body)
+
+ assert wire["reasoning_effort"] == "high"
+ assert _google_thinking_config(wire) is None
+
+
def test_build_request_body_preserves_caller_extra_body(gemini_provider):
req = make_request(extra_body={"metadata": {"user": "u1"}})
@@ -135,15 +212,19 @@ def test_build_request_body_preserves_caller_extra_body(gemini_provider):
def test_build_request_body_merges_caller_nested_google(gemini_provider):
req = make_request(
+ thinking=None,
extra_body={
"metadata": {"user": "u1"},
"extra_body": {
"google": {
- "thinking_config": {"budget_tokens": 128},
+ "thinking_config": {
+ "thinking_level": "low",
+ "include_thoughts": False,
+ },
"cached_content": "cachedContents/example",
}
},
- }
+ },
)
body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
@@ -159,8 +240,42 @@ def test_build_request_body_merges_caller_nested_google(gemini_provider):
assert google.get("cached_content") == "cachedContents/example"
thinking_config = google.get("thinking_config")
assert isinstance(thinking_config, dict)
- assert thinking_config.get("budget_tokens") == 128
- assert thinking_config.get("include_thoughts") is True
+ assert thinking_config == {
+ "thinking_level": "low",
+ "include_thoughts": False,
+ }
+
+
+def test_gemini_rejects_caller_thinking_config_with_fcc_reasoning_control(
+ gemini_provider: GeminiProvider,
+) -> None:
+ request = make_request(
+ thinking=None,
+ extra_body={
+ "extra_body": {"google": {"thinking_config": {"thinking_level": "low"}}}
+ },
+ )
+
+ with pytest.raises(InvalidRequestError, match="thinking_config"):
+ gemini_provider._build_request_body(
+ request,
+ reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
+ )
+
+
+def test_gemini_rejects_malformed_google_extension_container(
+ gemini_provider: GeminiProvider,
+) -> None:
+ request = make_request(
+ thinking=None,
+ extra_body={"extra_body": {"google": {"thinking_config": "low"}}},
+ )
+
+ with pytest.raises(InvalidRequestError, match="thinking_config must be an object"):
+ gemini_provider._build_request_body(
+ request,
+ reasoning=ReasoningPolicy.provider_default(),
+ )
def test_build_request_body_preserves_tool_call_extra_content(gemini_provider):
diff --git a/tests/providers/test_vertex.py b/tests/providers/test_vertex.py
index 6905c54c..c0971404 100644
--- a/tests/providers/test_vertex.py
+++ b/tests/providers/test_vertex.py
@@ -9,9 +9,13 @@ from google.auth.credentials import Credentials
from google.auth.exceptions import DefaultCredentialsError, TransportError
from google.auth.transport.requests import Request
-from free_claude_code.application.errors import ApplicationUnavailableError
+from free_claude_code.application.errors import (
+ ApplicationUnavailableError,
+ InvalidRequestError,
+)
from free_claude_code.config.provider_catalog import VERTEX_AI_API_ROOT
from free_claude_code.core.failures import ExecutionFailure, FailureKind
+from free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicy
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.model_listing import ModelListResponseError
from free_claude_code.providers.vertex import VertexProvider
@@ -90,6 +94,25 @@ def _provider(
)
+def _simulate_openai_sdk_wire_json(body: dict) -> dict:
+ wire = {key: value for key, value in body.items() if key != "extra_body"}
+ sdk_extra = body.get("extra_body")
+ if isinstance(sdk_extra, dict):
+ wire.update(sdk_extra)
+ return wire
+
+
+def _google_thinking_config(wire: dict) -> dict | None:
+ literal_extra_body = wire.get("extra_body")
+ if not isinstance(literal_extra_body, dict):
+ return None
+ google = literal_extra_body.get("google")
+ if not isinstance(google, dict):
+ return None
+ thinking_config = google.get("thinking_config")
+ return thinking_config if isinstance(thinking_config, dict) else None
+
+
@pytest.mark.parametrize(
("location", "service_endpoint"),
[
@@ -245,6 +268,91 @@ def test_vertex_request_maps_reasoning_off_to_zero_budget() -> None:
}
+ ("reasoning", "expected_thinking_config"),
+ [
+ (ReasoningPolicy.provider_default(), None),
+ (ReasoningPolicy.off(), {"thinking_budget": 0, "include_thoughts": False}),
+ (ReasoningPolicy.on(), {"include_thoughts": True}),
+ (
+ ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
+ {"thinking_budget": 2048, "include_thoughts": True},
+ ),
+ (
+ ReasoningPolicy.on(budget_tokens=777),
+ {"thinking_budget": 777, "include_thoughts": True},
+ ),
+ (
+ ReasoningPolicy.on(
+ effort=ReasoningEffort.HIGH,
+ budget_tokens=777,
+ ),
+ {"thinking_budget": 777, "include_thoughts": True},
+ ),
+ ],
+)
+def test_vertex_reasoning_has_one_google_wire_owner(
+ reasoning: ReasoningPolicy,
+ expected_thinking_config: dict | None,
+) -> None:
+ provider = _provider()
+
+ body = provider._build_request_body(
+ make_messages_request("google/gemini", thinking=None),
+ reasoning=reasoning,
+ )
+ wire = _simulate_openai_sdk_wire_json(body)
+
+ assert "reasoning_effort" not in wire
+ assert _google_thinking_config(wire) == expected_thinking_config
+
+
+def test_vertex_preserves_caller_thinking_config_only_for_provider_default() -> None:
+ provider = _provider()
+ request = make_messages_request(
+ "google/gemini",
+ thinking=None,
+ extra_body={
+ "extra_body": {
+ "google": {
+ "thinking_config": {
+ "thinking_level": "low",
+ "include_thoughts": False,
+ }
+ }
+ }
+ },
+ )
+
+ body = provider._build_request_body(
+ request,
+ reasoning=ReasoningPolicy.provider_default(),
+ )
+ wire = _simulate_openai_sdk_wire_json(body)
+
+ assert _google_thinking_config(wire) == {
+ "thinking_level": "low",
+ "include_thoughts": False,
+ }
+
+
+def test_vertex_rejects_caller_thinking_config_with_fcc_reasoning_control() -> None:
+ provider = _provider()
+ request = make_messages_request(
+ "google/gemini",
+ thinking=None,
+ extra_body={
+ "extra_body": {"google": {"thinking_config": {"thinking_level": "low"}}}
+ },
+ )
+
+ with pytest.raises(InvalidRequestError, match="thinking_config"):
+ provider._build_request_body(
+ request,
+ reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
+ )
+
+
def test_vertex_model_page_translates_google_resource_names_generically() -> None:
model_ids, page_token = extract_vertex_model_page(
{
diff --git a/uv.lock b/uv.lock
index e4a5ef17..681da6bf 100644
--- a/uv.lock
+++ b/uv.lock
@@ -620,7 +620,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "4.11.1"
+version = "4.11.2"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },