Gemini Live API を使用すると、Gemini モデルとのリアルタイムの双方向インタラクションが可能になります。音声、動画、テキストの入力とネイティブ音声出力をサポートしています。このガイドでは、サーバーで Google GenAI SDK を使用して API と統合する方法について説明します。
概要
Gemini Live API は、リアルタイム通信に WebSocket を使用します。google-genai SDK は、これらの接続を管理するための高レベルの非同期インターフェースを提供します。
クラウド セキュリティの主な概念には、
- セッション: モデルへの永続的な接続。
- Config: モダリティ(音声/テキスト)、音声、システム指示を設定します。
- リアルタイム入力: 音声フレームと動画フレームを 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?'
});
音声を送信する
音声は RAW PCM データ(RAW 16 ビット PCM 音声、16kHz、リトル エンディアン)として送信する必要があります。
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 });
}
次のステップ
- 音声検出やネイティブ音声機能など、主な機能と構成については、Live API の機能ガイドをご覧ください。
- ツールの使用ガイドを読んで、Live API をツールや関数呼び出しと統合する方法を確認します。
- 長時間にわたる会話を管理するには、セッション管理ガイドをご覧ください。
- クライアントとサーバー間のアプリケーションで安全な認証を行うには、エフェメラル トークンのガイドをご覧ください。
- 基盤となる WebSockets API について詳しくは、WebSockets API リファレンスをご覧ください。