Gemini 中文指南
获取 API 密钥 ↗

在 Live API 中使用工具

↓ 下载 MarkdownInteractions API

工具的使用使 Live API 能够超越单纯的对话,使其能够在现实世界中执行操作并引入外部上下文,同时保持实时连接。您可以定义工具,例如 函数调用 和 Google 搜索 与 Live API。

支持的工具概述 #

工具

Gemini 3.8 Live

Gemini 3.8 Live Extended Thinking

Gemini 3.1 Flash Live Preview

Gemini 2.5 Flash Live Preview

搜索

支持

支持

支持

支持

函数调用

支持(同步和 异步)

支持(仅异步)

支持(仅同步)

支持(同步和 异步)

Google 地图

不支持

不支持

不支持

不支持

代码执行

不支持

不支持

不支持

不支持

URL 上下文

不支持

不支持

不支持

不支持

函数调用 #

Live API 支持函数调用,就像常规内容生成请求一样。 函数调用允许 Live API 与外部数据和程序交互,从而大大增加您的应用程序可以完成的任务。

您可以将函数声明定义为会话配置的一部分。收到工具调用后,客户端应响应一个列表 FunctionResponse 对象使用 session.send_tool_response 方法。

请参阅 函数调用教程 了解更多。

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

client = genai.Client(http_options={"api_version": "v1beta"})

model = "gemini-3.8-live"

# Simple function definitions
turn_on_the_lights = {"name": "turn_on_the_lights"}
turn_off_the_lights = {"name": "turn_off_the_lights"}

tools = [{"function_declarations": [turn_on_the_lights, turn_off_the_lights]}]
config = {"response_modalities": ["AUDIO"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Turn on the lights please"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        wf = wave.open("audio.wav", "wb")
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(24000) # Output is 24kHz

        async for response in session.receive():
            if response.data is not None:
                wf.writeframes(response.data)
            elif response.tool_call:
                print("The tool was called")
                function_responses = []
                for fc in response.tool_call.function_calls:
                    function_response = types.FunctionResponse(
                        id=fc.id,
                        name=fc.name,
                        response={ "result": "ok" } # simple, hard-coded function response
                    )
                    function_responses.append(function_response)

                await session.send_tool_response(function_responses=function_responses)

        wf.close()

if __name__ == "__main__":
    asyncio.run(main())

通过单个提示,模型可以生成多个函数调用以及链接其输出所需的代码。这段代码在沙盒环境中执行,生成后续的 Bidi生成内容工具调用 消息。

异步函数调用 #

函数调用默认情况下按顺序执行,这意味着执行会暂停,直到每个函数调用的结果可用。这确保了顺序处理,这意味着在函数运行时您将无法继续与模型交互。

如果您不想阻止对话,可以告诉模型异步运行函数。为此,您首先需要添加一个 behavior 到函数定义:

python
# Non-blocking function definitions
turn_on_the_lights = {"name": "turn_on_the_lights", "behavior": "NON_BLOCKING"} # turn_on_the_lights will run asynchronously
turn_off_the_lights = {"name": "turn_off_the_lights"} # turn_off_the_lights will still pause all interactions with the model

NON-BLOCKING 确保函数异步运行,同时您可以继续与模型交互。

然后你需要告诉模型当它接收到时如何表现 FunctionResponse 使用 scheduling 参数。它可以:

  • 中断它正在做的事情并告诉您它立即得到的响应(scheduling="INTERRUPT"),

  • 等到它完成当前正在做的事情(scheduling="WHEN_IDLE"),

  • 或者什么也不做,并在稍后的讨论中使用这些知识(scheduling="SILENT")

python
# for a non-blocking function definition, apply scheduling in the function response:
  function_response = types.FunctionResponse(
      id=fc.id,
      name=fc.name,
      response={
          "result": "ok",
          "scheduling": "INTERRUPT" # Can also be WHEN_IDLE or SILENT
      }
  )

您可以在会话配置中启用事实依据和 Google 搜索。这提高了 Live API 的准确性并防止产生幻觉。请参阅 事实依据教程 了解更多。

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

client = genai.Client(http_options={"api_version": "v1beta"})

model = "gemini-3.8-live"

tools = [{'google_search': {}}]
config = {"response_modalities": ["AUDIO"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "When did the last Brazil vs. Argentina soccer match happen?"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        wf = wave.open("audio.wav", "wb")
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(24000) # Output is 24kHz

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.data is not None:
                    wf.writeframes(chunk.data)

                # The model might generate and execute Python code to use Search
                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                        if part.executable_code is not None:
                            print(part.executable_code.code)

                        if part.code_execution_result is not None:
                            print(part.code_execution_result.output)

        wf.close()

if __name__ == "__main__":
    asyncio.run(main())

结合多种工具 #

您可以在 Live API 中组合多个工具,进一步增强应用程序的功能:

python
prompt = """
Hey, I need you to do two things for me.

1. Use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
2. Then turn on the lights

Thanks!
"""

tools = [
    {"google_search": {}},
    {"function_declarations": [turn_on_the_lights, turn_off_the_lights]},
]

config = {"response_modalities": ["AUDIO"], "tools": tools}

# ... remaining model call

后续步骤 #

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