Google Gemini Live Voice
GeminiLiveVoice クラスは、Google Gemini Live API を使用したリアルタイム Voice 対話機能を提供します。双方向音声ストリーミング、Tool 呼び出し、セッション管理、標準の Google API と Vertex AI の両認証方式をサポートします。
使用例使用例への直接リンク
import { GeminiLiveVoice } from '@mastra/voice-google-gemini-live'
import { playAudio, getMicrophoneStream } from '@mastra/node-audio'
// Initialize with Gemini API (using API key)
const voice = new GeminiLiveVoice({
apiKey: process.env.GOOGLE_API_KEY, // Required for Gemini API
model: 'gemini-2.0-flash-exp',
speaker: 'Puck', // Default voice
debug: true,
})
// Or initialize with Vertex AI (using OAuth)
const voiceWithVertexAI = new GeminiLiveVoice({
vertexAI: true,
project: 'your-gcp-project',
location: 'us-central1',
serviceAccountKeyFile: '/path/to/service-account.json',
model: 'gemini-2.0-flash-exp',
speaker: 'Puck',
})
// Or use the VoiceConfig pattern (recommended for consistency with other providers)
const voiceWithConfig = new GeminiLiveVoice({
speechModel: {
name: 'gemini-2.0-flash-exp',
apiKey: process.env.GOOGLE_API_KEY,
},
speaker: 'Puck',
realtimeConfig: {
model: 'gemini-2.0-flash-exp',
apiKey: process.env.GOOGLE_API_KEY,
options: {
debug: true,
sessionConfig: {
interrupts: { enabled: true },
},
},
},
})
// Establish connection (required before using other methods)
await voice.connect()
// Set up event listeners
voice.on('speaker', audioStream => {
// Handle audio stream (NodeJS.ReadableStream)
playAudio(audioStream)
})
voice.on('writing', ({ text, role }) => {
// Handle transcribed text
console.log(`${role}: ${text}`)
})
voice.on('turnComplete', ({ timestamp }) => {
// Handle turn completion
console.log('Turn completed at:', timestamp)
})
// Convert text to speech
await voice.speak('Hello, how can I help you today?', {
speaker: 'Charon', // Override default voice
responseModalities: ['AUDIO', 'TEXT'],
})
// Process audio input
const microphoneStream = getMicrophoneStream()
await voice.send(microphoneStream)
// Update session configuration
await voice.updateSessionConfig({
speaker: 'Kore',
instructions: 'Be more concise in your responses',
})
// When done, disconnect
await voice.disconnect()
// Or use the synchronous wrapper
voice.close()
設定設定への直接リンク
コンストラクターオプションコンストラクターオプションへの直接リンク
apiKey?:
model?:
speaker?:
vertexAI?:
project?:
location?:
serviceAccountKeyFile?:
serviceAccountEmail?:
instructions?:
sessionConfig?:
interrupts?:
interrupts.enabled?:
interrupts.allowUserInterruption?:
contextCompression?:
debug?:
メソッドメソッドへの直接リンク
connect()connectへの直接リンク
Gemini Live API への接続を確立します。speak、listen、send メソッドを使用する前に呼び出す必要があります。
requestContext?:
returns:
speak()speakへの直接リンク
テキストを音声に変換してモデルに送信します。入力には文字列または読み取り可能なストリームを指定できます。
input:
options?:
speaker?:
languageCode?:
responseModalities?:
戻り値:Promise<void>(応答は speaker および writing イベントで送出されます)
sendContext()sendcontextへの直接リンク
モデルの応答を開始せずに、会話履歴をライブセッションへ送信します。コールド接続時に以前のターン(Mastra Memory から取得したものなど)を追加し、ユーザーが話す前にモデルへコンテキストを与えるために使用します。
await voice.sendContext([
{ role: 'user', content: 'What is the weather?' },
{ role: 'assistant', content: 'It is 72°F in San Francisco.' },
])
// Model stays silent until the user actually speaks.
await voice.send(micStream)
turns:
role("user" または "assistant")と content 文字列があります。新しいモデル(例:gemini-2.5-flash-native-audio-preview-12-2025)は両方のロールをサポートします。一部の古いモデルは user ロールのターンだけを受け付けます。options?:
turnComplete?:
戻り値:Promise<void>
listen()listenへの直接リンク
音声認識用の音声入力を処理します。音声データの読み取り可能なストリームを受け取り、文字起こしテキストを返します。
audioStream:
options?:
戻り値:Promise<string> - 文字起こしされたテキスト
send()sendへの直接リンク
ライブマイク入力など継続的な音声ストリーミングのために、Gemini サービスへ音声データをリアルタイムでストリーミングします。
audioData:
戻り値: Promise<void>
updateSessionConfig()updatesessionconfigへの直接リンク
実行時にセッション設定を更新します。Voice 設定、Speaker の選択、その他の実行時設定を変更できます。
config:
戻り値:Promise<void>
addTools()addtoolsへの直接リンク
Voice インスタンスに一連の Tool を追加します。Tool により、モデルは会話中に追加のアクションを実行できます。GeminiLiveVoice を Agent に追加すると、Agent に設定された Tool が Voice インターフェースで自動的に利用可能になります。
tools:
戻り値:void
addInstructions()addinstructionsへの直接リンク
モデルのシステム指示を追加または更新します。
instructions?:
戻り値: void
answer()answerへの直接リンク
モデルからの応答を開始します。このメソッドは、Agent と統合した際に主に内部で使用されます。
options?:
戻り値: Promise<void>
getSpeakers()getspeakersへの直接リンク
Gemini Live API で使用可能な Voice Speaker の一覧を返します。
戻り値:Promise<Array<{ voiceId: string; description?: string }>>
disconnect()disconnectへの直接リンク
Gemini Live セッションから切断してリソースを解放します。クリーンアップを適切に処理する非同期メソッドです。
戻り値: Promise<void>
close()closeへの直接リンク
disconnect() の同期ラッパーです。内部で disconnect() を await せずに呼び出します。
戻り値: void
on()onへの直接リンク
Voice イベントのイベントリスナーを登録します。
event:
callback:
戻り値: void
off()offへの直接リンク
以前に登録したイベントリスナーを削除します。
event:
callback:
戻り値: void
イベントイベントへの直接リンク
GeminiLiveVoice クラスは次のイベントを送出します。
speaker:
speaking:
writing:
modelTurn.parts.text ではなく、サーバーの output_audio_transcription チャンネルによって提供されます。thinking:
modelTurn.parts.text から取得したモデルの思考連鎖/推論テキストとともに送出されます。コールバックは { text: string } を受け取ります。非 native-audio モデルでは modelTurn.parts.text が発話応答となり、代わりに writing として送出されるため、このイベントは発生しません。session:
turnComplete:
toolCall:
usage:
error:
interrupt:
native-audio の動作native-audio の動作への直接リンク
native-audio Gemini Live モデル(gemini-2.5-flash-native-audio-preview-12-2025 など、ID に native-audio を含むモデル)は、テキスト出力を2つのチャンネルに分けます。
- モデルの発話応答は、音声と
output_audio_transcriptionの文字起こしとして配信され、role: 'assistant'のwritingとして公開されます。 - モデルの内部推論は
modelTurn.parts.textとして配信され、thinkingとして公開されます。
非 native-audio モデルには output_audio_transcription チャンネルがないため、modelTurn.parts.text 自体が発話応答となり、writing として送出されます。thinking イベントは発生しません。
入力の文字起こし、出力の文字起こし、割り込み検出(realtime_input_config.activity_handling = 'START_OF_ACTIVITY_INTERRUPTS')は、セットアップペイロードで自動的に有効になります。追加設定は不要です。
使用可能なモデル使用可能なモデルへの直接リンク
次の Gemini Live モデルを利用できます。
gemini-2.0-flash-exp(デフォルト)gemini-2.0-flash-exp-image-generationgemini-2.0-flash-live-001gemini-live-2.5-flash-preview-native-audiogemini-2.5-flash-exp-native-audio-thinking-dialoggemini-live-2.5-flash-previewgemini-2.6.flash-preview-tts
使用可能な Voice使用可能な Voiceへの直接リンク
次の Voice オプションを利用できます。
Puck(デフォルト):会話的で親しみやすい VoiceCharon:深みがあり威厳のある VoiceKore:ニュートラルでプロフェッショナルな VoiceFenrir:温かく親しみやすい Voice
認証方法認証方法への直接リンク
Gemini API(開発環境)Gemini API(開発環境)への直接リンク
Google AI Studio の API キーを使用する最も簡単な方法です。
const voice = new GeminiLiveVoice({
apiKey: 'your-api-key', // Required for Gemini API
model: 'gemini-2.0-flash-exp',
})
Vertex AI(本番環境)Vertex AI(本番環境)への直接リンク
OAuth 認証と Google Cloud Platform を使用する本番環境向けの方法です。
// Using service account key file
const voice = new GeminiLiveVoice({
vertexAI: true,
project: 'your-gcp-project',
location: 'us-central1',
serviceAccountKeyFile: '/path/to/service-account.json',
})
// Using Application Default Credentials
const voice = new GeminiLiveVoice({
vertexAI: true,
project: 'your-gcp-project',
location: 'us-central1',
})
// Using service account impersonation
const voice = new GeminiLiveVoice({
vertexAI: true,
project: 'your-gcp-project',
location: 'us-central1',
serviceAccountEmail: 'service-account@project.iam.gserviceaccount.com',
})
高度な機能高度な機能への直接リンク
セッション管理セッション管理への直接リンク
Gemini Live API は、ネットワーク中断に対応するセッション再開をサポートします。
voice.on('sessionHandle', ({ handle, expiresAt }) => {
// Store session handle for resumption
saveSessionHandle(handle, expiresAt)
})
// Resume a previous session
const voice = new GeminiLiveVoice({
sessionConfig: {
enableResumption: true,
maxDuration: '2h',
},
})
Tool 呼び出しTool 呼び出しへの直接リンク
会話中にモデルが関数を呼び出せるようにします。
import { z } from 'zod'
voice.addTools({
weather: {
description: 'Get weather information',
parameters: z.object({
location: z.string(),
}),
execute: async ({ location }) => {
const weather = await getWeather(location)
return weather
},
},
})
voice.on('toolCall', ({ name, args, id }) => {
console.log(`Tool called: ${name} with args:`, args)
})
注意事項注意事項への直接リンク
- Gemini Live API はリアルタイム通信に WebSocket を使用します
- 音声は入力では 16 kHz PCM16、出力では 24 kHz PCM16 として処理されます
- ほかのメソッドを使用する前に、Voice インスタンスを
connect()で接続する必要があります - リソースを適切に解放するため、使用後は必ず
close()を呼び出してください - Vertex AI 認証には適切な IAM 権限(
aiplatform.userロール)が必要です - セッション再開により、ネットワーク中断から復旧できます
- API はテキストと音声によるリアルタイム対話をサポートします