Gemini Live API 支援與 Gemini 模型進行即時雙向互動,可輸入音訊、影片和文字,並輸出原生音訊。本指南說明如何在伺服器上使用 Google GenAI SDK,與 API 整合。
總覽
Gemini Live API 使用 WebSocket 進行即時通訊。google-genai SDK 提供高層級的非同步介面,可管理這些連線。
重要概念:
- 工作階段:與模型建立的持續連線。
- 設定:設定模式 (音訊/文字)、語音和系統指令。
- 即時輸入:以 Blob 形式傳送音訊和視訊影格。
連線至 Live API
使用 API 金鑰啟動 Live API 工作階段:
Python
import asyncio
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
model = "gemini-2.5-flash-native-audio-preview-12-2025"
config = {"response_modalities": ["AUDIO"]}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
print("Session started")
# Send content...
if __name__ == "__main__":
asyncio.run(main())
JavaScript
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY"});
const model = 'gemini-2.5-flash-native-audio-preview-12-2025';
const config = { responseModalities: [Modality.AUDIO] };
async function main() {
const session = await ai.live.connect({
model: model,
callbacks: {
onopen: function () {
console.debug('Opened');
},
onmessage: function (message) {
console.debug(message);
},
onerror: function (e) {
console.debug('Error:', e.message);
},
onclose: function (e) {
console.debug('Close:', e.reason);
},
},
config: config,
});
console.debug("Session started");
// Send content...
session.close();
}
main();
正在傳送文字內容
您可以使用 send_realtime_input (Python) 或 sendRealtimeInput (JavaScript) 傳送文字。
Python
await session.send_realtime_input(text="Hello, how are you?")
JavaScript
session.sendRealtimeInput({
text: 'Hello, how are you?'
});
正在傳送音訊
音訊必須以原始 PCM 資料 (原始 16 位元 PCM 音訊、16 kHz、小端序) 傳送。
Python
# Assuming 'chunk' is your raw PCM audio bytes
await session.send_realtime_input(
audio=types.Blob(
data=chunk,
mime_type="audio/pcm;rate=16000"
)
)
JavaScript
// Assuming 'chunk' is a Buffer of raw PCM audio
session.sendRealtimeInput({
audio: {
data: chunk.toString('base64'),
mimeType: 'audio/pcm;rate=16000'
}
});
如要瞭解如何從用戶端裝置 (例如瀏覽器) 取得音訊,請參閱 GitHub 上的端對端範例。
正在傳送影片
影片影格會以個別圖片的形式傳送 (例如 JPEG 或 PNG) 圖片,且畫面更新率不得超過每秒 1 個影格。
Python
# Assuming 'frame' is your JPEG-encoded image bytes
await session.send_realtime_input(
video=types.Blob(
data=frame,
mime_type="image/jpeg"
)
)
JavaScript
// Assuming 'frame' is a Buffer of JPEG-encoded image data
session.sendRealtimeInput({
video: {
data: frame.toString('base64'),
mimeType: 'image/jpeg'
}
});
如需如何從用戶端裝置 (例如瀏覽器) 取得影片的範例,請參閱 GitHub 上的端對端範例。
接收音訊
模型會以資料區塊的形式傳回音訊回覆。
Python
async for response in session.receive():
if response.server_content and response.server_content.model_turn:
for part in response.server_content.model_turn.parts:
if part.inline_data:
audio_data = part.inline_data.data
# Process or play the audio data
JavaScript
// Inside the onmessage callback
const content = response.serverContent;
if (content?.modelTurn?.parts) {
for (const part of content.modelTurn.parts) {
if (part.inlineData) {
const audioData = part.inlineData.data;
// Process or play audioData (base64 encoded string)
}
}
}
如要瞭解如何在伺服器上接收音訊,以及在瀏覽器中播放音訊,請參閱 GitHub 上的範例應用程式。
正在接收文字內容
伺服器內容會提供使用者輸入內容和模型輸出內容的轉錄稿。
Python
async for response in session.receive():
content = response.server_content
if content:
if content.input_transcription:
print(f"User: {content.input_transcription.text}")
if content.output_transcription:
print(f"Gemini: {content.output_transcription.text}")
JavaScript
// Inside the onmessage callback
const content = response.serverContent;
if (content?.inputTranscription) {
console.log('User:', content.inputTranscription.text);
}
if (content?.outputTranscription) {
console.log('Gemini:', content.outputTranscription.text);
}
處理工具呼叫
這個 API 支援工具呼叫 (函式呼叫)。模型要求呼叫工具時,您必須執行函式並傳回回應。
Python
async for response in session.receive():
if response.tool_call:
function_responses = []
for fc in response.tool_call.function_calls:
# 1. Execute the function locally
result = my_tool_function(**fc.args)
# 2. Prepare the response
function_responses.append(types.FunctionResponse(
name=fc.name,
id=fc.id,
response={"result": result}
))
# 3. Send the tool response back to the session
await session.send_tool_response(function_responses=function_responses)
JavaScript
// Inside the onmessage callback
if (response.toolCall) {
const functionResponses = [];
for (const fc of response.toolCall.functionCalls) {
const result = myToolFunction(fc.args);
functionResponses.push({
name: fc.name,
id: fc.id,
response: { result }
});
}
session.sendToolResponse({ functionResponses });
}