fix(gemini): route Vertex AI express keys (AQ.) to aiplatform instead of 403ing on AI Studio

Google issues two Gemini key families: AI Studio keys (AIza...) and Vertex AI
express-mode keys (AQ....). Express keys only authenticate against
aiplatform.googleapis.com; the native adapter hardcoded the Studio host, so an
express key had no working path (403), and an explicit aiplatform base URL was
not even recognised as native Gemini and used the wrong model path.

- normalize_gemini_base_url(base_url, api_key="") routes an AQ. key that would
  land on generativelanguage to
  https://aiplatform.googleapis.com/v1beta1/publishers/google; an explicit proxy
  base is never rewritten. The express base carries the publishers/google
  prefix so every {base}/models/{model}:... builder (chat, tier probe, Gemini
  TTS) needs no path branching; an explicit aiplatform host root / v1beta1 base
  is completed to that form.
- is_native_gemini_base_url accepts the express host but NOT the OAuth Vertex
  provider's .../projects/{p}/locations/{r}/endpoints/openapi base, which is
  OpenAI-compatible and must stay off the native adapter.
- GeminiNativeClient, probe_gemini_tier and both Gemini TTS call sites pass the
  key through.

Cherry-picked from the reporter's earlier PR #96587 and reshaped onto current
main; #114343 and #101918 proposed the same routing.

Fixes #114335

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Co-authored-by: cloim <cloimism@gmail.com>
This commit is contained in:
authored and Teknium committed 2026-09-18 09:28:39 -07:00
1 parent b08fbfa0d7
commit 6293fca019
5 files changed
+100 -10

No files matched your search

