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.

feat(google): route every Gemini client through the Vertex-aware builder

rubenluetke10-beep38dd3dd4a24e
diff --git a/jarvis/brain/ack_brain/providers/gemini.py b/jarvis/brain/ack_brain/providers/gemini.py
index 47fe76a3f0..f56c1d9f97 100644
--- a/jarvis/brain/ack_brain/providers/gemini.py
+++ b/jarvis/brain/ack_brain/providers/gemini.py
@@ -43,8 +43,9 @@ class GeminiFlashAck:
f"No Gemini API key in keyring/env "
f"({self._config.api_key_secret} / GEMINI_API_KEY)."
)
- from google import genai
- self._client = genai.Client(api_key=api_key)
+ # Routed builder: AI Studio or Vertex express, decided per key.
+ from jarvis.core.google_genai import build_genai_client
+ self._client = build_genai_client(api_key)
return self._client
async def run(
diff --git a/jarvis/dictation/polish_client.py b/jarvis/dictation/polish_client.py
index 1e1158b511..903e59f694 100644
--- a/jarvis/dictation/polish_client.py
+++ b/jarvis/dictation/polish_client.py
@@ -865,7 +865,8 @@ class GeminiPolishClient:
def _ensure_client(self, timeout_s: float) -> Any:
if self._client is None:
- from google import genai
+ # Routed builder: AI Studio or Vertex express, decided per key.
+ from jarvis.core.google_genai import build_genai_client
# google-genai forces ``timeout=None`` on its own httpx client, so
# an explicit http_options timeout is the ONLY thing below the
@@ -882,8 +883,8 @@ class GeminiPolishClient:
# to accept; the caller's ``wait_for`` is what actually bounds the
# wait, and it is unchanged. Giving up at 1.5 s and letting the
# socket close on its own is strictly better than not asking at all.
- self._client = genai.Client(
- api_key=self._api_key,
+ self._client = build_genai_client(
+ self._api_key,
http_options={
"timeout": int(max(timeout_s, _GEMINI_MIN_DEADLINE_S) * 1000)
},
diff --git a/jarvis/harness/native_computer_use.py b/jarvis/harness/native_computer_use.py
index 33632edfc8..dcd17d5809 100644
--- a/jarvis/harness/native_computer_use.py
+++ b/jarvis/harness/native_computer_use.py
@@ -238,15 +238,16 @@ class _RealGeminiCUClient:
"""
def __init__(self, *, api_key: str | None = None) -> None:
- from google import genai # noqa: PLC0415
-
if api_key is None:
from jarvis.core.config import get_secret # noqa: PLC0415
api_key = get_secret("GEMINI_API_KEY", env_fallback="GEMINI_API_KEY")
if not api_key:
raise RuntimeError("no Gemini API key for native computer_use")
- self._client = genai.Client(api_key=api_key)
+ # Routed builder: AI Studio or Vertex express, decided per key.
+ from jarvis.core.google_genai import build_genai_client # noqa: PLC0415
+
+ self._client = build_genai_client(api_key)
def generate(self, *, model: str, screenshot: bytes, goal: str, history: list[str]) -> Any:
from google.genai import types # noqa: PLC0415
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index d2e43bc8ae..a6b6aa1eed 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -467,17 +467,46 @@ def _openai_compat_base_url(resolved_base_url: str | None) -> str:
def _create_native_client(endpoint: Any) -> Any:
- """Create the preferred google-genai client at the import boundary."""
- from google import genai
+ """Create the preferred google-genai client at the import boundary.
- client_kwargs: dict[str, Any] = {"api_key": endpoint.credential}
+ Routing: an explicitly resolved ``base_url`` (team proxy / override)
+ speaks the AI Studio wire format, so it pins the AI Studio route; a bare
+ key is routed by ``jarvis.core.google_genai`` (AI Studio vs Vertex AI
+ express mode, decided once per process).
+ """
+ from jarvis.core.google_genai import build_genai_client
+
+ http_options: Any = None
+ route: Any = None
if endpoint.base_url:
from google.genai import types as genai_types
- client_kwargs["http_options"] = genai_types.HttpOptions(
- base_url=endpoint.base_url,
- )
- return genai.Client(**client_kwargs)
+ http_options = genai_types.HttpOptions(base_url=endpoint.base_url)
+ route = "aistudio"
+ return build_genai_client(
+ endpoint.credential, http_options=http_options, route=route
+ )
+
+
+def _reject_compat_fallback_for_vertex(endpoint: Any, cause: BaseException) -> None:
+ """Fail loudly when the OpenAI-compat fallback cannot serve this key.
+
+ The compatibility transport only speaks AI Studio's endpoint. A key that
+ routes through Vertex AI express mode would hit it with a foreign
+ credential and die on every call with a bare auth error — an honest
+ RuntimeError naming the real conflict beats that silent dead end (§3).
+ """
+ if endpoint.base_url:
+ return
+ from jarvis.core.google_genai import resolve_google_key_route
+
+ if resolve_google_key_route(endpoint.credential) == "vertex":
+ raise RuntimeError(
+ "This Google API key routes through Vertex AI express mode, "
+ "which requires the google-genai SDK; the OpenAI-compatible "
+ "fallback only reaches AI Studio. Install google-genai (pip "
+ "install google-genai) or switch to a Google AI Studio key."
+ ) from cause
def _create_openai_compat_client(endpoint: Any) -> Any:
@@ -603,6 +632,7 @@ class GeminiBrain:
# documented HTTPS compatibility API. Log only the exception
# class: dependency messages can contain local paths, and the
# credential must never enter logs.
+ _reject_compat_fallback_for_vertex(ep, exc)
log.info(
"Gemini native SDK unavailable (%s); using the "
"OpenAI-compatible transport",
@@ -1103,6 +1133,7 @@ class GeminiBrain:
ep = cfg.resolve_provider_endpoint("gemini")
if not ep.credential:
raise
+ _reject_compat_fallback_for_vertex(ep, exc)
log.info(
"Gemini native stream dependency unavailable (%s); "
"using the OpenAI-compatible transport",
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.py
index 71c1fd4b50..33d35df9ad 100644
--- a/jarvis/plugins/realtime/gemini_live.py
+++ b/jarvis/plugins/realtime/gemini_live.py
@@ -558,10 +558,14 @@ class GeminiLiveProvider:
if not self._api_key:
raise RuntimeError("Gemini Live API key is not configured")
- from google import genai # lazy (AP-26)
- from google.genai import types
+ from google.genai import types # lazy (AP-26)
+
+ # Routed builder: AI Studio or Vertex express, decided per key. The
+ # async twin keeps a first-ever AQ. key's routing probe off the event
+ # loop; every later session open hits the process-wide cache.
+ from jarvis.core.google_genai import build_genai_client_async
- client = genai.Client(api_key=self._api_key)
+ client = await build_genai_client_async(self._api_key)
voice = str(getattr(cfg, "voice", "") or "").strip()
speech_config: dict[str, Any] = {}
if voice:
diff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.py
index 3bed6d6a6a..708fe4c8cb 100644
--- a/jarvis/plugins/stt/gemini_api.py
+++ b/jarvis/plugins/stt/gemini_api.py
@@ -274,7 +274,10 @@ class GeminiSTT:
"key is shared with the Gemini brain and TTS."
)
try:
- from google import genai
+ # Availability check only — the client itself is built below by the
+ # routed builder. A plain import (not find_spec) so a broken
+ # dependency chain also lands in the clear RuntimeError.
+ from google import genai # noqa: F401
except ImportError as exc:
raise RuntimeError(
"Gemini STT needs the 'google-genai' package (installed with the "
@@ -284,7 +287,12 @@ class GeminiSTT:
# ``Any`` keeps that fact from needing a types import the plugin must
# not make (the SDK is absent on a base install).
http_options: Any = self._http_options()
- self._client = genai.Client(api_key=key, http_options=http_options)
+ # Routed builder: AI Studio or Vertex express, decided per key. Lazy
+ # import, like the config import above (plugin stays jarvis.*-free at
+ # import time).
+ from jarvis.core.google_genai import build_genai_client
+
+ self._client = build_genai_client(key, http_options=http_options)
return self._client
def _build_contents(
diff --git a/jarvis/plugins/tts/gemini_flash_tts.py b/jarvis/plugins/tts/gemini_flash_tts.py
index 5bae58cb56..65a3c42029 100644
--- a/jarvis/plugins/tts/gemini_flash_tts.py
+++ b/jarvis/plugins/tts/gemini_flash_tts.py
@@ -110,7 +110,7 @@ DEFAULT_VOICES: tuple[str, ...] = (
# triggered the SAPI5 fallback more often — the different sample rate
# (22050 vs 24000) forced mid-stream resample flushes, producing crackling
# and robotic artifacts.
-_SENTENCE_END = re.compile(r"(?<=[.!?…])\s+(?=[A-ZÄÖÜ])") # i18n-allow: DE+EN capital-letter lookahead, matched in logic
+_SENTENCE_END = re.compile(r"(?<=[.!?…])\s+(?=[A-ZÄÖÜ])") # i18n-allow: DE+EN lookahead
class GeminiFlashTTS:
@@ -279,7 +279,12 @@ class GeminiFlashTTS:
self._vertex_project, self._vertex_location, self._model_name,
)
return
- self._client = genai.Client(api_key=self._resolve_api_key())
+ # Routed builder: an AI Studio key stays on AI Studio; a Vertex
+ # express key (AQ.) transparently gets ``vertexai=True`` — the
+ # API-key sibling of the service-account path above.
+ from jarvis.core.google_genai import build_genai_client
+
+ self._client = build_genai_client(self._resolve_api_key())
@staticmethod
def _project_id_from_sa(path: str) -> str | None:
@@ -446,7 +451,8 @@ class GeminiFlashTTS:
continue
log.warning(
- "Gemini TTS empty for sentence %d/%d — SAPI5 emergency brake active (config opt-in).",
+ "Gemini TTS empty for sentence %d/%d — SAPI5 emergency brake "
+ "active (config opt-in).",
i + 1, len(tasks),
)
# SAPI5 deliberately DOES fall back to ``self._language_code`` here
@@ -741,12 +747,12 @@ class GeminiFlashTTS:
)
# Robust against empty responses (safety filter, rate limit, etc.)
if not resp.candidates:
- finish = "unknown"
- try:
- pf = resp.prompt_feedback
- finish = f"block_reason={pf.block_reason}"
- except Exception: # noqa: BLE001
- pass
+ pf = getattr(resp, "prompt_feedback", None)
+ block_reason = getattr(pf, "block_reason", None) if pf else None
+ finish = (
+ f"block_reason={block_reason}" if block_reason is not None
+ else "unknown"
+ )
log.warning("Gemini TTS returned no candidates (%s) — voice=%s text=%r",
finish, voice, text[:80])
return b""
@@ -792,11 +798,11 @@ def _sapi5_synthesize(text: str, language_code: str = "de-DE") -> bytes:
log.warning("pywin32 not installed — SAPI5 fallback not available.")
return b""
- # pywin32 braucht CoInitialize in jedem Thread neu
+ # pywin32 needs a fresh CoInitialize per thread.
try:
pythoncom.CoInitialize()
- except Exception: # noqa: BLE001
- pass
+ except Exception as exc: # noqa: BLE001 — an already-initialized COM apartment is fine
+ log.debug("CoInitialize skipped: %s", exc)
try:
voice = win32com.client.Dispatch("SAPI.SpVoice")