本文說明如何在使用 Gemini Live API 時,設定 Gemini 模型的各種功能。您可以設定工具使用方式 (例如呼叫函式和建立基準),以及即時音訊功能 (例如情緒感知對話和主動判斷式語音)。
設定工具使用方式
多項工具與支援 Gemini Live API 的各種模型版本相容,包括:
如要啟用特定工具,以便在傳回的回覆中使用,請在初始化模型時,將工具名稱加入 tools 清單。以下各節將舉例說明如何在程式碼中使用各項內建工具。
重要事項:Gemini API 不支援在同一個設定要求中,合併使用搜尋工具 (例如 googleSearch) 和非搜尋工具 (例如函式呼叫或 Gemini Enterprise Agent Platform RAG Engine retrieval 工具)。只有在所有工具皆為搜尋工具時,才能同時使用多項工具。
函式呼叫
如要讓模型與您管理的外部系統或 API 互動,請使用呼叫函式。可用於檢查資料庫、傳送電子郵件或與自訂 API 互動等工作。Gemini Live API 支援非同步呼叫函式。詳情請參閱「使用 Gemini Live API 進行非同步函式呼叫」。
模型會生成函式呼叫,應用程式則會執行程式碼,並將結果傳回模型。
所有函式都必須在工作階段開始時宣告,方法是在 LiveConnectConfig 訊息中傳送工具定義。
如要啟用呼叫函式,請在設定訊息的 tools 清單中加入 function_declarations:
Python
import asyncio from google import genai from google.genai.types import ( Content, LiveConnectConfig, Part, ) # Initialize the client. client = genai.Client( enterprise=True, project="GOOGLE_CLOUD_PROJECT", # Replace with your project ID location="LOCATION", # Replace with your location ) MODEL_ID = "gemini-3.8-live" def get_current_weather(location: str) -> str: """Example method. Returns the current weather. Args: location: The city and state, e.g. San Francisco, CA """ weather_map: dict[str, str] = { "Boston, MA": "snowing", "San Francisco, CA": "foggy", "Seattle, WA": "raining", "Austin, TX": "hot", "Chicago, IL": "windy", } return weather_map.get(location, "unknown") async def main(): config = LiveConnectConfig( response_modalities=["AUDIO"], tools=[get_current_weather], ) async with client.aio.live.connect( model=MODEL_ID, config=config, ) as session: text_input = "Get the current weather in Boston." print(f"Input: {text_input}") await session.send_realtime_input(text=text_input) ) async for message in session.receive(): if message.tool_call: function_responses = [] for function_call in message.tool_call.function_calls: print(f"FunctionCall > {function_call}") # Execute the tool and send the response back to the model. result = get_current_weather(**function_call.args) function_responses.append( { "name": function_call.name, "response": {"result": result}, "id": function_call.id, } ) if function_responses: await session.send_tool_response(function_responses=function_responses) if __name__ == "__main__": asyncio.run(main())
如需在系統指令中使用函式呼叫的範例,請參閱最佳做法範例。
Model Context Protocol (MCP) 工具
Google Gen AI SDK 不會在 Gemini Live API 工作階段中,自動執行 Model Context Protocol (MCP) 工具呼叫。如要在 Gemini Live API 工作階段中使用 MCP 工具,可以採取下列任一做法:
- 直接管理 MCP 工具呼叫:如果您直接使用 Google Gen AI SDK,應用程式必須管理 MCP 用戶端工作階段、在模型要求時執行工具呼叫,並使用
send_tool_response傳回結果。 - 使用 Agent Development Kit (ADK):使用 ADK 中的
McpToolset類別,該類別提供 Gemini Live API 的內建 MCP 整合功能。ADK 會自動從 MCP 伺服器探索工具、將其結構定義轉換為函式宣告、在雙向串流期間執行 MCP 工具呼叫,並將工具回應傳回模型。
搭配 ADK 使用 MCP 工具
您可以按照下列步驟,使用 ADK 將 MCP 工具連結至 Gemini Live API:
使用
mcp額外項目安裝google-adk套件:pip install "google-adk[mcp]"建立名為
live_mcp_example.py的指令碼,使用StreamableHTTPConnectionParams將McpToolset連線至 MCP 服務,並使用runner.run_live()串流事件。更改下列內容:
PROJECT_ID:您的 Cloud de Confiance by S3NS 專案 ID。MCP_SERVER_URL:Streamable HTTP MCP 伺服器網址 (例如http://127.0.0.1:8765/mcp)。
import asyncio import contextlib import os from google.adk.agents import Agent, LiveRequestQueue, RunConfig from google.adk.agents.run_config import StreamingMode from google.adk.runners import InMemoryRunner from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams from google.genai import types os.environ.setdefault("GOOGLE_GENAI_USE_ENTERPRISE", "TRUE") os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "PROJECT_ID") os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "us-central1") async def main() -> None: # 1. Connect to the Streamable HTTP MCP service mcp_toolset = McpToolset( connection_params=StreamableHTTPConnectionParams( url="MCP_SERVER_URL", ) ) # 2. Create the ADK Agent with a Gemini Live model and the MCP toolset agent = Agent( name="mcp_live_agent", model="gemini-3.8-live", instruction="You are a helpful assistant. Use the provided MCP tools when needed.", tools=[mcp_toolset], ) runner = InMemoryRunner(agent=agent, app_name="mcp_live_demo") session = await runner.session_service.create_session( app_name="mcp_live_demo", user_id="user_1", ) # 3. Configure bidirectional streaming and send a prompt live_request_queue = LiveRequestQueue() run_config = RunConfig( streaming_mode=StreamingMode.BIDI, response_modalities=[types.Modality.AUDIO], output_audio_transcription=types.AudioTranscriptionConfig(), ) live_request_queue.send_content( types.Content( role="user", parts=[types.Part.from_text(text="What is the weather in Paris?")], ) ) # 4. Stream Live events (ADK automatically executes MCP tools) awaiting_post_tool_response = False saw_function_response = False has_model_output = False try: async with contextlib.aclosing( runner.run_live( user_id="user_1", session_id=session.id, live_request_queue=live_request_queue, run_config=run_config, ) ) as live_events: async for event in live_events: for call in event.get_function_calls(): print(f"[MCP Tool Call] {call.name}({call.args})") awaiting_post_tool_response = True saw_function_response = False has_model_output = False for resp in event.get_function_responses(): print(f"[MCP Tool Response] {resp.name} -> {resp.response}") saw_function_response = True if event.output_transcription and event.output_transcription.text: if not awaiting_post_tool_response or saw_function_response: has_model_output = True awaiting_post_tool_response = False if event.output_transcription.finished: print(f"[Transcript] {event.output_transcription.text}") # Wait for the final response turn after tool execution completes if event.turn_complete: if awaiting_post_tool_response or not has_model_output: continue live_request_queue.close() break finally: await mcp_toolset.close() await runner.close() if __name__ == "__main__": asyncio.run(main())
以 Google 搜尋建立基準
如要讓模型將回覆內容連結至可驗證的資訊來源,提供更準確且符合事實的回覆,請使用以 Google 搜尋強化事實基礎。可用於搜尋網路等工作。
與呼叫函式不同,伺服器端整合會自動處理資訊檢索。
如要啟用「以 Google 搜尋強化事實基礎」,請在設定訊息的 tools 清單中加入 google_search:
Python
import asyncio from google import genai from google.genai.types import ( Content, LiveConnectConfig, Part, ) # Initialize the client. client = genai.Client( enterprise=True, project="GOOGLE_CLOUD_PROJECT", # Replace with your project ID location="LOCATION", # Replace with your location ) MODEL_ID = "gemini-3.8-live" async def main(): config = LiveConnectConfig( response_modalities=["AUDIO"], tools=[{"google_search": {}}], ) async with client.aio.live.connect( model=MODEL_ID, config=config, ) as session: text_input = "What is the current weather in Toronto, Canada?" print(f"Input: {text_input}") await session.send_realtime_input(text=text_input) async for message in session.receive(): # Consume the messages from the model. # In native audio, the model response is in audio format. pass if __name__ == "__main__": asyncio.run(main())
設定情緒感知對話
只有 gemini-live-2.5-flash-native-audio 需要設定情緒感知對話。本節不適用於 gemini-3.8-live。
啟用「情緒感知對話」後,模型會嘗試根據使用者的語氣和情緒表達方式,瞭解並回應。
如要啟用情緒感知對話,請在設定訊息中將 enable_affective_dialog 設為 true:
Python
config = LiveConnectConfig( response_modalities=["AUDIO"], enable_affective_dialog=True, )
設定主動判斷式語音
只有 gemini-live-2.5-flash-native-audio 需要設定主動判斷式語音。主動式音訊功能包含在 gemini-3.8-live 中。
你可以透過主動判斷式語音功能,控制模型回覆的時間。例如,您可以要求 Gemini 僅在收到提示或討論特定主題時回覆。如要觀看主動判斷式語音功能的示範影片,請參閱「Gemini LiveAPI Native Audio Preview」。
如要啟用「主動判斷式語音」,請在設定訊息中設定 proactivity 欄位,並將 proactive_audio 設為 true:
Python
config = LiveConnectConfig( response_modalities=["AUDIO"], proactivity=ProactivityConfig(proactive_audio=True), )
對話範例
以下是與 Gemini 討論烹飪的對話範例:
Prompt: "You are an AI assistant in Italian cooking; only chime in when the topic is about Italian cooking."
Speaker A: "I really love cooking!" (No response from Gemini.)
Speaker B: "Oh yes, me too! My favorite is French cuisine." (No response from
Gemini.)
Speaker A: "I really like Italian food; do you know how to make a pizza?"
(Italian cooking topic triggers response from Gemini.)
Gemini Live API: "I'd be happy to help! Here's a recipe for a pizza."
常見用途
使用「主動判斷式語音」時,Gemini 的運作方式如下:
- 以極低延遲回覆:Gemini 會在使用者說完後回覆,減少中斷情形,並在發生中斷時,協助 Gemini 不遺漏上下文。
- 避免中斷:主動判斷式語音可協助 Gemini 避免受到背景噪音或外部對話干擾,並防止 Gemini 在對話期間插入外部對話時做出回應。
- 處理中斷情形:如果使用者需要在 Gemini 回覆時中斷,主動判斷式語音可讓 Gemini 更輕鬆地適當回應 (也就是處理適當的中斷情形),而不是在使用者使用嗯或呃等填充詞時中斷。
- 共同聆聽音訊:Gemini 可以共同聆聽非說話者聲音的音訊檔案,並在後續對話中回答與該音訊檔案相關的問題。
帳單
Gemini 聽取對話時,系統會收取輸入音訊詞元的費用。
輸出音訊詞元方面,只有在 Gemini 回覆時才會計費。如果 Gemini 沒有回應或保持靜音,系統不會收取輸出音訊權杖的費用。
詳情請參閱「Agent Platform 定價」。
後續步驟
如要進一步瞭解如何使用 Gemini Live API,請參閱: