Google Gemini Live Voice
GeminiLiveVoice 類別使用 Google Gemini Live API 提供即時語音互動功能。它支援雙向音訊串流、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」的直接連結
在執行階段更新工作階段設定。可修改語音設定與語音選擇,也能修改其他執行階段設定。
config:
回傳:Promise<void>
addTools()「addtools」的直接連結
將一組 Tools 加入 Voice 執行個體。Tools 可讓模型在對話期間執行其他動作。GeminiLiveVoice 加入 Agent 時,為 Agent 設定的任何 Tools 都會自動提供給 Voice 介面。
tools:
回傳:void
addInstructions()「addinstructions」的直接連結
新增或更新模型的系統指示。
instructions?:
回傳:void
answer()「answer」的直接連結
觸發模型回應。此方法主要在與 Agent 整合時由內部使用。
options?:
回傳:Promise<void>
getSpeakers()「getspeakers」的直接連結
回傳 Gemini Live API 可用的語音清單。
回傳:Promise<Array<{ voiceId: string; description?: string }>>
disconnect()「disconnect」的直接連結
中斷 Gemini Live 工作階段的連線並清理資源。此非同步方法會妥善處理清理作業。
回傳:Promise<void>
close()「close」的直接連結
disconnect() 的同步包裝函式。內部呼叫 disconnect(),但不等待其完成。
回傳:void
on()「on」的直接連結
註冊 Voice 事件的事件監聽器。
event:
callback:
回傳:void
off()「off」的直接連結
移除先前註冊的事件監聽器。
event:
callback:
回傳:void
事件「事件」的直接連結
GeminiLiveVoice 類別會發出下列事件:
speaker:
speaking:
writing:
output_audio_transcription 通道驅動,而不是 modelTurn.parts.text。thinking:
modelTurn.parts.text 的模型思考鏈/推理文字。回呼會收到 { text: string }。此事件不會在非原生音訊模型上觸發;在這類模型上,modelTurn.parts.text 是語音回應,會改以 writing 發出。session:
turnComplete:
toolCall:
usage:
error:
interrupt:
原生音訊行為「原生音訊行為」的直接連結
原生音訊 Gemini Live 模型(ID 包含 native-audio 的任何模型,例如 gemini-2.5-flash-native-audio-preview-12-2025)會將文字輸出分到兩個通道:
- 模型說出的回覆會以音訊加上
output_audio_transcription轉錄提供,並以role: 'assistant'的writing呈現。 - 模型的內部推理會以
modelTurn.parts.text提供,並以thinking呈現。
非原生音訊模型沒有 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
可用語音「可用語音」的直接連結
可使用下列語音選項:
Puck(預設):自然對話、友善Charon:低沉、權威Kore:中性、專業Fenrir:溫暖、平易近人
驗證方法「驗證方法」的直接連結
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 使用 WebSockets 進行即時通訊
- 輸入音訊會以 16kHz PCM16 處理,輸出音訊則以 24kHz PCM16 處理
- Voice 執行個體必須先透過
connect()連線,才能使用其他方法 - 完成後一律呼叫
close(),以正確清理資源 - Vertex AI 驗證需要適當的 IAM 權限(
aiplatform.user角色) - 工作階段恢復功能可從網路中斷中復原
- 此 API 支援使用文字與音訊進行即時互動