Gemini 中文指南
获取 API 密钥 ↗

机器人流式处理

↓ 下载 MarkdownInteractions API

该 gemini-robotics-er-2-streaming-preview 模型端点公开了一个专用的流端点,该端点与 Live API,实现应用程序和机器人之间的实时双向交互。这使得它适合需要快速反馈循环和对环境做出反应的智能体。

在 Google AI Studio 中体验

从 GitHub 克隆示例应用程序

使用案例 #

  • 多机器人协调:多个机器人通过共享会话传达任务状态并委派子任务。
  • 持续监控:观察场景并在发生特定事件(例如容器达到填充水平)时触发操作的机器人。
  • 仓储物流:拣选和包装智能体可以直观地验证物品、跟踪包装进度并从错误中恢复。

技术规格 #

下表概述了 Live API 的技术规格:

类别详情
输入方式音频(原始 16 位 PCM 音频,16kHz,小端)、图像 (JPEG <= 1FPS)、文本
输出方式文本
协议有状态 WebSocket 连接 (WSS)

构建智能体设置 #

每个基于 Live API 构建的机器人智能体都遵循三个步骤:

  1. 将机器人功能声明为工具。 机器人可以执行的每个动作(导航、抓取、说话)都成为带有名称、描述和参数模式的函数声明。必须使用身体动作 "behavior": "BLOCKING" 因此模型会等待机器人完成后再选择下一步。
  2. 将多模态输入流式传输到持久会话中。 打开一个 live.connect 会话并在任务的整个生命周期中保持打开状态。当视频帧、音频或文本从机器人的传感器到达时发送。
  3. 在接收循环中处理工具调用。 每次模型选择一个动作时,它都会发送一个 tool_call 消息。您的接收循环针对您的机器人 SDK 执行该函数并发回 tool_response。会话保持打开状态,模型根据结果选择下一步操作。

以下部分展示如何将这些步骤应用于三种常见模式:基线智能体循环、使用心跳进行主动场景监控以及通过 TTS 作为工具路由语音。

通过函数调用编排机器人 #

以下示例显示了在单个 Python 脚本中连接在一起的所有三个步骤。

步骤 1 — 工具定义 — 将机器人功能声明为函数声明。的 navigate 功能用途 "behavior": "BLOCKING" 因此模型会等待机器人到达路径点,然后再调用另一个工具。在同一列表中添加更多函数声明以公开其他机器人功能。

步骤 2 - 输入帮助程序 - 显示将不同模态输入流式传输到会话中的三个函数: send_text 对于命令, send_image 对于具有可选文本提示的相机框架,以及 send_audio 用于来自麦克风的原始 PCM 音频。

步骤 3(接收循环)同时运行并处理两种消息: server_content 消息(模型的文本输出)和 tool_call 消息(请求机器人动作的模型)。当工具调用到达时,循环调用 execute_tool — 用真实机器人 SDK 替换的存根 — 然后发回 tool_response 这样模型就可以选择下一步动作。

python
import asyncio
from google import genai
from google.genai import types

MODEL = "gemini-robotics-er-2-streaming-preview"

# ── Tool definitions ─────────────────────────────────────────────────────────
tools = [
   {
       "function_declarations": [
           {
               "name": "navigate",
               "description": "Navigate the robot to a named waypoint.",
               "behavior": "BLOCKING",
               "parameters": {
                   "type": "OBJECT",
                   "properties": {"name": {"type": "STRING"}},
                   "required": ["name"],
               },
           },
           # Add more function definitions here
       ]
   }
]

# ── Stub tool executor (replace with real robot SDK calls) ───────────────────
def execute_tool(name: str, args: dict) -> dict:
   print(f"  [Tool] {name}({args})")
   return {"status": "success"}

# ── Input helpers ────────────────────────────────────────────────────────────
def send_text(session, text: str):
   """Send a text turn."""
   return session.send_client_content(
       turns=types.Content(role="user", parts=[types.Part(text=text)]),
       turn_complete=True,
   )

def send_image(session, image_bytes: bytes, prompt: str = ""):
   """Send a JPEG image with an optional text prompt."""
   parts = [
       types.Part(
           inline_data=types.Blob(data=image_bytes, mime_type="image/jpeg")
       )
   ]
   if prompt:
       parts.append(types.Part(text=prompt))
   return session.send_client_content(
       turns=types.Content(role="user", parts=parts),
       turn_complete=True,
   )

def send_audio(session, audio_chunk: bytes):
   """Stream a chunk of raw PCM audio (16-bit, 16 kHz, mono)."""
   return session.send_realtime_input(
       media=types.Blob(data=audio_chunk, mime_type="audio/pcm;rate=16000")
   )

# ── Receive loop ─────────────────────────────────────────────────────────────
async def receive_loop(session):
   """Print model text and handle tool calls until the session ends."""
   async for message in session.receive():
       if message.server_content:
           sc = message.server_content
           if sc.model_turn and sc.model_turn.parts:
               for part in sc.model_turn.parts:
                   if part.text:
                       print(f"Model: {part.text}", end="", flush=True)
           if sc.turn_complete:
               print("\n[Turn Complete]")
       elif message.tool_call:
           responses = []
           for call in message.tool_call.function_calls:
               print(f"\n[Tool Call] {call.name}({call.args})")
               result = execute_tool(call.name, call.args)
               responses.append(
                   types.FunctionResponse(
                       name=call.name,
                       response=result,
                       id=call.id,
                   )
               )
           await session.send_tool_response(function_responses=responses)

# ── Main ─────────────────────────────────────────────────────────────────────
async def main():
   client = genai.Client(api_key=os.environ["GEMINI_API_KEY"], http_options={"api_version": "v1beta"})
   config = types.LiveConnectConfig(
       response_modalities=["TEXT"],
       tools=tools,
       system_instruction=types.Content(
           parts=[types.Part(text="You are a robot controller. Use tools to execute commands.")]
       ),
   )
   async with client.aio.live.connect(model=MODEL, config=config) as session:
       recv_task = asyncio.create_task(receive_loop(session))
       # Connect robot perception callbacks and user inputs to the helpers above.
       recv_task.cancel()

asyncio.run(main())

每次工具响应后,接收循环保持活动状态。该模型可以构建并修改长期计划,而无需您提前对整个动作序列进行编码。

主动时空推理 #

Live API 流式传输视频,但视频帧本身不会触发新的推理回合。视频帧必须附有文本或音频提示才能触发模型响应。参见 Live API 功能 了解更多详情。

为了实现主动推理,请实施 心跳:定期发送最新的相机帧,然后发送简短的文本提示,迫使模型检查场景并做出明确的决定。视频输入速率限制为每秒一帧。

实现心跳#

心跳协程作为单独的运行 asyncio 同一会话中的任务。在等待每个回合完成时,它会机会性地以 1 Hz 节奏(与视频输入速率限制匹配)为目标(er_turn_done)以避免中断正在进行的推理:

python
async def heartbeat(session, camera, er_turn_done: asyncio.Event):
    TARGET_INTERVAL_SEC = 1.0

    while True:
        start_time = asyncio.get_running_loop().time()

        frame = await camera.latest_jpeg()
        await session.send_realtime_input(
            video=types.Blob(data=frame, mime_type="image/jpeg")
        )
        await session.send_realtime_input(
            text=(
                "[HEARTBEAT] If no task is active, call 'ack' and wait for user"
                " input. If a task is active: observe the scene. If the current"
                " step is progressing correctly, call 'ack'. If the current step"
                " is complete, call 'run_instruction' with the next step. If the"
                " overall goal is achieved, call 'reset' and inform the user."
            )
        )

        # Wait for the model to finish responding before sending the next heartbeat
        await er_turn_done.wait()
        er_turn_done.clear()

        # Sleep only the remaining time to maintain ~1 Hz cadence
        elapsed = asyncio.get_running_loop().time() - start_time
        remaining = TARGET_INTERVAL_SEC - elapsed
        if remaining > 0:
            await asyncio.sleep(remaining)

更新接收循环#

要在模型完成转动时发出信号,请更新您的 receive_loop 设置 er_turn_done:

python
# In receive_loop: signal when the model finishes its turn
if sc.turn_complete:
    er_turn_done.set()

通过外部 TTS 音频输出 #

Gemini Robotics ER 2 返回文本。您的应用程序将完成的响应路由到单独的 TTS 提供商(例如 Gemini TTS)通过注入的回调。这使语音延迟、语音选择和中断行为都在您的控制之下,并让您无需更改即可交换 TTS 后端智能体逻辑。

您还可以将 TTS 声明为工具,以便模型将“说某事”视为“移动手臂”。将以下函数声明添加到您的 tools 第一部分的列表:

python
TOOLS = [
    {
        "name": "send_message",
        "description": (
            "Speak a message aloud via TTS, then deliver it to the"
            " specified target. Use target='user' to speak directly"
            " to the user, or a peer agent name (e.g., 'duo') to"
            " communicate with another robot."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "target": {
                    "type": "string",
                    "description": "Recipient: 'user' or a peer agent name.",
                },
                "message": {
                    "type": "string",
                    "description": "The message to speak and deliver.",
                },
            },
            "required": ["target", "message"],
        },
    },
]

通过将 TTS 封装在函数声明中,模型可以通过与任何其他机器人操作相同的工具调用路径来处理语音。您的应用程序通过注入的回调来完成调用。

GitHub 示例 #

有关完整的工作示例,包括 Spot 机器人零食获取演示和 Tinybot pan-tilt hello world,请参阅 机器人 Live API 示例.

后续步骤 #

搜索标题、API 名称或正文内容