Live API 可讓您與 Gemini 進行低延遲的雙向語音/視訊互動。您可以使用 Live API,為使用者提供自然流暢的對話體驗,並讓使用者透過語音指令中斷模型的回覆。模型可處理文字、音訊和影片輸入內容,並提供文字和音訊輸出內容。
您可以在 Google AI Studio 中試用 Live API。
使用 Live API
本節說明如何搭配使用 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-live-001"
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-live-001"
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)
# Un-comment this code 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())
音訊格式
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"],
}
逐步更新內容
使用遞增更新功能傳送文字輸入內容、建立工作階段背景資訊或還原工作階段背景資訊。針對短時間的內容,您可以傳送逐向互動,以代表確切的事件順序:
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
}
}
對於較長的背景資訊,建議您提供單一訊息摘要,以便釋出脈絡窗口,供後續互動使用。
變更語音
Live API 支援 Puck、Charon、Kore、Fenrir、Aoede、Leda、Orus 和 Zephyr 等語音。
如要指定語音,請在 speechConfig
物件中設定語音名稱,做為工作階段設定的一部分:
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"
}
}
}
使用函式呼叫
您可以使用 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
設定語音活動偵測 (VAD)
根據預設,模型會自動對連續音訊輸入串流執行語音活動偵測 (VAD)。您可以使用設定配置的 realtimeInputConfig.automaticActivityDetection
欄位設定 VAD。
如果音訊串流暫停超過一秒 (例如使用者關閉麥克風),就應傳送 audioStreamEnd
事件,以便清除任何已快取的音訊。用戶端隨時可以恢復傳送音訊資料。
或者,您也可以在設定訊息中將 realtimeInputConfig.automaticActivityDetection.disabled
設為 true
,停用自動語音偵測功能。在這個設定中,用戶端負責偵測使用者的語音,並在適當時間傳送 activityStart
和 activityEnd
訊息。這個設定不會傳送 audioStreamEnd
。相反地,任何中斷串流的情況都會標示為 activityEnd
訊息。
這項功能的 SDK 支援功能將於未來幾週內推出。
取得符記數
您可以在傳回的伺服器訊息的 usageMetadata 欄位中,找到已使用的符記總數。
這項功能的 SDK 支援功能將於未來幾週內推出。
設定工作階段恢復功能
雖然工作階段持續時間有限,您可以設定設定配置的 sessionResumption 欄位。
傳遞這項設定可啟用工作階段恢復支援功能,並讓伺服器傳送 SessionResumptionUpdate 訊息,這可用於恢復工作階段,方法是將上一個恢復符記傳遞為後續連線的 SessionResumptionConfig.handle
。
在工作階段中斷前收到訊息
伺服器會傳送「GoAway」GoAway訊息,表示目前的連線即將終止。這則訊息包含 timeLeft,可顯示剩餘時間,並讓您在連線以「已中止」狀態終止前採取進一步行動。
產生完成後收到訊息
伺服器會傳送 generationComplete 訊息,表示模型已完成產生回應。
啟用內容視窗壓縮功能
如要啟用較長的工作階段,並避免連線突然中斷,您可以設定設定配置的 contextWindowCompression 欄位,啟用內容視窗壓縮功能。
在 ContextWindowCompressionConfig 中,您可以設定滑動視窗機制和觸發壓縮功能的符記數。
這項功能的 SDK 支援功能將於未來幾週內推出。
變更媒體解析度
您可以在工作階段設定中設定 mediaResolution
欄位,藉此指定輸入媒體的媒體解析度。
這項功能的 SDK 支援功能將於未來幾週內推出。
限制
規劃專案時,請考量 Live API 和 Gemini 2.0 的下列限制。
用戶端驗證
Live API 只提供伺服器對伺服器驗證,不建議直接用於用戶端。用戶端輸入內容應透過中介應用程式伺服器進行轉送,以便透過 Live API 進行安全驗證。
工作階段持續時間上限
音訊工作階段持續時間上限為 15 分鐘,音訊和視訊工作階段則上限為 2 分鐘。如果工作階段時間長度超過限制,連線就會終止。
模型也受限於脈絡大小。與視訊和音訊串流一併傳送大量內容,可能會導致工作階段提早終止。
脈絡窗口
工作階段的脈絡窗口限制為 32k 個符號。
第三方整合
如要部署網站和行動應用程式,您可以參考以下選項: