Skip to content

Build and run agents you can see, understand and trust.

feat(realtime): support Gemini Live API model (#2556)

DavdGao3500806c2968
diff --git a/README.md b/README.md
index 6b15d384b..45bee233c 100644
--- a/README.md
+++ b/README.md
@@ -73,8 +73,8 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
-- **[2026-09] `INTE`:** OpenAI Realtime API supported in `RealtimeAgent` — `gpt-realtime` models with barge-in, truncation and tool calls.
-- **[2026-09] `FEAT` `Experimental`:** Realtime voice agent supported — full-duplex speech-to-speech via `RealtimeAgent` on the DashScope Realtime API (Qwen-Omni, Qwen-Audio-3.0), with barge-in and tool calls. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime)
+- **[2026-09] `INTE`:** Support DashScope, OpenAI, Gemini and xAI realtime APIs in `RealtimeAgent`. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/realtime/full-duplex)
+- **[2026-09] `FEAT` `Experimental`:** Realtime voice agent supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/realtime/overview)
- **[2026-09] `FEAT`:** A2A protocol supported — chat with any remote A2A agent via `A2AAgent`. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/a2a) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/a2a)
- **[2026-08] `FEAT`:** Pipeline supported — run multiple agents by a fixed logic behind one event stream. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/pipeline) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/pipeline/overview)
- **[2026-08] `INTE`:** DingTalk channel supported. [Docs](https://docs.agentscope.io/latest/en/deploy/channel/dingtalk)
diff --git a/README_zh.md b/README_zh.md
index 594146db0..0188f686c 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -72,8 +72,8 @@ AgentScope 的目标是充分发挥大模型的推理与工具调用能力,
## 新闻
<!-- BEGIN NEWS -->
-- **[2026-09] `集成`:** `RealtimeAgent` 支持 OpenAI Realtime API —— 接入 `gpt-realtime` 系列模型,支持打断、截断与工具调用。
-- **[2026-09] `功能` `实验性`:** 支持实时语音智能体 —— 通过 `RealtimeAgent` 接入 DashScope Realtime API(Qwen-Omni、Qwen-Audio-3.0),全双工语音对话、打断与工具调用。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime)
+- **[2026-09] `集成`:** `RealtimeAgent` 支持 DashScope、OpenAI、Gemini 与 xAI 的实时语音 API。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/realtime/full-duplex)
+- **[2026-09] `功能` `实验性`:** 支持实时语音智能体。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/realtime/overview)
- **[2026-09] `功能`:** 支持 A2A 协议 —— 通过 `A2AAgent` 与任意远端 A2A 智能体对话。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/a2a) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/a2a)
- **[2026-08] `功能`:** 支持流水线 —— 按照固化逻辑运行多智能体,并向外提供统一接口。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/pipeline) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/pipeline/overview)
- **[2026-08] `集成`:** 支持钉钉(DingTalk)频道。[文档](https://docs.agentscope.io/latest/zh/deploy/channel/dingtalk)
diff --git a/docs/NEWS.md b/docs/NEWS.md
index d22ffdba9..a544b0995 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,8 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
-- **[2026-09] `INTE`:** OpenAI Realtime API supported in `RealtimeAgent` — `gpt-realtime` models with barge-in, truncation and tool calls.
-- **[2026-09] `FEAT` `Experimental`:** Realtime voice agent supported — full-duplex speech-to-speech via `RealtimeAgent` on the DashScope Realtime API (Qwen-Omni, Qwen-Audio-3.0), with barge-in and tool calls. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime)
+- **[2026-09] `INTE`:** Support DashScope, OpenAI, Gemini and xAI realtime APIs in `RealtimeAgent`. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/realtime/full-duplex)
+- **[2026-09] `FEAT` `Experimental`:** Realtime voice agent supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/realtime/overview)
- **[2026-09] `FEAT`:** A2A protocol supported — chat with any remote A2A agent via `A2AAgent`. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/a2a) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/a2a)
- **[2026-08] `FEAT`:** Pipeline supported — run multiple agents by a fixed logic behind one event stream. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/pipeline) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/pipeline/overview)
- **[2026-08] `INTE`:** DingTalk channel supported. [Docs](https://docs.agentscope.io/latest/en/deploy/channel/dingtalk)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 2444392c6..e80bb4474 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,8 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
-- **[2026-09] `集成`:** `RealtimeAgent` 支持 OpenAI Realtime API —— 接入 `gpt-realtime` 系列模型,支持打断、截断与工具调用。
-- **[2026-09] `功能` `实验性`:** 支持实时语音智能体 —— 通过 `RealtimeAgent` 接入 DashScope Realtime API(Qwen-Omni、Qwen-Audio-3.0),全双工语音对话、打断与工具调用。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime)
+- **[2026-09] `集成`:** `RealtimeAgent` 支持 DashScope、OpenAI、Gemini 与 xAI 的实时语音 API。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/realtime/full-duplex)
+- **[2026-09] `功能` `实验性`:** 支持实时语音智能体。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/realtime) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/realtime/overview)
- **[2026-09] `功能`:** 支持 A2A 协议 —— 通过 `A2AAgent` 与任意远端 A2A 智能体对话。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/a2a) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/a2a)
- **[2026-08] `功能`:** 支持流水线 —— 按照固化逻辑运行多智能体,并向外提供统一接口。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/pipeline) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/pipeline/overview)
- **[2026-08] `集成`:** 支持钉钉(DingTalk)频道。[文档](https://docs.agentscope.io/latest/zh/deploy/channel/dingtalk)
diff --git a/src/agentscope/agent/_realtime/_agent.py b/src/agentscope/agent/_realtime/_agent.py
index 6d8ddc54d..4b8b1a6c5 100644
--- a/src/agentscope/agent/_realtime/_agent.py
+++ b/src/agentscope/agent/_realtime/_agent.py
@@ -830,7 +830,7 @@ class RealtimeAgent:
self._emit(
ModelCallStartEvent(
reply_id=self._reply_id,
- model_name=self.model.model_name,
+ model_name=self.model.model,
),
)
return self._reply
diff --git a/src/agentscope/credential/_gemini.py b/src/agentscope/credential/_gemini.py
index 7eacbdf8f..336958479 100644
--- a/src/agentscope/credential/_gemini.py
+++ b/src/agentscope/credential/_gemini.py
@@ -9,6 +9,7 @@ from ._base import CredentialBase
if TYPE_CHECKING:
from ..embedding import EmbeddingModelBase
from ..model import ChatModelBase
+ from ..realtime import RealtimeModelBase
from ..tts import TTSModelBase
@@ -47,3 +48,12 @@ class GeminiCredential(CredentialBase):
from ..tts import GeminiTTSModel
return [GeminiTTSModel]
+
+ @classmethod
+ def get_realtime_model_classes(
+ cls,
+ ) -> list[Type["RealtimeModelBase"]]:
+ """Return the Gemini realtime model classes."""
+ from ..realtime import GeminiRealtimeModel
+
+ return [GeminiRealtimeModel]
diff --git a/src/agentscope/realtime/__init__.py b/src/agentscope/realtime/__init__.py
index bb5de85fc..d24365f62 100644
--- a/src/agentscope/realtime/__init__.py
+++ b/src/agentscope/realtime/__init__.py
@@ -23,6 +23,7 @@ from ._events import (
ToolCallEvent,
TranscriptDeltaEvent,
)
+from ._gemini import GeminiRealtimeModel
from ._model_card import RealtimeModelCard
from ._openai import OpenAIRealtimeModel
from ._playout import PlayoutPosition
@@ -42,6 +43,7 @@ __all__ = [
"RealtimeModelBase",
"DashScopeRealtimeModel",
"DashScopeAudioRealtimeModel",
+ "GeminiRealtimeModel",
"OpenAIRealtimeModel",
"XAIRealtimeModel",
"RealtimeModelCard",
diff --git a/src/agentscope/realtime/_base.py b/src/agentscope/realtime/_base.py
index dd7030d8f..6f3a10833 100644
--- a/src/agentscope/realtime/_base.py
+++ b/src/agentscope/realtime/_base.py
@@ -58,7 +58,7 @@ class RealtimeModelBase(ABC):
def __init__(
self,
- model_name: str,
+ model: str,
credential: CredentialBase,
parameters: "RealtimeModelBase.Parameters | None" = None,
model_card: RealtimeModelCard | None = None,
@@ -66,7 +66,7 @@ class RealtimeModelBase(ABC):
"""Initialize the realtime model.
Args:
- model_name (`str`):
+ model (`str`):
The model name, e.g. ``"qwen3-omni-flash-realtime"``.
credential (`CredentialBase`):
The credential used to authenticate against the provider.
@@ -74,26 +74,26 @@ class RealtimeModelBase(ABC):
Provider-specific parameters; defaults are used if omitted.
model_card (`RealtimeModelCard | None`, optional):
The model card. When ``None`` it is looked up by
- *model_name* among the cards shipped with this class, so
+ *model* among the cards shipped with this class, so
that constructing a model by name alone still yields the
right sample rates and limits.
Raises:
- `ValueError`: If no card is given and none matches *model_name*.
+ `ValueError`: If no card is given and none matches *model*.
"""
- self.model_name = model_name
+ self.model = model
self.credential = credential
self.parameters = parameters or self.Parameters()
- self.card = model_card or self._find_card(model_name)
+ self.card = model_card or self._find_card(model)
@classmethod
- def _find_card(cls, model_name: str) -> RealtimeModelCard:
- """Look up the shipped card for *model_name*."""
+ def _find_card(cls, model: str) -> RealtimeModelCard:
+ """Look up the shipped card for *model*."""
for card in cls.list_models():
- if card.name == model_name:
+ if card.name == model:
return card
raise ValueError(
- f"No realtime model card found for {model_name!r} in "
+ f"No realtime model card found for {model!r} in "
f"{cls.__name__}. Pass `model_card` explicitly for a model "
f"that ships no card.",
)
diff --git a/src/agentscope/realtime/_dashscope/_model.py b/src/agentscope/realtime/_dashscope/_model.py
index f350510c6..dfc561ac2 100644
--- a/src/agentscope/realtime/_dashscope/_model.py
+++ b/src/agentscope/realtime/_dashscope/_model.py
@@ -53,7 +53,7 @@ class DashScopeRealtimeModel(RealtimeModelBase):
def __init__(
self,
- model_name: str,
+ model: str,
credential: DashScopeCredential,
parameters: "DashScopeRealtimeModel.Parameters | None" = None,
model_card: RealtimeModelCard | None = None,
@@ -61,7 +61,7 @@ class DashScopeRealtimeModel(RealtimeModelBase):
"""Initialize the DashScope realtime model.
Args:
- model_name (`str`):
+ model (`str`):
The model name, e.g. ``"qwen3-omni-flash-realtime"``.
credential (`DashScopeCredential`):
The DashScope credential.
@@ -70,7 +70,7 @@ class DashScopeRealtimeModel(RealtimeModelBase):
model_card (`RealtimeModelCard | None`, optional):
The model card, looked up by name if omitted.
"""
- super().__init__(model_name, credential, parameters, model_card)
+ super().__init__(model, credential, parameters, model_card)
self.parameters: DashScopeRealtimeModel.Parameters
self._ws: Any = None
self._reader: asyncio.Task | None = None
@@ -99,7 +99,7 @@ class DashScopeRealtimeModel(RealtimeModelBase):
credential: DashScopeCredential = self.credential # type: ignore
self._ws = await websockets.connect(
- f"{_REALTIME_URL}?model={self.model_name}",
+ f"{_REALTIME_URL}?model={self.model}",
additional_headers={
"Authorization": f"Bearer "
f"{credential.api_key.get_secret_value()}",
diff --git a/src/agentscope/realtime/_gemini/__init__.py b/src/agentscope/realtime/_gemini/__init__.py
new file mode 100644
index 000000000..c920de344
--- /dev/null
+++ b/src/agentscope/realtime/_gemini/__init__.py
@@ -0,0 +1,5 @@
+# -*- coding: utf-8 -*-
+"""The Gemini realtime models."""
+from ._model import GeminiRealtimeModel
+
+__all__ = ["GeminiRealtimeModel"]
diff --git a/src/agentscope/realtime/_gemini/_model.py b/src/agentscope/realtime/_gemini/_model.py
new file mode 100644
index 000000000..b21487f53
--- /dev/null
+++ b/src/agentscope/realtime/_gemini/_model.py
@@ -0,0 +1,482 @@
+# -*- coding: utf-8 -*-
+"""The Gemini Live API realtime model."""
+import asyncio
+import base64
+import json
+import uuid
+from typing import Any, AsyncIterator, Literal
+
+from pydantic import Field
+
+from .. import _events as me
+from .._base import (
+ ModelDisconnectedError,
+ RealtimeModelBase,
+ TruncationSupport,
+)
+from .._model_card import RealtimeModelCard
+from ..._logging import logger
+from ..._utils._common import _flatten_json_schema
+from ...credential import GeminiCredential
+from ...message import TextBlock, ToolCallBlock, ToolResultBlock
+from ...model._gemini._model import _sanitize_schema_for_gemini
+
+_LIVE_URL = (
+ "wss://generativelanguage.googleapis.com/ws/"
+ "google.ai.generativelanguage.v1beta.GenerativeService"
+ ".BidiGenerateContent"
+)
+
+
+class GeminiRealtimeModel(RealtimeModelBase):
+ """The Gemini Live API over WebSocket.
+
+ Three protocol traits shape this adapter:
+
+ - Nothing on the wire is addressable. An item id is minted here for
+ each model turn and each user turn so every event carries one.
+ - Generation is implicit: a finished user turn or a tool response
+ starts the reply, so :meth:`request_response` sends nothing.
+ - Interruption is the server's job — it reports
+ ``serverContent.interrupted`` and drops the rest of the reply
+ itself — so :meth:`truncate` and :meth:`cancel_response` are no-ops.
+ With caller-owned turns the caller silences the reply locally
+ instead, and the server is told not to interrupt on its own.
+ """
+
+ class Parameters(RealtimeModelBase.Parameters):
+ """Tuneables surfaced to the UI."""
+
+ voice: str = Field(default="Puck", title="Voice")
+ turn_detection: Literal["automatic", "none"] = Field(
+ default="automatic",
+ title="Turn Detection",
+ description="``none`` hands endpointing to the caller.",
+ )
+ start_sensitivity: Literal["HIGH", "LOW"] = Field(
+ default="HIGH",
+ description="How eagerly speech is detected as started.",
+ )
+ end_sensitivity: Literal["HIGH", "LOW"] = Field(
+ default="HIGH",
+ description="How eagerly speech is detected as ended.",
+ )
+ prefix_padding_ms: int = Field(default=300, ge=0)
+ silence_duration_ms: int = Field(default=800, ge=0)
+ input_audio_transcription: bool = Field(
+ default=True,
+ title="Transcribe Input",
+ description="Whether to transcribe the user's speech.",
+ )
+
+ type = "gemini_realtime"
+ truncation = TruncationSupport.SERVER
+ supports_text_input = True
+
+ def __init__(
+ self,
+ model: str,
+ credential: GeminiCredential,
+ parameters: "GeminiRealtimeModel.Parameters | None" = None,
+ model_card: RealtimeModelCard | None = None,
+ ) -> None:
+ """Initialize the Gemini realtime model.
+
+ Args:
+ model (`str`):
+ The model name, e.g. ``"gemini-3.1-flash-live-preview"``.
+ credential (`GeminiCredential`):
+ The Gemini credential.
+ parameters (`GeminiRealtimeModel.Parameters | None`, optional):
+ Provider parameters; defaults are used if omitted.
+ model_card (`RealtimeModelCard | None`, optional):
+ The model card, looked up by name if omitted.
+ """
+ super().__init__(model, credential, parameters, model_card)
+ self.parameters: GeminiRealtimeModel.Parameters
+ self.resumption_handle = ""
+ """The latest handle the server offered. Not used on reconnect:
+ the agent carries the transcript in the instructions instead."""
+ self._ws: Any = None
+ self._reader: asyncio.Task | None = None
+ self._queue: asyncio.Queue[me.ModelEvent | None] = asyncio.Queue()
+ self._response_id = ""
+ self._user_id = ""
+ self._input_text = ""
+ self._usage: dict = {}
+ self._activity = False
+ self._ready = asyncio.Event()
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+
+ async def connect(
+ self,
+ instructions: str,
+ tools: list[dict] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Open the WebSocket and send the setup message."""
+ import websockets
+
+ if kwargs.get("turn_detection_disabled"):
+ self.parameters = self.parameters.model_copy(
+ update={"turn_detection": "none"},
+ )
+ self._response_id, self._user_id, self._input_text = "", "", ""
+ self._usage, self._activity = {}, False
+
+ credential: GeminiCredential = self.credential # type: ignore
+ self._ws = await websockets.connect(
+ f"{_LIVE_URL}?key={credential.api_key.get_secret_value()}",
+ )
+ self._ready.clear()
+ self._reader = asyncio.create_task(self._read(), name="gemini-rt")
+ await self._send(
+ self._setup(
+ instructions,
+ tools,
+ kwargs.get("resumption_handle", ""),
+ ),
+ )
+ # Realtime input is rejected until the server acknowledges setup.
+ await self._ready.wait()
+ if self._ws is None:
+ raise ModelDisconnectedError("Session closed during setup.")
+
+ async def close(self) -> None:
+ """Stop reading and close the WebSocket."""
+ if self._reader is not None:
+ self._reader.cancel()
+ await asyncio.gather(self._reader, return_exceptions=True)
+ self._reader = None
+ if self._ws is not None:
+ await self._ws.close()
+ self._ws = None
+
+ async def events(self) -> AsyncIterator[me.ModelEvent]:
+ """Yield events until the session ends."""
+ while True:
+ event = await self._queue.get()
+ if event is None:
+ return
+ yield event
+
+ # ------------------------------------------------------------------
+ # Input
+ # ------------------------------------------------------------------
+
+ async def push_audio(self, pcm: bytes) -> None:
+ """Send PCM16 mono audio at :attr:`input_sample_rate`. With
+ caller-owned turns, the first chunk opens the activity window that
+ :meth:`commit_turn` closes."""
+ if self.parameters.turn_detection == "none" and not self._activity:
+ self._activity = True
+ await self._send({"realtimeInput": {"activityStart": {}}})
+ await self._send(
+ {
+ "realtimeInput": {
+ "audio": {
+ "mimeType": f"audio/pcm;rate={self.input_sample_rate}",
+ "data": base64.b64encode(pcm).decode("ascii"),
+ },
+ },
+ },
+ )
+
+ async def push_text(self, text: str) -> None:
+ """Send a complete text turn, which the model answers at once."""
+ await self._send(
+ {
+ "clientContent": {
+ "turns": [{"role": "user", "parts": [{"text": text}]}],
+ "turnComplete": True,
+ },
+ },
+ )
+
+ async def push_tool_result(self, block: ToolResultBlock) -> None:
+ """Send one ``functionResponse``; the model resumes on its own."""
+ output = (
+ block.output
+ if isinstance(block.output, str)
+ else "".join(
+ _.text for _ in block.output if isinstance(_, TextBlock)
+ )
+ )
+ await self._send(
+ {
+ "toolResponse": {
+ "functionResponses": [
+ {
+ "id": block.id,
+ "name": block.name,
+ "response": {"output": output},
+ },
+ ],
+ },
+ },
+ )
+
+ async def commit_turn(self) -> None:
+ """Close the activity window, which asks for the reply."""
+ if self._activity:
+ self._activity = False
+ await self._send({"realtimeInput": {"activityEnd": {}}})
+
+ # ------------------------------------------------------------------
+ # Response control
+ # ------------------------------------------------------------------
+
+ async def request_response(self) -> None:
+ """No-op: a finished turn or a tool response is the request."""
+
+ async def cancel_response(self) -> None:
+ """No-op: the protocol has no cancel frame."""
+
+ async def truncate(
+ self,
+ item_id: str,
+ played_ms: int,
+ played_text: str,
+ ) -> None:
+ """No-op: the server drops the interrupted reply itself."""
+
+ # ------------------------------------------------------------------
+ # Wire
+ # ------------------------------------------------------------------
+
+ def _setup(
+ self,
+ instructions: str,
+ tools: list[dict] | None,
+ resumption_handle: str,
+ ) -> dict:
+ """Build the ``setup`` message, the only one the server accepts
+ first and the only place the session can be configured."""
+ p = self.parameters
+ if p.turn_detection == "none":
+ # The caller barges in locally; letting the server do it too
+ # would kill every reply, since audio keeps flowing between
+ # turns and each one reopens its activity window.
+ realtime_input = {
+ "automaticActivityDetection": {"disabled": True},
+ "activityHandling": "NO_INTERRUPTION",
+ }
+ else:
+ realtime_input = {
+ "automaticActivityDetection": {
+ "startOfSpeechSensitivity": (
+ f"START_SENSITIVITY_{p.start_sensitivity}"
+ ),
+ "endOfSpeechSensitivity": (
+ f"END_SENSITIVITY_{p.end_sensitivity}"
+ ),
+ "prefixPaddingMs": p.prefix_padding_ms,
+ "silenceDurationMs": p.silence_duration_ms,
+ },
+ }
+ setup: dict[str, Any] = {
+ "model": f"models/{self.model}",
+ "generationConfig": {
+ "responseModalities": ["AUDIO"],
+ "speechConfig": {
+ "voiceConfig": {
+ "prebuiltVoiceConfig": {"voiceName": p.voice},
+ },
+ },
+ },
+ "systemInstruction": {"parts": [{"text": instructions}]},
+ "realtimeInputConfig": realtime_input,
+ # Audio is the only response modality, so the reply's text
+ # exists nowhere else.
+ "outputAudioTranscription": {},
+ "sessionResumption": (
+ {"handle": resumption_handle} if resumption_handle else {}
+ ),
+ }
+ if p.input_audio_transcription:
+ setup["inputAudioTranscription"] = {}
+ if tools and self.card.supports_tools:
+ setup["tools"] = [
+ {
+ "functionDeclarations": [
+ {
+ **schema["function"],
+ "parameters": _sanitize_schema_for_gemini(
+ _flatten_json_schema(
+ schema["function"].get("parameters", {}),
+ ),
+ ),
+ }
+ for schema in tools
+ if "function" in schema
+ ],
+ },
+ ]
+ return {"setup": setup}
+
+ async def _send(self, payload: dict) -> None:
+ """Send one JSON frame.
+
+ Raises:
+ `ModelDisconnectedError`: If the provider has closed the
+ session, e.g. after its connection lifetime is up.
+ """
+ from websockets.exceptions import ConnectionClosed
+
+ if self._ws is None:
+ raise ModelDisconnectedError("Not connected.")
+ try:
+ await self._ws.send(json.dumps(payload, ensure_ascii=False))
+ except ConnectionClosed as exc:
+ self._ws = None
+ raise ModelDisconnectedError(str(exc.rcvd or exc)) from exc
+
+ async def _read(self) -> None:
+ """Drain the WebSocket into the event queue until it closes."""
+ try:
+ async for raw in self._ws:
+ if isinstance(raw, bytes):
+ raw = raw.decode("utf-8")
+ try:
+ events = self._parse(json.loads(raw))
+ except Exception: # noqa: BLE001
+ logger.exception("GeminiRealtimeModel: bad frame")
+ continue
+ for event in events:
+ self._queue.put_nowait(event)
+ except Exception as exc: # noqa: BLE001
+ logger.error("GeminiRealtimeModel: connection lost: %s", exc)
+ finally:
+ self._ws = None
+ self._ready.set() # release a connect() still waiting
+ self._queue.put_nowait(me.SessionEndedEvent(reason="closed"))
+ self._queue.put_nowait(None)
+
+ def _open_response(self) -> list[me.ModelEvent]:
+ """Start a model turn: settle the user turn it answers, and mint
+ the id every event of this turn carries."""
+ if self._response_id:
+ return []
+ events: list[me.ModelEvent] = []
+ if self._input_text:
+ # Input transcription arrives in fragments; the user turn is
+ # settled only once the model starts answering it.
+ events.append(
+ me.InputTranscriptionEvent(
+ item_id=self._user_id,
+ text=self._input_text,
+ ),
+ )
+ self._user_id, self._input_text = "", ""
+ self._response_id = uuid.uuid4().hex
+ events.append(me.ResponseCreatedEvent(item_id=self._response_id))
+ return events
+
+ def _parse(self, data: dict) -> list[me.ModelEvent]:
+ """Translate one server message into model events."""
+ if usage := data.get("usageMetadata"):
+ self._usage = usage
+
+ if "serverContent" in data:
+ return self._parse_content(data["serverContent"])
+
+ if tool_call := data.get("toolCall"):
+ # The server hands the floor over with a tool call, so the
+ # reply ends here and the follow-up is a turn of its own.
+ events = self._open_response()
+ events += [
+ me.ToolCallEvent(
+ item_id=self._response_id,
+ tool_call=ToolCallBlock(
+ id=call.get("id") or uuid.uuid4().hex,
+ name=call.get("name", ""),
+ input=json.dumps(
+ call.get("args") or {},
+ ensure_ascii=False,
+ ),
+ ),
+ )
+ for call in tool_call.get("functionCalls") or []
+ ]
+ return events + self._close_response()
+
+ if go_away := data.get("goAway"):
+ # Advance notice only; the session ends when the socket does.
+ logger.info(
+ "GeminiRealtimeModel: server closes in %s",
+ go_away.get("timeLeft", "0s"),
+ )
+ return []
+
+ if update := data.get("sessionResumptionUpdate"):
+ if update.get("resumable"):
+ self.resumption_handle = update.get("newHandle", "")
+ return []
+
+ if "setupComplete" in data:
+ self._ready.set()
+ else:
+ logger.debug("GeminiRealtimeModel: ignoring %s", list(data))
+ return []
+
+ def _parse_content(self, content: dict) -> list[me.ModelEvent]:
+ """Translate one ``serverContent`` message into model events."""
+ events: list[me.ModelEvent] = []
+
+ if text := (content.get("inputTranscription") or {}).get("text"):
+ self._user_id = self._user_id or uuid.uuid4().hex
+ self._input_text += text
+
+ if content.get("interrupted"):
+ # The only notice that the user spoke over the reply; the
+ # server has already dropped the rest of it.
+ self._user_id = self._user_id or uuid.uuid4().hex
+ self._response_id, self._usage = "", {}
+ return [me.SpeechStartedEvent(item_id=self._user_id)]
+
+ parts = (content.get("modelTurn") or {}).get("parts") or []
+ transcript = (content.get("outputTranscription") or {}).get("text", "")
+ if parts or transcript:
+ events += self._open_response()
+ for part in parts:
+ if data := (part.get("inlineData") or {}).get("data"):
+ events.append(
+ me.AudioDeltaEvent(
+ item_id=self._response_id,
+ pcm=base64.b64decode(data),
+ sample_rate=self.output_sample_rate,
+ ),
+ )
+ elif part.get("text"):
+ events.append(
+ me.TranscriptDeltaEvent(
+ item_id=self._response_id,
+ delta=part["text"],
+ ),
+ )
+ if transcript:
+ events.append(
+ me.TranscriptDeltaEvent(
+ item_id=self._response_id,
+ delta=transcript,
+ ),
+ )
+
+ if content.get("turnComplete"):
+ events += self._close_response()
+ return events
+
+ def _close_response(self) -> list[me.ModelEvent]:
+ """End the open model turn with the usage last reported."""
+ if not self._response_id:
+ return []
+ event = me.ResponseDoneEvent(
+ item_id=self._response_id,
+ input_tokens=self._usage.get("promptTokenCount", 0),
+ output_tokens=self._usage.get("responseTokenCount", 0),
+ )
+ self._response_id, self._usage = "", {}
+ return [event]
diff --git a/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml b/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml
new file mode 100644
index 000000000..1c4e36b00
--- /dev/null
+++ b/src/agentscope/realtime/_gemini/_models/gemini-2.5-flash-native-audio-preview-12-2025.yaml
@@ -0,0 +1,30 @@
+type: realtime_model
+name: gemini-2.5-flash-native-audio-preview-12-2025
+label: Gemini 2.5 Flash Native Audio
+status: active
+
+input_types:
+ - audio/pcm
+ - text/plain
+output_types:
+ - audio/pcm
+ - text/plain
+
+input_sample_rate: 16000
+output_sample_rate: 24000
+
+supports_tools: true
+
+max_context_tokens: 131072
+# Audio-only sessions are capped at 15 minutes; the connection itself
+# lasts about 10 and is resumed with a `sessionResumption` handle.
+max_session_duration_s: 900
+
+parameter_overrides:
+ voice:
+ enum: ["Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda", "Orus",
+ "Aoede", "Callirrhoe", "Autonoe", "Enceladus", "Iapetus",
+ "Umbriel", "Algieba", "Despina", "Erinome", "Algenib",
+ "Rasalgethi", "Laomedeia", "Achernar", "Alnilam", "Schedar",
+ "Gacrux", "Pulcherrima", "Achird", "Zubenelgenubi",
+ "Vindemiatrix", "Sadachbia", "Sadaltager", "Sulafat"]
diff --git a/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml b/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml
new file mode 100644
index 000000000..7041df507
--- /dev/null
+++ b/src/agentscope/realtime/_gemini/_models/gemini-3.1-flash-live-preview.yaml
@@ -0,0 +1,30 @@
+type: realtime_model
+name: gemini-3.1-flash-live-preview
+label: Gemini 3.1 Flash Live
+status: active
+
+input_types:
+ - audio/pcm
+ - text/plain
+output_types:
+ - audio/pcm
+ - text/plain
+
+input_sample_rate: 16000
+output_sample_rate: 24000
+
+supports_tools: true
+
+max_context_tokens: 131072
+# Audio-only sessions are capped at 15 minutes; the connection itself
+# lasts about 10 and is resumed with a `sessionResumption` handle.
+max_session_duration_s: 900
+
+parameter_overrides:
+ voice:
+ enum: ["Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda", "Orus",
+ "Aoede", "Callirrhoe", "Autonoe", "Enceladus", "Iapetus",
+ "Umbriel", "Algieba", "Despina", "Erinome", "Algenib",
+ "Rasalgethi", "Laomedeia", "Achernar", "Alnilam", "Schedar",
+ "Gacrux", "Pulcherrima", "Achird", "Zubenelgenubi",
+ "Vindemiatrix", "Sadachbia", "Sadaltager", "Sulafat"]
diff --git a/src/agentscope/realtime/_openai/_model.py b/src/agentscope/realtime/_openai/_model.py
index fc9d21d78..30cf6e2cc 100644
--- a/src/agentscope/realtime/_openai/_model.py
+++ b/src/agentscope/realtime/_openai/_model.py
@@ -70,7 +70,7 @@ class OpenAIRealtimeModel(RealtimeModelBase):
def __init__(
self,
- model_name: str,
+ model: str,
credential: OpenAICredential,
parameters: "OpenAIRealtimeModel.Parameters | None" = None,
model_card: RealtimeModelCard | None = None,
@@ -78,7 +78,7 @@ class OpenAIRealtimeModel(RealtimeModelBase):
"""Initialize the OpenAI realtime model.
Args:
- model_name (`str`):
+ model (`str`):
The model name, e.g. ``"gpt-realtime-2.1"``.
credential (`OpenAICredential`):
The OpenAI credential.
@@ -87,7 +87,7 @@ class OpenAIRealtimeModel(RealtimeModelBase):
model_card (`RealtimeModelCard | None`, optional):
The model card, looked up by name if omitted.
"""
- super().__init__(model_name, credential, parameters, model_card)
+ super().__init__(model, credential, parameters, model_card)
self.parameters: OpenAIRealtimeModel.Parameters
self._ws: Any = None
self._reader: asyncio.Task | None = None
@@ -125,7 +125,7 @@ class OpenAIRealtimeModel(RealtimeModelBase):
# ``https`` -> ``wss``, ``http`` -> ``ws``.
url = base_url.replace("http", "ws", 1)
self._ws = await websockets.connect(
- f"{url}/realtime?model={self.model_name}",
+ f"{url}/realtime?model={self.model}",
additional_headers=headers,
)
self._reader = asyncio.create_task(self._read(), name="openai-rt")
diff --git a/src/agentscope/realtime/_xai/_model.py b/src/agentscope/realtime/_xai/_model.py
index e5a5131cc..280512784 100644
--- a/src/agentscope/realtime/_xai/_model.py
+++ b/src/agentscope/realtime/_xai/_model.py
@@ -62,7 +62,7 @@ class XAIRealtimeModel(RealtimeModelBase):
def __init__(
self,
- model_name: str,
+ model: str,
credential: XAICredential,
parameters: "XAIRealtimeModel.Parameters | None" = None,
model_card: RealtimeModelCard | None = None,
@@ -70,7 +70,7 @@ class XAIRealtimeModel(RealtimeModelBase):
"""Initialize the xAI realtime model.
Args:
- model_name (`str`):
+ model (`str`):
The model name, e.g. ``"grok-voice-latest"``.
credential (`XAICredential`):
The xAI credential.
@@ -79,7 +79,7 @@ class XAIRealtimeModel(RealtimeModelBase):
model_card (`RealtimeModelCard | None`, optional):
The model card, looked up by name if omitted.
"""
- super().__init__(model_name, credential, parameters, model_card)
+ super().__init__(model, credential, parameters, model_card)
self.parameters: XAIRealtimeModel.Parameters
self._ws: Any = None
self._reader: asyncio.Task | None = None
@@ -107,8 +107,7 @@ class XAIRealtimeModel(RealtimeModelBase):
credential: XAICredential = self.credential # type: ignore
self._ws = await websockets.connect(
- f"wss://{credential.api_host}/v1/realtime"
- f"?model={self.model_name}",
+ f"wss://{credential.api_host}/v1/realtime" f"?model={self.model}",
additional_headers={
"Authorization": f"Bearer "
f"{credential.api_key.get_secret_value()}",
diff --git a/tests/realtime_gemini_test.py b/tests/realtime_gemini_test.py
new file mode 100644
index 000000000..1125b8186
--- /dev/null
+++ b/tests/realtime_gemini_test.py
@@ -0,0 +1,543 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for the Gemini Live realtime adapter: cards, the setup
+message and frame parsing. Nothing here opens a connection."""
+# pylint: disable=protected-access
+import base64
+import unittest
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString
+
+from agentscope.credential import GeminiCredential
+from agentscope.message import ToolResultBlock
+from agentscope.realtime import (
+ GeminiRealtimeModel,
+ ModelDisconnectedError,
+ TruncationSupport,
+)
+
+CRED = GeminiCredential(api_key="key-x")
+MODEL = "gemini-3.1-flash-live-preview"
+TOOLS = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get the weather.",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+ },
+]
+
+
+def _dump(events: list) -> list:
+ """Events as ``(class name, fields)`` pairs, comparable to literals."""
+ return [(type(e).__name__, e.model_dump()) for e in events]
+
+
+class GeminiCardsTest(unittest.TestCase):
+ """The shipped cards and the credential lookup that finds them."""
+
+ def test_cards(self) -> None:
+ """Both Live dialog models, tagged with the adapter type."""
+ self.assertListEqual(
+ [
+ (
+ c.name,
+ c.model_type,
+ c.supports_tools,
+ c.max_context_tokens,
+ c.max_session_duration_s,
+ c.output_sample_rate,
+ )
+ for c in GeminiRealtimeModel.list_models()
+ ],
+ [
+ (
+ "gemini-2.5-flash-native-audio-preview-12-2025",
+ "gemini_realtime",
+ True,
+ 131072,
+ 900,
+ 24000,
+ ),
+ (
+ "gemini-3.1-flash-live-preview",
+ "gemini_realtime",
+ True,
+ 131072,
+ 900,
+ 24000,
+ ),
+ ],
+ )
+
+ def test_credential_maps_card_back_to_class(self) -> None:
+ """The service-layer lookup: card.model_type -> class, no scan."""
+ classes = {c.type: c for c in CRED.get_realtime_model_classes()}
+ self.assertDictEqual(
+ {
+ card.name: classes[card.model_type].__name__
+ for card in CRED.list_realtime_models()
+ },
+ {
+ "gemini-2.5-flash-native-audio-preview-12-2025": (
+ "GeminiRealtimeModel"
+ ),
+ "gemini-3.1-flash-live-preview": "GeminiRealtimeModel",
+ },
+ )
+
+ def test_unknown_model_name_is_rejected(self) -> None:
+ """A name with no card fails at construction."""
+ with self.assertRaises(ValueError):
+ GeminiRealtimeModel("no-such-model", CRED)
+
+ def test_adapter_facts(self) -> None:
+ """Protocol facts of the adapter, constant across its models."""
+ model = GeminiRealtimeModel(MODEL, CRED)
+ self.assertListEqual(
+ [
+ model.type,
+ model.truncation,
+ model.supports_text_input,
+ model.input_sample_rate,
+ model.output_sample_rate,
+ ],
+ [
+ "gemini_realtime",
+ TruncationSupport.SERVER,
+ True,
+ 16000,
+ 24000,
+ ],
+ )
+
+
+class GeminiSetupTest(unittest.TestCase):
+ """The setup message sent on connect."""
+
+ def test_automatic_turn_detection(self) -> None:
+ """Server VAD, tools and both transcriptions."""
+ model = GeminiRealtimeModel(MODEL, CRED)
+ self.assertDictEqual(
+ model._setup("be nice", TOOLS, ""),
+ {
+ "setup": {
+ "model": "models/gemini-3.1-flash-live-preview",
+ "generationConfig": {
+ "responseModalities": ["AUDIO"],
+ "speechConfig": {
+ "voiceConfig": {
+ "prebuiltVoiceConfig": {"voiceName": "Puck"},
+ },
+ },
+ },
+ "systemInstruction": {"parts": [{"text": "be nice"}]},
+ "realtimeInputConfig": {
+ "automaticActivityDetection": {
+ "startOfSpeechSensitivity": (
+ "START_SENSITIVITY_HIGH"
+ ),
+ "endOfSpeechSensitivity": "END_SENSITIVITY_HIGH",
+ "prefixPaddingMs": 300,
+ "silenceDurationMs": 800,
+ },
+ },
+ "outputAudioTranscription": {},
+ "sessionResumption": {},
+ "inputAudioTranscription": {},
+ "tools": [
+ {
+ "functionDeclarations": [
+ {
+ "name": "get_weather",
+ "description": "Get the weather.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "city": {"type": "string"},
+ },
+ "required": ["city"],
+ },
+ },
+ ],
+ },
+ ],
+ },
+ },
+ )
+
+ def test_caller_owned_turn_detection(self) -> None:
+ """``none`` disables server VAD and its interruptions, and the
+ resumption handle is echoed back."""
+ model = GeminiRealtimeModel(
+ MODEL,
+ CRED,
+ parameters=GeminiRealtimeModel.Parameters(
+ voice="Kore",
+ turn_detection="none",
+ input_audio_transcription=False,
+ ),
+ )
+ self.assertDictEqual(
+ model._setup("hi", None, "h-1"),
+ {
+ "setup": {
+ "model": "models/gemini-3.1-flash-live-preview",
+ "generationConfig": {
+ "responseModalities": ["AUDIO"],
+ "speechConfig": {
+ "voiceConfig": {
+ "prebuiltVoiceConfig": {"voiceName": "Kore"},
+ },
+ },
+ },
+ "systemInstruction": {"parts": [{"text": "hi"}]},
+ "realtimeInputConfig": {
+ "automaticActivityDetection": {"disabled": True},
+ "activityHandling": "NO_INTERRUPTION",
+ },
+ "outputAudioTranscription": {},
+ "sessionResumption": {"handle": "h-1"},
+ },
+ },
+ )
+
+
+class GeminiParseTest(unittest.TestCase):
+ """Server messages -> model events."""
+
+ def setUp(self) -> None:
+ """A fresh model per test; no connection is opened."""
+ self.model = GeminiRealtimeModel(MODEL, CRED)
+
+ def test_reply_messages(self) -> None:
+ """A whole turn: transcription fragments settle when the reply
+ starts, audio and transcript stream, usage lands on the end."""
+ audio = base64.b64encode(b"\x01\x00").decode()
+ messages = [
+ {"setupComplete": {}},
+ {"serverContent": {"inputTranscription": {"text": "今天"}}},
+ {"serverContent": {"inputTranscription": {"text": "天气"}}},
+ {
+ "serverContent": {
+ "modelTurn": {
+ "parts": [
+ {
+ "inlineData": {
+ "mimeType": "audio/pcm;rate=24000",
+ "data": audio,
+ },
+ },
+ ],
+ },
+ },
+ },
+ {"serverContent": {"outputTranscription": {"text": "晴天"}}},
+ {"serverContent": {"generationComplete": True}},
+ {
+ "usageMetadata": {
+ "promptTokenCount": 10,
+ "responseTokenCount": 5,
+ "totalTokenCount": 15,
+ },
+ "serverContent": {"turnComplete": True},
+ },
+ ]
+ self.assertListEqual(
+ [_dump(self.model._parse(m)) for m in messages],
+ [
+ [],
+ [],
+ [],
+ [
+ (
+ "InputTranscriptionEvent",
+ {"item_id": AnyString(), "text": "今天天气"},
+ ),
+ ("ResponseCreatedEvent", {"item_id": AnyString()}),
+ (
+ "AudioDeltaEvent",
+ {
+ "item_id": AnyString(),
+ "pcm": b"\x01\x00",
+ "sample_rate": 24000,
+ },
+ ),
+ ],
+ [
+ (
+ "TranscriptDeltaEvent",
+ {"item_id": AnyString(), "delta": "晴天"},
+ ),
+ ],
+ [],
+ [
+ (
+ "ResponseDoneEvent",
+ {
+ "item_id": AnyString(),
+ "input_tokens": 10,
+ "output_tokens": 5,
+ },
+ ),
+ ],
+ ],
+ )
+
+ def test_tool_call_ends_the_turn(self) -> None:
+ """A tool call hands the floor back, so the reply is closed with
+ it and the caller can run the tool."""
+ self.assertListEqual(
+ _dump(
+ self.model._parse(
+ {
+ "toolCall": {
+ "functionCalls": [
+ {
+ "id": "c1",
+ "name": "get_weather",
+ "args": {"city": "上海"},
+ },
+ ],
+ },
+ },
+ ),
+ ),
+ [
+ ("ResponseCreatedEvent", {"item_id": AnyString()}),
+ (
+ "ToolCallEvent",
+ {
+ "item_id": AnyString(),
+ "tool_call": {
+ "type": "tool_call",
+ "id": "c1",
+ "name": "get_weather",
+ "input": '{"city": "上海"}',
+ "state": "pending",
+ "suggested_rules": [],
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ },
+ ),
+ (
+ "ResponseDoneEvent",
+ {
+ "item_id": AnyString(),
+ "input_tokens": 0,
+ "output_tokens": 0,
+ },
+ ),
+ ],
+ )
+
+ def test_interrupted_is_the_barge_in_notice(self) -> None:
+ """``interrupted`` is the only signal that the user spoke over
+ the reply; the turn is dropped without a done event."""
+ self.model._parse(
+ {"serverContent": {"outputTranscription": {"text": "晴"}}},
+ )
+ self.assertListEqual(
+ [
+ _dump(
+ self.model._parse(
+ {"serverContent": {"interrupted": True}},
+ ),
+ ),
+ _dump(
+ self.model._parse(
+ {"serverContent": {"turnComplete": True}},
+ ),
+ ),
+ ],
+ [
+ [
+ (
+ "SpeechStartedEvent",
+ {"item_id": AnyString(), "at_ms": 0},
+ ),
+ ],
+ [],
+ ],
+ )
+
+ def test_setup_complete_releases_connect(self) -> None:
+ """``connect()`` waits on the setup acknowledgement, which the
+ reader flags when it arrives."""
+ self.assertListEqual(
+ [
+ self.model._ready.is_set(),
+ self.model._parse({"setupComplete": {}}),
+ self.model._ready.is_set(),
+ ],
+ [False, [], True],
+ )
+
+ def test_session_messages(self) -> None:
+ """Resumption handles are kept; ``goAway`` and tool-call
+ cancellation carry no event."""
+ handles = [
+ self.model._parse(
+ {
+ "sessionResumptionUpdate": {
+ "newHandle": "h-1",
+ "resumable": True,
+ },
+ },
+ ),
+ self.model.resumption_handle,
+ _dump(
+ self.model._parse({"toolCallCancellation": {"ids": ["c1"]}}),
+ ),
+ _dump(self.model._parse({"goAway": {"timeLeft": "10s"}})),
+ ]
+ self.assertListEqual(
+ handles,
+ [
+ [],
+ "h-1",
+ [],
+ [],
+ ],
+ )
+
+
+class GeminiSendTest(IsolatedAsyncioTestCase):
+ """The frames each input method puts on the wire."""
+
+ def setUp(self) -> None:
+ """Capture what would be sent instead of sending it."""
+ self.model = GeminiRealtimeModel(MODEL, CRED)
+ self.sent: list[dict] = []
+
+ async def capture(payload: dict) -> None:
+ """Record one frame."""
+ self.sent.append(payload)
+
+ self.model._send = capture # type: ignore[method-assign]
+
+ async def test_text_turn_and_tool_result(self) -> None:
+ """A text turn is complete on arrival; a tool result resumes the
+ model without asking for a response."""
+ await self.model.push_text("你好")
+ await self.model.push_tool_result(
+ ToolResultBlock(id="c1", name="get_weather", output="晴天"),
+ )
+ await self.model.request_response()
+ self.assertListEqual(
+ self.sent,
+ [
+ {
+ "clientContent": {
+ "turns": [
+ {"role": "user", "parts": [{"text": "你好"}]},
+ ],
+ "turnComplete": True,
+ },
+ },
+ {
+ "toolResponse": {
+ "functionResponses": [
+ {
+ "id": "c1",
+ "name": "get_weather",
+ "response": {"output": "晴天"},
+ },
+ ],
+ },
+ },
+ ],
+ )
+
+ async def test_caller_owned_turn_brackets_the_audio(self) -> None:
+ """With server VAD off, the first chunk opens the activity window
+ and the commit closes it."""
+ self.model.parameters = GeminiRealtimeModel.Parameters(
+ turn_detection="none",
+ )
+ await self.model.push_audio(b"\x01\x00")
+ await self.model.push_audio(b"\x02\x00")
+ await self.model.commit_turn()
+ await self.model.commit_turn()
+ self.assertListEqual(
+ self.sent,
+ [
+ {"realtimeInput": {"activityStart": {}}},
+ {
+ "realtimeInput": {
+ "audio": {
+ "mimeType": "audio/pcm;rate=16000",
+ "data": "AQA=",
+ },
+ },
+ },
+ {
+ "realtimeInput": {
+ "audio": {
+ "mimeType": "audio/pcm;rate=16000",
+ "data": "AgA=",
+ },
+ },
+ },
+ {"realtimeInput": {"activityEnd": {}}},
+ ],
+ )
+
+ async def test_server_turn_detection_sends_audio_only(self) -> None:
+ """With server VAD the caller never brackets anything."""
+ await self.model.push_audio(b"\x01\x00")
+ await self.model.commit_turn()
+ self.assertListEqual(
+ self.sent,
+ [
+ {
+ "realtimeInput": {
+ "audio": {
+ "mimeType": "audio/pcm;rate=16000",
+ "data": "AQA=",
+ },
+ },
+ },
+ ],
+ )
+
+
+class GeminiDisconnectTest(IsolatedAsyncioTestCase):
+ """A closed WebSocket surfaces as ModelDisconnectedError."""
+
+ async def test_send_on_closed_socket(self) -> None:
+ """websockets' ConnectionClosed becomes the realtime-level error
+ and the socket reference is dropped."""
+ from websockets.exceptions import ConnectionClosedError
+ from websockets.frames import Close
+
+ class ClosedSocket:
+ """Raises like a socket the provider already closed."""
+
+ async def send(self, _payload: str) -> None:
+ """Fail with the provider's close frame."""
+ close = Close(1011, "connection lifetime")
+ raise ConnectionClosedError(close, close, True)
+
+ model = GeminiRealtimeModel(MODEL, CRED)
+ model._ws = ClosedSocket()
+
+ with self.assertRaises(ModelDisconnectedError) as ctx:
+ await model.push_audio(b"\x00\x00")
+ self.assertEqual(
+ (str(ctx.exception), model._ws),
+ ("1011 (internal error) connection lifetime", None),
+ )
+
+ async def test_send_before_connect(self) -> None:
+ """No socket at all is the same condition."""
+ model = GeminiRealtimeModel(MODEL, CRED)
+ with self.assertRaises(ModelDisconnectedError):
+ await model.push_text("你好")