Multimodal Live API

Multimodal Live API 可讓您與 Gemini 進行低延遲的雙向語音/視訊互動。使用 Multimodal Live API,您可以為使用者提供自然流暢的對話體驗,並讓使用者透過語音指令中斷模型的回覆。模型可處理文字、音訊和影片輸入內容,並提供文字和音訊輸出內容。

您可以在 Google AI Studio 中試用 Multimodal Live API。

使用 Multimodal Live API

本節說明如何搭配使用 Multimodal Live API 和其中一個 SDK。如要進一步瞭解基礎 WebSockets API,請參閱下方的 WebSockets API 參考資料

收發簡訊

import asyncio
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY", http_options={'api_version': 'v1alpha'})
model = "gemini-2.0-flash-exp"

config = {"response_modalities": ["TEXT"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        while True:
            message = input("User> ")
            if message.lower() == "exit":
                break
            await session.send(input=message, end_of_turn=True)

            async for response in session.receive():
                if response.text is not None:
                    print(response.text, end="")

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

接收音訊

以下範例說明如何接收音訊資料,並將資料寫入 .wav 檔案。

import asyncio
import wave
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY", http_options={'api_version': 'v1alpha'})
model = "gemini-2.0-flash-exp"

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

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        wf = wave.open("audio.wav", "wb")
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(24000)

        message = "Hello? Gemini are you there?"
        await session.send(input=message, end_of_turn=True)

        async for idx,response in async_enumerate(session.receive()):
            if response.data is not None:
                wf.writeframes(response.data)

            # Comment this out to print audio data info
            # if response.server_content.model_turn is not None:
            #      print(response.server_content.model_turn.parts[0].inline_data.mime_type)

        wf.close()

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

音訊格式

Multimodal Live API 支援下列音訊格式:

  • 輸入音訊格式:原始 16 位元 PCM 音訊,位元深度為 16 位元,取樣率為 16 kHz 小端序
  • 輸出音訊格式:24 kHz 小端序的原始 16 位元 PCM 音訊

串流音訊和影片

系統指示

系統指示可讓您根據特定需求和用途,引導模型的行為。系統指示可在設定配置中設定,並在整個工作階段中持續生效。

from google.genai import types

config = {
    "system_instruction": types.Content(
        parts=[
            types.Part(
                text="You are a helpful assistant and answer in a friendly tone."
            )
        ]
    ),
    "response_modalities": ["TEXT"],
}

逐步更新內容

使用遞增更新功能傳送文字輸入內容、建立工作階段背景資訊或還原工作階段背景資訊。針對短時間的內容,您可以傳送逐向互動,以代表確切的事件順序:

PythonJSON
from google.genai import types

turns = [
    types.Content(parts=[types.Part(text="What is the capital of France?")], role="user"),
    types.Content(parts=[types.Part(text="Paris")], role="model")
]
await session.send(input=types.LiveClientContent(turns=turns))

turns = [types.Content(parts=[types.Part(text="What is the capital of Germany?")], role="user")]
await session.send(input=types.LiveClientContent(turns=turns, turn_complete=True))
{
  "clientContent": {
    "turns": [
      {
        "parts":[
          {
            "text": ""
          }
        ],
        "role":"user"
      },
      {
        "parts":[
          {
            "text": ""
          }
        ],
        "role":"model"
      }
    ],
    "turnComplete": true
  }
}

對於較長的背景資訊,建議您提供單一訊息摘要,以便釋出脈絡窗口,供後續互動使用。

變更語音

Multimodal Live API 支援以下語音:Aoede、Charon、Fenrir、Kore 和 Puck。

如要指定語音,請在 speechConfig 物件中設定語音名稱,做為工作階段設定的一部分:

PythonJSON
from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    speech_config=types.SpeechConfig(
        voice_config=types.VoiceConfig(
            prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
        )
    )
)
{
  "voiceConfig": {
    "prebuiltVoiceConfig": {
      "voiceName": "Kore"
    }
  }
}

使用函式呼叫

您可以使用 Multimodal Live API 定義工具。請參閱函式呼叫教學課程,進一步瞭解函式呼叫。

您必須在工作階段設定中定義工具:

config = types.LiveConnectConfig(
    response_modalities=["TEXT"],
    tools=[set_light_values]
)

async with client.aio.live.connect(model=model, config=config) as session:
    await session.send(input="Turn the lights down to a romantic level", end_of_turn=True)

    async for response in session.receive():
        print(response.tool_call)

模型可從單一提示產生多個函式呼叫,以及連結輸出的必要程式碼。這個程式碼會在沙箱環境中執行,產生後續的 BidiGenerateContentToolCall 訊息。執行作業會暫停,直到每個函式呼叫的結果可用為止,藉此確保按順序處理。

用戶端應回傳 BidiGenerateContentToolResponse

音訊輸入和輸出會對模型使用函式呼叫的功能造成負面影響。

處理中斷

使用者隨時可以中斷模型的輸出內容。當語音活動偵測功能 (VAD) 偵測到中斷情形時,系統會取消並捨棄目前的產生作業。只有已傳送至用戶端的資訊會保留在工作階段記錄中。接著,伺服器會傳送 BidiGenerateContentServerContent 訊息,回報中斷情形。

此外,Gemini 伺服器會捨棄任何待處理的函式呼叫,並傳送含有取消呼叫 ID 的 BidiGenerateContentServerContent 訊息。

async for response in session.receive():
    if response.server_content.interrupted is not None:
        # The generation was interrupted

限制

規劃專案時,請考量 Multimodal Live API 和 Gemini 2.0 的下列限制。

用戶端驗證

Multimodal Live API 只提供伺服器對伺服器驗證,不建議直接用於用戶端。用戶端輸入內容應透過中介應用程式伺服器轉送,以便透過 Multimodal Live API 進行安全驗證。

對話記錄

雖然模型會追蹤工作階段中的互動,但不會儲存對話記錄。工作階段結束時,系統會清除對應的上下文。

為了還原先前的會話,或為模型提供使用者互動的歷史背景資訊,應用程式應自行維護對話記錄,並使用 BidiGenerateContentClientContent 訊息,在新的會話開始時傳送這項資訊。

工作階段持續時間上限

音訊工作階段持續時間上限為 15 分鐘,音訊和視訊工作階段則上限為 2 分鐘。如果工作階段時間長度超過限制,連線就會終止。

模型也受限於內容大小。與視訊和音訊串流一併傳送大量內容,可能會導致工作階段提早終止。

語音活動偵測 (VAD)

模型會自動對連續音訊輸入串流執行語音活動偵測 (VAD)。VAD 一律會啟用,且其參數無法設定。

符記數

不支援符記數量。

頻率限制

以下頻率限制適用於此 API:

  • 每個 API 金鑰 3 個並行工作階段
  • 每分鐘 400 萬個符記

WebSockets API 參考資料

Multimodal Live API 是使用 WebSockets 的具狀態 API。本節將進一步說明 WebSockets API。

工作階段

WebSocket 連線會在用戶端和 Gemini 伺服器之間建立工作階段。用戶端啟動新連線後,工作階段可以與伺服器交換訊息,以便執行下列操作:

  • 將文字、音訊或影片傳送至 Gemini 伺服器。
  • 接收 Gemini 伺服器傳送的音訊、文字或函式呼叫要求。

連線後的初始訊息會設定工作階段設定,包括模型、產生參數、系統指示和工具。

請參閱以下設定範例。請注意,SDK 中的名稱大小寫可能會有所不同。您可以參閱這篇文章,瞭解 Python SDK 的設定選項。


{
 
"model": string,
 
"generationConfig": {
   
"candidateCount": integer,
   
"maxOutputTokens": integer,
   
"temperature": number,
   
"topP": number,
   
"topK": integer,
   
"presencePenalty": number,
   
"frequencyPenalty": number,
   
"responseModalities": [string],
   
"speechConfig": object
 
},
 
"systemInstruction": string,
 
"tools": [object]
}

傳送訊息

如要透過 WebSocket 連線交換訊息,用戶端必須透過已開啟的 WebSocket 連線傳送 JSON 物件。JSON 物件必須包含下列物件集合中單一欄位:


{
 
"setup": BidiGenerateContentSetup,
 
"clientContent": BidiGenerateContentClientContent,
 
"realtimeInput": BidiGenerateContentRealtimeInput,
 
"toolResponse": BidiGenerateContentToolResponse
}

支援的用戶端訊息

請參閱下表中支援的用戶端訊息:

訊息 說明
BidiGenerateContentSetup 要在第一則訊息中傳送的工作階段設定
BidiGenerateContentClientContent 從用戶端傳送的目前對話內容增量更新
BidiGenerateContentRealtimeInput 即時音訊或視訊輸入
BidiGenerateContentToolResponse 回應伺服器傳回的 ToolCallMessage

接收訊息

如要接收 Gemini 的訊息,請接聽 WebSocket 的「message」事件,然後根據支援的伺服器訊息定義剖析結果。

請參閱以下資訊:

async with client.aio.live.connect(model='...', config=config) as session:
    await session.send(input='Hello world!', end_of_turn=True)
    async for message in session.receive():
        print(message)

伺服器訊息會包含下列物件集合中單一欄位:


{
 
"setupComplete": BidiGenerateContentSetupComplete,
 
"serverContent": BidiGenerateContentServerContent,
 
"toolCall": BidiGenerateContentToolCall,
 
"toolCallCancellation": BidiGenerateContentToolCallCancellation
}

支援的伺服器訊息

請參閱下表中支援的伺服器訊息:

訊息 說明
BidiGenerateContentSetupComplete 來自用戶端的 BidiGenerateContentSetup 訊息,在設定完成時傳送
BidiGenerateContentServerContent 模型針對用戶端訊息產生的內容
BidiGenerateContentToolCall 要求用戶端執行函式呼叫,並傳回與相符 ID 的回應
BidiGenerateContentToolCallCancellation 當使用者中斷模型輸出作業,導致函式呼叫取消時傳送

訊息和事件

BidiGenerateContentClientContent

從用戶端傳送的目前對話內容增量更新。此處的所有內容都會無條件附加至對話記錄,並用於提示模型產生內容。

這裡的訊息會中斷任何目前的模型產生作業。

欄位
turns[]

Content

選用設定。附加至與模型目前對話的內容。

對於單次查詢,這會是單一例項。對於多輪查詢,這是重複欄位,其中包含對話記錄和最新要求。

turn_complete

bool

選用設定。如果為 true,表示伺服器內容產生作業應從目前累積的提示開始。否則,伺服器會等待其他訊息,然後才開始產生。

BidiGenerateContentRealtimeInput

即時傳送的使用者輸入內容。

BidiGenerateContentClientContent 相比,這個選項具有以下幾個差異:

  • 可持續傳送,不會中斷模型產生作業。
  • 如果需要在 BidiGenerateContentClientContentBidiGenerateContentRealtimeInput 之間交錯混合資料,伺服器會嘗試最佳化,以便取得最佳回應,但不保證一定能成功。
  • 不需明確指定輪到誰說話,而是由使用者活動 (例如說話結束) 決定。
  • 即使在回合結束前,系統也會逐漸處理資料,以便快速開始處理模型的回應。
  • 系統一律會假設這是使用者的輸入內容 (無法用於填入對話記錄)。可持續傳送,不會中斷。模型會自動偵測使用者語音的開頭和結尾,並視情況開始或停止串流回應。資料會在傳送時逐漸處理,盡量減少延遲時間。
欄位
media_chunks[]

Blob

選用設定。媒體輸入內容的內嵌位元組資料。

BidiGenerateContentServerContent

模型為了回應用戶端訊息而產生的伺服器增量更新。

系統會盡快產生內容,但不會即時產生。用戶端可以選擇緩衝並即時播放。

欄位
turn_complete

bool

僅供輸出。如果為 true,表示模型已完成產生作業。系統只會在回應其他用戶端訊息時開始產生內容。可與 content 搭配使用,表示 content 是回合中的最後一個。

interrupted

bool

僅供輸出。如果為 true,表示用戶端訊息已中斷目前的模型產生作業。如果用戶端正在即時播放內容,這就是停止並清空目前播放佇列的最佳訊號。

grounding_metadata

GroundingMetadata

僅供輸出。為產生的內容建立基礎中繼資料。

model_turn

Content

僅供輸出。模型在與使用者進行目前對話時產生的內容。

BidiGenerateContentSetup

要在第一個 (也是唯一的) 用戶端訊息中傳送的訊息。包含在串流工作階段期間套用的設定。

用戶端應等待 BidiGenerateContentSetupComplete 訊息,再傳送任何其他訊息。

欄位
model

string

必要欄位。模型的資源名稱。這會做為模型要使用的 ID。

格式:models/{model}

generation_config

GenerationConfig

選用設定。產生設定。

系統不支援下列欄位:

  • responseLogprobs
  • responseMimeType
  • logprobs
  • responseSchema
  • stopSequence
  • routingConfig
  • audioTimestamp
system_instruction

Content

選用設定。使用者為模型提供系統指示。

注意:部分只能使用文字。每個部分的內容會放在不同的段落中。

tools[]

Tool

選用設定。模型可能用來產生下一個回應的 Tools 清單。

Tool 是一小段程式碼,可讓系統與外部系統互動,執行模型知識和範圍以外的動作或一組動作。

BidiGenerateContentSetupComplete

這個類型沒有任何欄位。

回覆用戶端傳送的 BidiGenerateContentSetup 訊息。

BidiGenerateContentToolCall

要求用戶端執行函式呼叫,並傳回與相符 id 的回應。

欄位
function_calls[]

FunctionCall

僅供輸出。要執行的函式呼叫。

BidiGenerateContentToolCallCancellation

通知用戶端,先前發出的 ToolCallMessage 含有指定的 id,因此不應執行,應予以取消。如果這些工具呼叫有副作用,用戶端可能會嘗試撤銷工具呼叫。只有在用戶端中斷伺服器轉換時,才會出現這則訊息。

欄位
ids[]

string

僅供輸出。要取消的工具呼叫 ID。

BidiGenerateContentToolResponse

用戶端針對從伺服器收到的 ToolCall 產生回應。個別 FunctionResponse 物件會透過 id 欄位與相應的 FunctionCall 物件配對。

請注意,在單向和伺服器串流 GenerateContent API 中,函式呼叫會透過交換 Content 部分,而在雙向 GenerateContent API 中,函式呼叫會透過這些專用訊息集進行。

欄位
function_responses[]

FunctionResponse

選用設定。函式呼叫的回應。

進一步瞭解常見類型

如要進一步瞭解常用的 API 資源類型 BlobContentFunctionCallFunctionResponseGenerationConfigGroundingMetadataTool,請參閱產生內容

第三方整合

如要部署網站和行動應用程式,您可以參考以下選項: