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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(realtime): Gemini Live adapter over google-genai Live API
Ruben Lütkeed31d9a8cc04
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pynew file mode 100644index 0000000000..d3f1678951--- /dev/null+++ b/jarvis/plugins/realtime/gemini_live.py@@ -0,0 +1,145 @@+"""Gemini Live realtime provider (google-genai Live API) for jarvis.realtime.++Structural mirror of ``openai_realtime.py``: same class shape, same lazy-import+discipline (AP-26 — ``from google import genai`` / ``from google.genai import+types`` only inside methods, never at module top), same ``RealtimeEvent``+mapping style. This module must not import ``jarvis.*`` beyond the config+secret helper, ``jarvis.core.protocols.AudioChunk`` and+``jarvis.realtime.protocol`` (both stdlib-light, no heavy side effects).++Live audio is 16 kHz PCM in / 24 kHz PCM out. The mic is already captured at+16 kHz, so — unlike the OpenAI adapter, which upsamples 16 kHz -> 24 kHz+before ``input_audio_buffer.append`` — no resample happens here.++Verified against the INSTALLED SDK (google-genai==2.9.0, checked 2026-07-08):+- ``genai.Client(api_key=...).aio.live.connect(model=..., config=...)`` is an+ async context manager (``AsyncIterator[AsyncSession]``); call it to get the+ cm, then ``await cm.__aenter__()`` / ``await cm.__aexit__(None, None,+ None)`` (mirrors the plan's usage; ``genai.live.AsyncLive.connect``).+- ``AsyncSession`` exposes: ``close``, ``receive``, ``send``,+ ``send_client_content``, ``send_realtime_input``, ``send_tool_response``,+ ``start_stream``. Audio in goes through+ ``send_realtime_input(audio=types.Blob(data=..., mime_type=...))``+ (``Blob`` fields: ``data``, ``display_name``, ``mime_type``).+- ``receive()`` yields ``types.LiveServerMessage``, which has a ``.data``+ *property* (not a model field — concatenates inline audio parts from+ ``server_content.model_turn``, ``None`` when there is none) plus a+ ``server_content`` field of type ``LiveServerContent`` with fields+ ``input_transcription``, ``output_transcription``, ``interrupted``,+ ``turn_complete`` (both transcription fields are ``Transcription`` objects+ with a ``.text`` field) — exactly the shape this module maps below.+- ``types.LiveConnectConfig`` has ``response_modalities``,+ ``system_instruction``, ``input_audio_transcription`` and+ ``output_audio_transcription`` (both ``AudioTranscriptionConfig``) among+ its fields — transcripts are OFF by default and MUST be requested via the+ latter two, or ``server_content`` never carries a transcription.++Model id: ``gemini-3.1-flash-live-preview``, confirmed live on+https://ai.google.dev/gemini-api/docs/live-api/get-started-sdk (fetched+2026-07-08) as the model used in that page's ``client.aio.live.connect()``+Python/JS examples — i.e. reachable with a plain Google AI Studio API key+(no Vertex AI service account needed). The older ``gemini-2.0-flash-live-001``+id from the initial task brief no longer appears in current docs; use the+verified id above. Re-verify if AI Studio deprecates this preview model.+"""++from __future__ import annotations++import logging+from collections.abc import AsyncIterator+from typing import Any++from jarvis.core.config import get_provider_secret+from jarvis.core.protocols import AudioChunk+from jarvis.realtime.protocol import RealtimeEvent, RealtimeSessionConfig++log = logging.getLogger(__name__)++_MODEL = "gemini-3.1-flash-live-preview"+_INPUT_RATE = 16000 # mic is already 16 kHz -- no resample before send+_OUTPUT_RATE = 24000+++class _GeminiLiveSession:+ def __init__(self, session: Any, cm: Any, cfg: RealtimeSessionConfig, session_id: str) -> None:+ self._session = session # the live AsyncSession+ self._cm = cm # the async context manager `connect()` returned, for close()+ self._cfg = cfg+ self.session_id = session_id++ async def send_audio(self, chunk: AudioChunk) -> None:+ from google.genai import types # lazy (AP-26)++ pcm = chunk.pcm # mic is 16 kHz == _INPUT_RATE; no resample needed+ await self._session.send_realtime_input(+ audio=types.Blob(data=pcm, mime_type=f"audio/pcm;rate={_INPUT_RATE}")+ )++ async def receive(self) -> AsyncIterator[RealtimeEvent]:+ async for msg in self._session.receive():+ data = getattr(msg, "data", None)+ if data:+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(pcm=data, sample_rate=_OUTPUT_RATE, timestamp_ns=0),+ )+ sc = getattr(msg, "server_content", None)+ if sc is not None:+ ot = getattr(sc, "output_transcription", None)+ if ot and getattr(ot, "text", None):+ yield RealtimeEvent(type="output_transcript_delta", text=ot.text)+ it = getattr(sc, "input_transcription", None)+ if it and getattr(it, "text", None):+ yield RealtimeEvent(type="input_transcript", text=it.text, is_final=True)+ if getattr(sc, "interrupted", False):+ yield RealtimeEvent(type="speech_started")+ if getattr(sc, "turn_complete", False):+ yield RealtimeEvent(type="turn_complete")++ async def update_session(+ self, *, instructions: str | None = None, language: str | None = None+ ) -> None:+ # Gemini Live sets system_instruction only at connect time; there is no+ # mid-session update call on AsyncSession. An honest no-op.+ return None++ async def truncate(self, audio_end_ms: int) -> None:+ return None # server-side context trim not exposed; barge-in handled by send flow++ async def interrupt(self) -> None:+ return None # interruption is driven by new input audio (server VAD)++ async def close(self) -> None:+ try:+ await self._cm.__aexit__(None, None, None)+ except Exception: # noqa: BLE001+ log.debug("gemini-live: session close raised, ignoring", exc_info=True)+++class GeminiLiveProvider:+ name = "gemini-live"+ supports_realtime = True+ input_sample_rate = _INPUT_RATE+ output_sample_rate = _OUTPUT_RATE++ async def can_open_duplex_session(self) -> bool:+ return bool(get_provider_secret("gemini"))++ async def open_session(self, cfg: RealtimeSessionConfig) -> _GeminiLiveSession:+ from google import genai # lazy (AP-26)+ from google.genai import types++ client = genai.Client(api_key=get_provider_secret("gemini"))+ live_config = types.LiveConnectConfig(+ # types.Modality is a str-Enum ("AUDIO" == Modality.AUDIO at runtime);+ # the enum member (not a bare string) satisfies the SDK's static type.+ response_modalities=[types.Modality.AUDIO],+ system_instruction=cfg.instructions or None,+ input_audio_transcription=types.AudioTranscriptionConfig(),+ output_audio_transcription=types.AudioTranscriptionConfig(),+ )+ cm = client.aio.live.connect(model=_MODEL, config=live_config)+ session = await cm.__aenter__()+ import uuid++ return _GeminiLiveSession(session, cm, cfg, session_id=str(uuid.uuid4()))diff --git a/tests/contract/test_realtime_provider_contract.py b/tests/contract/test_realtime_provider_contract.pyindex 7e56a1f181..f52cc25f0f 100644--- a/tests/contract/test_realtime_provider_contract.py+++ b/tests/contract/test_realtime_provider_contract.py@@ -8,6 +8,11 @@ def _load_provider_class():return OpenAIRealtimeProvider+def _load_gemini_provider_class():+ from jarvis.plugins.realtime.gemini_live import GeminiLiveProvider+ return GeminiLiveProvider++def test_provider_is_structurally_conformant():cls = _load_provider_class()inst = cls()@@ -16,6 +21,14 @@ def test_provider_is_structurally_conformant():assert inst.name == "openai-realtime"+def test_gemini_live_provider_is_structurally_conformant():+ cls = _load_gemini_provider_class()+ inst = cls()+ assert isinstance(inst, RealtimeProvider)+ assert inst.supports_realtime is True+ assert inst.name == "gemini-live"++@pytest.mark.asyncioasync def test_can_open_duplex_session_returns_bool_when_keyless(monkeypatch):import jarvis.plugins.realtime.openai_realtime as mod@@ -25,6 +38,15 @@ async def test_can_open_duplex_session_returns_bool_when_keyless(monkeypatch):assert await inst.can_open_duplex_session() is False+async def test_gemini_live_can_open_duplex_session_returns_bool_when_keyless(monkeypatch):+ import jarvis.plugins.realtime.gemini_live as mod++ monkeypatch.setattr(mod, "get_provider_secret", lambda _p: None)+ inst = _load_gemini_provider_class()()+ assert await inst.can_open_duplex_session() is False++def test_module_does_not_import_openai_at_top_level():# AP-26: the SDK import is lazy inside methods, not at module import.import ast@@ -39,3 +61,19 @@ def test_module_does_not_import_openai_at_top_level():for n in (getattr(node, "names", []) or [])]assert not any("openai" in (a.name or "") for a in top_imports)+++def test_gemini_live_module_does_not_import_google_genai_at_top_level():+ # AP-26: the SDK import is lazy inside methods, not at module import.+ import ast+ import pathlib++ src = pathlib.Path("jarvis/plugins/realtime/gemini_live.py").read_text("utf-8")+ tree = ast.parse(src)+ top_imports = [+ n+ for node in tree.body+ if isinstance(node, (ast.Import, ast.ImportFrom))+ for n in (getattr(node, "names", []) or [])+ ]+ assert not any("google" in (a.name or "") for a in top_imports)diff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.pynew file mode 100644index 0000000000..1a7a79b31a--- /dev/null+++ b/tests/unit/realtime/test_gemini_live.py@@ -0,0 +1,156 @@+"""Unit tests for the Gemini Live realtime adapter (google-genai Live API).++All google-genai types are faked with ``SimpleNamespace`` / plain async+generators -- these tests never touch the network or the real SDK.+"""++from __future__ import annotations++import ast+import pathlib+from types import SimpleNamespace++import pytest++from jarvis.plugins.realtime.gemini_live import GeminiLiveProvider, _GeminiLiveSession+from jarvis.realtime.protocol import RealtimeSessionConfig+++async def test_can_open_duplex_session_reflects_key(monkeypatch):+ monkeypatch.setattr(+ "jarvis.plugins.realtime.gemini_live.get_provider_secret",+ lambda name: "AIza-test" if name == "gemini" else "",+ )+ assert await GeminiLiveProvider().can_open_duplex_session() is True++ monkeypatch.setattr(+ "jarvis.plugins.realtime.gemini_live.get_provider_secret", lambda name: ""+ )+ assert await GeminiLiveProvider().can_open_duplex_session() is False+++def test_provider_shape():+ p = GeminiLiveProvider()+ assert p.name == "gemini-live" and p.supports_realtime is True+ assert p.input_sample_rate == 16000 and p.output_sample_rate == 24000+++def _fake_message(*, data=None, server_content=None):+ return SimpleNamespace(data=data, server_content=server_content)+++async def test_receive_maps_all_five_event_types():+ """A synthetic google-genai receive() stream maps 1:1 to RealtimeEvent."""++ messages = [+ # audio_delta+ _fake_message(data=b"\x01\x02\x03\x04"),+ # output_transcript_delta+ _fake_message(+ server_content=SimpleNamespace(+ output_transcription=SimpleNamespace(text="hello there"),+ input_transcription=None,+ interrupted=False,+ turn_complete=False,+ )+ ),+ # input_transcript (final)+ _fake_message(+ server_content=SimpleNamespace(+ output_transcription=None,+ input_transcription=SimpleNamespace(text="what the user said"),+ interrupted=False,+ turn_complete=False,+ )+ ),+ # speech_started (interrupted flag)+ _fake_message(+ server_content=SimpleNamespace(+ output_transcription=None,+ input_transcription=None,+ interrupted=True,+ turn_complete=False,+ )+ ),+ # turn_complete+ _fake_message(+ server_content=SimpleNamespace(+ output_transcription=None,+ input_transcription=None,+ interrupted=False,+ turn_complete=True,+ )+ ),+ ]++ async def fake_receive():+ for msg in messages:+ yield msg++ fake_session = SimpleNamespace(receive=fake_receive)+ session = _GeminiLiveSession(+ session=fake_session,+ cm=SimpleNamespace(),+ cfg=RealtimeSessionConfig(),+ session_id="s1",+ )++ events = [ev async for ev in session.receive()]++ assert [ev.type for ev in events] == [+ "audio_delta",+ "output_transcript_delta",+ "input_transcript",+ "speech_started",+ "turn_complete",+ ]+ assert events[0].audio is not None+ assert events[0].audio.pcm == b"\x01\x02\x03\x04"+ assert events[0].audio.sample_rate == 24000+ assert events[1].text == "hello there"+ assert events[2].text == "what the user said"+ assert events[2].is_final is True+++async def test_close_calls_context_manager_aexit():+ aexit_calls = []++ class _FakeCM:+ async def __aexit__(self, *args):+ aexit_calls.append(args)++ session = _GeminiLiveSession(+ session=SimpleNamespace(),+ cm=_FakeCM(),+ cfg=RealtimeSessionConfig(),+ session_id="s1",+ )+ await session.close()+ assert aexit_calls == [(None, None, None)]+++def test_module_does_not_import_google_genai_at_top_level():+ # AP-26: the SDK import is lazy inside methods, not at module import.+ src = pathlib.Path("jarvis/plugins/realtime/gemini_live.py").read_text("utf-8")+ tree = ast.parse(src)+ top_imports = [+ n+ for node in tree.body+ if isinstance(node, (ast.Import, ast.ImportFrom))+ for n in (getattr(node, "names", []) or [])+ ]+ assert not any("google" in (a.name or "") for a in top_imports)++ # Belt and suspenders: importing the module must not pull google.genai+ # into sys.modules either.+ import sys++ sys.modules.pop("jarvis.plugins.realtime.gemini_live", None)+ had_genai_before = "google.genai" in sys.modules+ import jarvis.plugins.realtime.gemini_live # noqa: F401++ if not had_genai_before:+ assert "google.genai" not in sys.modules