> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Google Gemini Live 語音 GeminiLiveVoice 類別使用 Google Gemini Live API 提供實時語音互動功能。它支援雙向音訊串流、Tool 調用、工作階段管理,以及標準 Google API 和 Vertex AI 驗證方式。 ## 使用範例 ```typescript 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`): 用於實時語音互動的模型 ID。 (Default: `'gemini-2.0-flash-exp'`) **speaker** (`GeminiVoiceName`): 語音合成的預設語音 ID。 (Default: `'Puck'`) **vertexAI** (`boolean`): 使用 Vertex AI 而非 Gemini API 進行驗證。 (Default: `false`) **project** (`string`): Google Cloud 項目 ID(使用 Vertex AI 時必須提供)。 **location** (`string`): Vertex AI 使用的 Google Cloud 區域。 (Default: `'us-central1'`) **serviceAccountKeyFile** (`string`): 用於 Vertex AI 驗證的服務帳戶 JSON 金鑰檔案路徑。 **serviceAccountEmail** (`string`): 用於模擬身分的服務帳戶電郵地址(可取代金鑰檔案)。 **instructions** (`string`): 模型的系統指示。 **sessionConfig** (`GeminiSessionConfig`): 工作階段設定,包括中斷及上下文設定。 **sessionConfig.interrupts** (`object`): 中斷處理設定。 **sessionConfig.interrupts.enabled** (`boolean`): 啟用中斷處理。 **sessionConfig.interrupts.allowUserInterruption** (`boolean`): 允許用戶中斷模型回應。 **sessionConfig.contextCompression** (`boolean`): 啟用自動上下文壓縮。 **debug** (`boolean`): 啟用除錯記錄以協助疑難排解。 (Default: `false`) ## 方法 ### `connect()` 建立與 Gemini Live API 的連線。使用 speak、listen 或 send 方法前必須先調用此方法。 **requestContext** (`object`): 連線所用的選填請求上下文。 **returns** (`Promise`): 連線建立後解析的 Promise。 ### `speak()` 將文字轉換成語音並傳送至模型。可接受字串或可讀串流作為輸入。 **input** (`string | NodeJS.ReadableStream`): 要轉換成語音的文字或文字串流。 **options** (`GeminiLiveVoiceOptions`): 選填的語音設定。 **options.speaker** (`GeminiVoiceName`): 此語音請求使用的語音 ID。 **options.languageCode** (`string`): 回應的語言代碼。 **options.responseModalities** (`('AUDIO' | 'TEXT')[]`): 要從模型接收的回應模態。 傳回:`Promise`(回應透過 `speaker` 及 `writing` 事件發出) ### `sendContext()` 將對話記錄傳送至即時工作階段,而不觸發模型回應。可在全新連線時使用此方法加入先前的對話輪次(例如來自 Mastra Memory),讓模型在用戶說話前取得上下文。 ```typescript 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),部分較舊的模型則只接受用戶角色的輪次。 **options** (`object`): 選填設定。 **options.turnComplete** (`boolean`): 是否將此輪次標記為完成並觸發模型回應。 傳回:`Promise` ### `listen()` 處理用於語音辨識的音訊輸入。此方法接收音訊資料的可讀串流,並傳回轉錄文字。 **audioStream** (`NodeJS.ReadableStream`): 要轉錄的音訊串流。 **options** (`GeminiLiveVoiceOptions`): 選填的聆聽設定。 傳回:`Promise` — 轉錄文字 ### `send()` 將音訊資料實時串流至 Gemini 服務,適用於即時咪高峰輸入等持續音訊串流情境。 **audioData** (`NodeJS.ReadableStream | Int16Array`): 要傳送至服務的音訊串流或緩衝區。 傳回:`Promise` ### `updateSessionConfig()` 在執行期間更新工作階段設定。此方法可修改語音設定及講者選擇,也可修改其他執行期間設定。 **config** (`Partial`): 要套用的設定更新。 傳回:`Promise` ### `addTools()` 向語音實例加入一組 Tool。Tool 讓模型可在對話期間執行其他操作。將 GeminiLiveVoice 加入 Agent 後,為該 Agent 設定的所有 Tool 均會自動供語音介面使用。 **tools** (`ToolsInput`): 要配備的 Tool 設定。 傳回:`void` ### `addInstructions()` 加入或更新模型的系統指示。 **instructions** (`string`): 要設定的系統指示。 傳回:`void` ### `answer()` 觸發模型回應。此方法主要在與 Agent 整合時於內部使用。 **options** (`Record`): 回答請求的選填參數。 傳回:`Promise` ### `getSpeakers()` 傳回 Gemini Live API 可用的語音講者清單。 傳回:`Promise>` ### disconnect() 中斷 Gemini Live 工作階段的連線並清理資源。這是妥善處理清理工作的非同步方法。 傳回:`Promise` ### `close()` disconnect() 的同步包裝函數。此方法會在內部調用 `disconnect()`,但不會等待其完成。 傳回:`void` ### `on()` 為語音事件註冊事件監聽器。 **event** (`string`): 要監聽的事件名稱。 **callback** (`Function`): 事件發生時要調用的函數。 傳回:`void` ### `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`): 連同 token 用量資料一併發出。回呼會接收 { 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'`)會在設定 payload 中自動啟用,毋須額外設定。 ## 可用模型 可使用以下 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(開發) 最簡單的方式是使用來自 [Google AI Studio](https://makersuite.google.com/app/apikey) 的 API 金鑰: ```typescript const voice = new GeminiLiveVoice({ apiKey: 'your-api-key', // Required for Gemini API model: 'gemini-2.0-flash-exp', }) ``` ### Vertex AI(生產環境) 在生產環境中配合 OAuth 驗證及 Google Cloud Platform 使用: ```typescript // 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 支援恢復工作階段,以處理網絡中斷: ```typescript 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 調用 讓模型可在對話期間調用函數: ```typescript 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 處理 - 使用其他方法前,必須先使用 `connect()` 連接語音實例 - 完成後務必調用 `close()`,以妥善清理資源 - Vertex AI 驗證需要適當的 IAM 權限(`aiplatform.user` 角色) - 恢復工作階段功能可從網絡中斷中復原 - API 支援文字及音訊的實時互動