+39 -6
View File
@@ -34,6 +34,10 @@ except Exception:
_API_CLIENT = f"hermes-agent/{_HERMES_VERSION}" # client context per Gemini's partner-integration guidance
DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
# Vertex AI express-mode keys (``AQ.…``) only authenticate against aiplatform, which serves the
# same native API under ``{version}/publishers/google/models/…``; the base carries that prefix so
# every ``{base}/models/{model}:…`` builder (chat, tier probe, TTS) needs no path branching.
VERTEX_EXPRESS_BASE_URL = "https://aiplatform.googleapis.com/v1beta1/publishers/google"
# Published max output-token ceiling shared by every current Gemini text model; used
# for max_tokens=None because the native API's low internal default truncates output.
@@ -100,7 +104,20 @@ def gemini_requires_tool_call_ids(model: str) -> bool:
_API_VERSION_SEGMENT = re.compile(r"^v\d+(?:alpha|beta)?\d*$", re.IGNORECASE)
def normalize_gemini_base_url(base_url: Optional[str]) -> str:
def is_vertex_express_key(api_key: str) -> bool:
"""Vertex AI express-mode keys are ``AQ.…``; AI Studio keys are ``AIza…``."""
return str(api_key or "").strip().startswith("AQ.")
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
the native adapter."""
normalized = str(base_url or "").strip().lower()
return "aiplatform.googleapis.com" in normalized and "/projects/" not in normalized
def normalize_gemini_base_url(base_url: Optional[str], api_key: str = "") -> str:
"""Gemini native base URL with the API version segment guaranteed. Google's own client treats the
base as a host root and appends the version itself, so users configure ``GEMINI_BASE_URL`` (or a
proxy root like ``http://localhost:4000/gemini``) that way; our request builders expect
@@ -108,11 +125,25 @@ def normalize_gemini_base_url(base_url: Optional[str]) -> str:
slashes and an ``/openai`` suffix are stripped; an existing version segment (``v1``, ``v1beta``,
``v1alpha``, ...) is kept; empty input returns ``DEFAULT_GEMINI_BASE_URL``. Only the LAST path
segment is inspected, so ``.../v1beta/extra`` still gets ``/v1beta`` appended; this does not
decide routing (see ``is_native_gemini_base_url``)."""
decide routing (see ``is_native_gemini_base_url``).
A Vertex express base (``aiplatform.googleapis.com``, ``…/v1beta1`` or the full
``…/v1beta1/publishers/google``) is completed to the ``publishers/google`` form. With ``api_key``
given, an express key (``AQ.``) that would land on the Studio host is routed to
``VERTEX_EXPRESS_BASE_URL`` instead — it can only ever 403 there — while an explicit proxy or
Vertex base is left alone."""
trimmed = str(base_url or "").strip().rstrip("/")
trimmed = re.sub(r"/openai\Z", "", trimmed, flags=re.IGNORECASE).rstrip("/")
if not trimmed:
return DEFAULT_GEMINI_BASE_URL
trimmed = DEFAULT_GEMINI_BASE_URL
if is_vertex_express_key(api_key) and "generativelanguage.googleapis.com" in trimmed.lower():
return VERTEX_EXPRESS_BASE_URL
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]):
trimmed = f"{trimmed}/v1beta1"
return f"{trimmed}/publishers/google"
if _API_VERSION_SEGMENT.match(trimmed.rsplit("/", 1)[-1]):
return trimmed
return f"{trimmed}/v1beta"
@@ -121,7 +152,9 @@ def normalize_gemini_base_url(base_url: Optional[str]) -> str:
def is_native_gemini_base_url(base_url: str) -> bool:
"""True when the endpoint speaks Gemini's native REST API (not ``/openai``)."""
normalized = str(base_url or "").strip().rstrip("/").lower()
return "generativelanguage.googleapis.com" in normalized and not normalized.endswith("/openai")
if normalized.endswith("/openai"):
return False
return "generativelanguage.googleapis.com" in normalized or is_vertex_express_base_url(normalized)
def gemini_accepts_parameters_json_schema(base_url: str) -> bool:
@@ -138,7 +171,7 @@ def probe_gemini_tier(
key = (api_key or "").strip()
if not key:
return "unknown"
base = normalize_gemini_base_url(base_url)
base = normalize_gemini_base_url(base_url, key)
payload = {"contents": [{"role": "user", "parts": [{"text": "hi"}]}], "generationConfig": {"maxOutputTokens": 1}}
headers = {"Content-Type": "application/json", "X-Goog-Api-Client": _API_CLIENT}
try:
@@ -722,7 +755,7 @@ class GeminiNativeClient:
if not (api_key or "").strip():
raise RuntimeError(_MISSING_KEY_ERROR)
self.api_key, self.is_closed = api_key, False
self.base_url = normalize_gemini_base_url(base_url)
self.base_url = normalize_gemini_base_url(base_url, api_key)
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))
+43
View File
@@ -787,3 +787,46 @@ def test_iter_sse_events_stops_at_done_and_ignores_trailing_frames():
resp = _FakeStreamResponse(['data: {"candidates": [1]}\ndata: [DONE]'])
assert list(_iter_sse_events(resp)) == [{"candidates": [1]}]
@pytest.mark.parametrize(
"api_key, configured, expected_prefix",
[
# Express key + default Studio host: the only place it can never work → aiplatform express surface.
("AQ.express-key", None, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models/"),
# Control: Studio key keeps the Studio host.
("AIza-test", None, "https://generativelanguage.googleapis.com/v1beta/models/"),
# An explicit aiplatform base (host root or versioned) is completed to the publishers form.
("AQ.express-key", "https://aiplatform.googleapis.com", "https://aiplatform.googleapis.com/v1beta1/publishers/google/models/"),
("AIza-test", "https://aiplatform.googleapis.com/v1beta1", "https://aiplatform.googleapis.com/v1beta1/publishers/google/models/"),
# An explicit proxy is never overridden by the key shape.
("AQ.express-key", "http://localhost:4000/gemini", "http://localhost:4000/gemini/v1beta/models/"),
],
)
def test_native_client_routes_vertex_express_keys_to_aiplatform(api_key, configured, expected_prefix):
"""Vertex express keys (``AQ.``) 403 on generativelanguage; the request must hit
``aiplatform.googleapis.com/v1beta1/publishers/google/models/…`` unless the user pointed elsewhere."""
from agent.gemini_native_adapter import GeminiNativeClient
seen = []
class _HTTP:
def post(self, url, **_):
seen.append(url)
return SimpleNamespace(status_code=200, json=lambda: {"candidates": [
{"content": {"role": "model", "parts": [{"text": "ok"}]}, "finishReason": "STOP"}]})
client = GeminiNativeClient(api_key=api_key, base_url=configured, http_client=_HTTP())
client.chat.completions.create(model="gemini-3.7-flash", messages=[{"role": "user", "content": "hi"}])
assert seen == [f"{expected_prefix}gemini-3.7-flash:generateContent"]
def test_native_gemini_detection_covers_express_but_not_vertex_oauth_openapi():
"""The express base is native Gemini; the OAuth Vertex provider's OpenAI-compatible
``…/endpoints/openapi`` base must NOT be captured by the native adapter."""
from agent.gemini_native_adapter import is_native_gemini_base_url
assert is_native_gemini_base_url("https://aiplatform.googleapis.com/v1beta1/publishers/google")
assert not is_native_gemini_base_url(
"https://aiplatform.googleapis.com/v1beta1/projects/p/locations/global/endpoints/openapi"
)
+1 -1
View File
@@ -246,7 +246,7 @@ class GeminiStreamer(StreamingTTSProvider):
voice = str(self.section.get("voice", DEFAULT_GEMINI_TTS_VOICE)).strip() or DEFAULT_GEMINI_TTS_VOICE
from agent.gemini_native_adapter import normalize_gemini_base_url
base_url = normalize_gemini_base_url(
self.section.get("base_url") or get_env_value("GEMINI_BASE_URL") or DEFAULT_GEMINI_TTS_BASE_URL
self.section.get("base_url") or get_env_value("GEMINI_BASE_URL") or DEFAULT_GEMINI_TTS_BASE_URL, api_key,
)
payload = {
"contents": [{"parts": [{"text": text}]}],
+1 -1
View File
@@ -570,7 +570,7 @@ def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]
from hermes_cli.config import get_env_value
from agent.gemini_native_adapter import normalize_gemini_base_url
base_url = normalize_gemini_base_url(
gemini_config.get("base_url") or get_env_value("GEMINI_BASE_URL") or DEFAULT_GEMINI_TTS_BASE_URL
gemini_config.get("base_url") or get_env_value("GEMINI_BASE_URL") or DEFAULT_GEMINI_TTS_BASE_URL, api_key,
)
persona_prompt = _read_gemini_persona_prompt(gemini_config)
tts_script = text
+16 -2
View File
@@ -109,8 +109,22 @@ appends `/v1beta` for you, so `GEMINI_BASE_URL=https://generativelanguage.google
works the same as spelling out the `/v1beta` suffix. The same normalization
applies to the Gemini TTS base URL (`tts.gemini.base_url`). Chat requests only
take the native Gemini path when the base URL points at
`generativelanguage.googleapis.com`; a proxy on another host is treated as an
OpenAI-compatible endpoint, so configure it with its `/openai`-style URL.
`generativelanguage.googleapis.com` or the Vertex AI express host below; a proxy on
another host is treated as an OpenAI-compatible endpoint, so configure it with its
`/openai`-style URL.
### Vertex AI Express Mode Keys
Google issues two Gemini key families. AI Studio keys start with `AIza…`; **Vertex AI
express-mode** keys start with `AQ.…` and only authenticate against
`aiplatform.googleapis.com` (they get 403 on the AI Studio host). Hermes detects the
`AQ.` prefix and routes those keys to
`https://aiplatform.googleapis.com/v1beta1/publishers/google` automatically — set
`GEMINI_API_KEY` to the express key and leave `GEMINI_BASE_URL` unset. If you set
`GEMINI_BASE_URL` to `https://aiplatform.googleapis.com` (with or without `/v1beta1`)
Hermes completes it to the `publishers/google` form; a base URL on any other host (a
proxy) is never rewritten. Express keys are separate from the OAuth-based
[Vertex AI provider](/guides/google-vertex), which needs no API key.
## Available Models