Skip to content

The agent that grows with you

fix(gemini): surface Standard-key guidance on 400 API_KEY_INVALID

xxxigmd27a43f1b6fc
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 82d4a45828a..77d33ec4663 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -50,8 +50,9 @@ _STANDARD_KEY_GUIDANCE = (
"'Standard' Google Cloud keys for the Gemini API on June 19, 2026, and all Standard keys stop working in "
"September 2026. Open https://aistudio.google.com/api-keys, check the key's type and status, and create a "
"replacement Gemini API key (or, as a temporary bridge, restrict the Standard key to "
- "generativelanguage.googleapis.com). Then update GEMINI_API_KEY / GOOGLE_API_KEY in ~/.hermes/.env and "
- "restart your session. Details: https://ai.google.dev/gemini-api/docs/api-key"
+ "generativelanguage.googleapis.com). Then update GEMINI_API_KEY / GOOGLE_API_KEY in ~/.hermes/.env, "
+ "delete any leftover Windows/system copy of those variables, and restart. A stale shell key can hide "
+ "the .env value. Details: https://ai.google.dev/gemini-api/docs/api-key"
)
# Stands in for a model turn that never arrived (stream failure / interrupt / quota
# fallback) when a human user text turn directly follows a tool-result turn, keeping
@@ -169,11 +170,27 @@ def is_free_tier_quota_error(error_message: str) -> bool:
return bool(error_message) and "free_tier" in error_message.lower()
-def is_standard_key_auth_error(status: int, error_message: str, reason: str = "") -> bool:
- """True when a Gemini 401 means Google rejected the key TYPE (legacy "Standard" Cloud key → misleading
- "expected OAuth 2 access token" / ErrorInfo ``ACCESS_TOKEN_TYPE_UNSUPPORTED``). Narrow so ``API_KEY_INVALID``
- keeps its message."""
- return status == 401 and (reason == "ACCESS_TOKEN_TYPE_UNSUPPORTED" or "expected oauth 2 access token" in (error_message or "").lower())
+def is_standard_key_auth_error(
+ status: int, error_message: str, reason: str = "", *, api_key: str = "",
+) -> bool:
+ """True when Google rejected a legacy "Standard" (AIza) Cloud key.
+
+ Original shape (June 2026): 401 + ``ACCESS_TOKEN_TYPE_UNSUPPORTED`` / "expected OAuth 2
+ access token". After the September 2026 cutoff the same leftover AIza key often comes
+ back as 400 ``API_KEY_INVALID`` ("API key not valid") — attach migration guidance on
+ that 400 only when the presented key is still AIza-shaped, so a mistyped Auth (``AQ.``)
+ key keeps the raw invalid-key message.
+ """
+ msg = (error_message or "").lower()
+ if status == 401 and (reason == "ACCESS_TOKEN_TYPE_UNSUPPORTED" or "expected oauth 2 access token" in msg):
+ return True
+ if (
+ status == 400
+ and (api_key or "").startswith("AIza")
+ and (reason == "API_KEY_INVALID" or "api key not valid" in msg)
+ ):
+ return True
+ return False
class GeminiAPIError(Exception):
@@ -665,7 +682,9 @@ def _error_object(body_text: str) -> Dict[str, Any]:
return err_obj if isinstance(err_obj, dict) else {}
-def gemini_http_error(response: httpx.Response, *, body_text: Optional[str] = None) -> GeminiAPIError:
+def gemini_http_error(
+ response: httpx.Response, *, body_text: Optional[str] = None, api_key: str = "",
+) -> GeminiAPIError:
status = response.status_code
body_text = (_response_text(response) if body_text is None else body_text) or ""
err_obj = _error_object(body_text)
@@ -677,10 +696,11 @@ def gemini_http_error(response: httpx.Response, *, body_text: Optional[str] = No
else f"Gemini returned HTTP {status}: {body_text[:500]}"
)
# Users who bypassed the setup wizard (raw GOOGLE_API_KEY in .env) still need to learn the free
- # tier cannot sustain an agent session; a legacy "Standard" key gets the real fix (Google's raw 401 asks for OAuth).
+ # tier cannot sustain an agent session; a legacy "Standard" key gets the real fix (Google's raw
+ # 401 asks for OAuth; after Sept 2026 the same AIza key is often a 400 API_KEY_INVALID).
if status == 429 and is_free_tier_quota_error(err_message or body_text):
message += _FREE_TIER_GUIDANCE
- if is_standard_key_auth_error(status, err_message or body_text, reason):
+ if is_standard_key_auth_error(status, err_message or body_text, reason, api_key=api_key):
message += _STANDARD_KEY_GUIDANCE
return GeminiAPIError(
message, code=_HTTP_ERROR_CODES.get(status, f"gemini_http_{status}"), status_code=status, response=response,
@@ -745,7 +765,7 @@ class GeminiNativeClient:
return self._stream_completion(model, url + "streamGenerateContent?alt=sse", request, timeout)
response = self._http.post(url + "generateContent", json=request, headers=self._headers(), timeout=timeout)
if response.status_code != 200:
- raise gemini_http_error(response)
+ raise gemini_http_error(response, api_key=self.api_key)
try:
payload = response.json()
except ValueError as exc:
@@ -759,7 +779,9 @@ class GeminiNativeClient:
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 gemini_http_error(response, body_text=read_streaming_error_body(response))
+ raise gemini_http_error(
+ response, body_text=read_streaming_error_body(response), api_key=self.api_key,
+ )
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)