跳至主要內容

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?:

string
用於 Gemini API 驗證的 Google API 金鑰。除非使用 Vertex AI,否則為必填。

model?:

GeminiVoiceModel
= 'gemini-2.0-flash-exp'
即時語音互動使用的模型 ID。

speaker?:

GeminiVoiceName
= 'Puck'
語音合成的預設語音 ID。

vertexAI?:

boolean
= false
使用 Vertex AI,而非 Gemini API 進行驗證。

project?:

string
Google Cloud 專案 ID(Vertex AI 必填)。

location?:

string
= 'us-central1'
Vertex AI 的 Google Cloud 區域。

serviceAccountKeyFile?:

string
用於 Vertex AI 驗證的服務帳戶 JSON 金鑰檔路徑。

serviceAccountEmail?:

string
用於模擬身分的服務帳戶電子郵件(可取代金鑰檔)。

instructions?:

string
提供給模型的系統指示。

sessionConfig?:

GeminiSessionConfig
包含中斷與內容設定的工作階段設定。
GeminiSessionConfig

interrupts?:

object
中斷處理設定。

interrupts.enabled?:

boolean
啟用中斷處理。

interrupts.allowUserInterruption?:

boolean
允許使用者中斷模型回應。

contextCompression?:

boolean
啟用自動內容壓縮。

debug?:

boolean
= false
啟用偵錯記錄以排解問題。

方法
「方法」的直接連結

connect()
「connect」的直接連結

建立與 Gemini Live API 的連線。必須先呼叫此方法,才能使用 speak、listen 或 send 方法。

requestContext?:

object
連線的選用請求內容。

returns:

Promise<void>
連線建立後解析的 Promise。

speak()
「speak」的直接連結

將文字轉換為語音並傳送至模型。輸入可接受字串或可讀資料流。

input:

string | NodeJS.ReadableStream
要轉換為語音的文字或文字資料流。

options?:

GeminiLiveVoiceOptions
選用的語音設定。
GeminiLiveVoiceOptions

speaker?:

GeminiVoiceName
此語音請求使用的語音 ID。

languageCode?:

string
回應的語言程式碼。

responseModalities?:

('AUDIO' | 'TEXT')[]
要從模型接收的回應模態。

回傳:Promise<void>(回應會透過 speakerwriting 事件發出)

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:

IncrementalTurn[]
要預先載入工作階段的先前對話輪次。每個輪次都包含 role("user" 或 "assistant")與 content 字串。較新的模型(例如 gemini-2.5-flash-native-audio-preview-12-2025)支援兩種角色,部分舊模型只接受 user 角色的輪次。

options?:

object
選用設定。
object

turnComplete?:

boolean
是否將對話輪次標記為完成並觸發模型回應。

回傳:Promise<void>

listen()
「listen」的直接連結

處理用於語音辨識的音訊輸入。接受音訊資料的可讀資料流,並回傳轉錄文字。

audioStream:

NodeJS.ReadableStream
要轉錄的音訊資料流。

options?:

GeminiLiveVoiceOptions
選用的聆聽設定。

回傳:Promise<string> — 轉錄文字

send()
「send」的直接連結

將音訊資料即時串流傳送至 Gemini 服務,適用於即時麥克風輸入等持續音訊串流情境。

audioData:

NodeJS.ReadableStream | Int16Array
要傳送至服務的音訊資料流或緩衝區。

回傳:Promise<void>

updateSessionConfig()
「updatesessionconfig」的直接連結

在執行階段更新工作階段設定。可修改語音設定與語音選擇,也能修改其他執行階段設定。

config:

Partial<GeminiLiveVoiceConfig>
要套用的設定更新。

回傳:Promise<void>

addTools()
「addtools」的直接連結

將一組 Tools 加入 Voice 執行個體。Tools 可讓模型在對話期間執行其他動作。GeminiLiveVoice 加入 Agent 時,為 Agent 設定的任何 Tools 都會自動提供給 Voice 介面。

tools:

ToolsInput
要配備的 Tools 設定。

回傳:void

addInstructions()
「addinstructions」的直接連結

新增或更新模型的系統指示。

instructions?:

string
要設定的系統指示。

回傳:void

answer()
「answer」的直接連結

觸發模型回應。此方法主要在與 Agent 整合時由內部使用。

options?:

Record<string, unknown>
回答請求的選用參數。

回傳: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:

string
要監聽的事件名稱。

callback:

Function
事件發生時要呼叫的函式。

回傳:void

off()
「off」的直接連結

移除先前註冊的事件監聽器。

event:

string
要停止監聽的事件名稱。

callback:

Function
要移除的特定回呼函式。

回傳:void

事件
「事件」的直接連結

GeminiLiveVoice 類別會發出下列事件:

speaker:

event
收到模型的音訊資料時發出。回呼會收到 NodeJS.ReadableStream。

speaking:

event
連同音訊中繼資料發出。回呼會收到 { audioData?: Int16Array, sampleRate?: number }。

writing:

event
轉錄文字可用時發出。回呼會收到 { text: string, role: 'assistant' | 'user' }。在原生音訊模型上,助理轉錄由伺服器的 output_audio_transcription 通道驅動,而不是 modelTurn.parts.text

thinking:

event
在原生音訊模型上發出,包含來自 modelTurn.parts.text 的模型思考鏈/推理文字。回呼會收到 { text: string }。此事件不會在非原生音訊模型上觸發;在這類模型上,modelTurn.parts.text 是語音回應,會改以 writing 發出。

session:

event
工作階段狀態變更時發出。回呼會收到 { state: 'connecting' | 'connected' | 'disconnected' | 'disconnecting' | 'updated', config?: object }。

turnComplete:

event
對話輪次完成時發出。回呼會收到 { timestamp: number }。

toolCall:

event
模型請求呼叫 Tool 時發出。回呼會收到 { name: string, args: object, id: string }。

usage:

event
連同權杖用量資訊發出。回呼會收到 { inputTokens: number, outputTokens: number, totalTokens: number, modality: string }。

error:

event
發生錯誤時發出。回呼會收到 { message: string, code?: string, details?: unknown }。

interrupt:

event
當使用者在模型回應期間開始說話而插話時發出。伺服器會取消目前對話輪次後續的所有音訊。回呼會收到 { type: 'user', timestamp: number }。

原生音訊行為
「原生音訊行為」的直接連結

原生音訊 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-generation
  • gemini-2.0-flash-live-001
  • gemini-live-2.5-flash-preview-native-audio
  • gemini-2.5-flash-exp-native-audio-thinking-dialog
  • gemini-live-2.5-flash-preview
  • gemini-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 支援使用文字與音訊進行即時互動