xAI Realtime voice
XAIRealtimeVoice 類別透過 xAI Grok Voice Agent API 提供即時語音互動功能。它實作 Mastra 的 MastraVoice 即時合約,並支援雙向音訊串流、文字輪次、伺服器 VAD、xAI 語音、函式 Tool,以及 xAI 伺服器端 Tool。
用法範例「用法範例」的直接連結
import { Agent } from '@mastra/core/agent'
import { getMicrophoneStream, playAudio } from '@mastra/node-audio'
import { XAIRealtimeVoice } from '@mastra/voice-xai-realtime'
const voice = new XAIRealtimeVoice({
apiKey: process.env.XAI_API_KEY,
model: 'grok-voice-think-fast-1.0',
speaker: 'eve',
instructions: 'You are a concise voice assistant.',
turnDetection: { type: 'server_vad' },
})
const agent = new Agent({
id: 'voice-agent',
name: 'Voice Agent',
instructions: 'You are a helpful voice assistant.',
model: 'xai/grok-4.3',
voice,
})
await agent.voice.connect()
agent.voice.on('speaker', audioStream => {
playAudio(audioStream)
})
agent.voice.on('writing', ({ text, role }) => {
console.log(`${role}: ${text}`)
})
await agent.voice.speak('How can I help you today?')
const microphoneStream = getMicrophoneStream()
await agent.voice.send(microphoneStream)
agent.voice.close()
設定「設定」的直接連結
建構函式選項「建構函式選項」的直接連結
apiKey?:
ephemeralToken?:
model?:
speaker?:
instructions?:
turnDetection?:
audio?:
serverTools?:
session?:
url?:
debug?:
VoiceConfig 模式「VoiceConfig 模式」的直接連結
你也可以使用 Mastra 的共用語音設定結構:
const voice = new XAIRealtimeVoice({
speaker: 'ara',
realtimeConfig: {
model: 'grok-voice-think-fast-1.0',
apiKey: process.env.XAI_API_KEY,
options: {
instructions: 'Answer briefly.',
turnDetection: { type: 'server_vad', threshold: 0.85 },
},
},
})
驗證「驗證」的直接連結
伺服器端應用程式請使用 apiKey 或 XAI_API_KEY。此 Provider 專為 Node.js 伺服器端執行環境而設計。若伺服器已產生 xAI 臨時 token,可以將其作為 ephemeralToken 傳入;Provider 會使用 xai-client-secret.<token> WebSocket protocol,而非 authorization header。若同時設定 apiKey 與 ephemeralToken,Provider 會使用臨時 token。
方法「方法」的直接連結
connect()「connect」的直接連結
建立 WebSocket 連線並傳送初始 session.update。
requestContext?:
回傳:Promise<void>
close()「close」的直接連結
關閉 WebSocket 連線、結束使用中的 speaker 串流,並清除已排入佇列的事件、待處理的函式呼叫狀態與請求脈絡。disconnect() 是 close() 的別名。
回傳:void
addInstructions()「addinstructions」的直接連結
設定工作階段指示。若 WebSocket 已開啟,Provider 會傳送 session.update。傳入 undefined 會儲存空字串,並清除目前工作階段或下一次連線中的有效指示。
instructions?:
回傳:void
addTools()「addtools」的直接連結
註冊 Mastra 函式 Tool;連線後,會透過 session.update 重新整理工作階段 Tool。
tools?:
回傳:void
updateConfig()「updateconfig」的直接連結
傳送含有其他 xAI 工作階段欄位的 session.update 事件。
sessionConfig:
回傳:void
speak()「speak」的直接連結
使用 conversation.item.create 傳送文字輪次,接著請求回應。
input:
options.speaker?:
options.response?:
回傳:Promise<void>
send()「send」的直接連結
使用 input_audio_buffer.append 串流即時音訊區塊。
send() 需要已開啟的連線。請在 connect() resolve 後,用它處理麥克風即時音訊。可讀取串流的區塊必須是二進位音訊區塊(Buffer、ArrayBuffer 或 typed array)。
audioData:
eventId?:
回傳:Promise<void>
listen()「listen」的直接連結
使用 input_audio_buffer.append 傳送有限長度的音訊串流。預設會提交輸入緩衝區並請求回應。
audioData:
options.commit?:
options.createResponse?:
回傳:Promise<void>
answer()「answer」的直接連結
傳送 response.create,要求 xAI 繼續對話。
回傳:Promise<void>
commitAudioBuffer() 與 clearAudioBuffer()「commitaudiobuffer-and-clearaudiobuffer」的直接連結
傳送對應的 xAI 即時使用者端事件,以手動控制輪次。
回傳:Promise<void>
cancelResponse()「cancelresponse」的直接連結
傳送 response.cancel,中斷進行中的回應。
responseId?:
eventId?:
回傳:Promise<void>
事件「事件」的直接連結
XAIRealtimeVoice 會將 xAI 即時伺服器事件對應至 Mastra 語音事件:
speaker:發出助理音訊的可讀取串流。speaking:發出助理音訊增量。speaking.done:助理音訊回應完成時發出。writing:發出助理文字增量與使用者輸入轉錄。error:發出 xAI 與 Provider 執行錯誤,也會發出 Tool 執行錯誤及格式錯誤的函式呼叫引數。Tool 錯誤包含details.call_id與details.name。close:WebSocket 關閉時發出。tool-call-start:在執行 Mastra 函式 Tool 前發出。tool-call-result:Mastra 函式 Tool 回傳後發出。
原始 xAI 事件名稱也會發出,因此你可以訂閱 response.output_audio.delta、response.text.delta、response.function_call_arguments.done 與 response.done 等事件。
Tool「Tool」的直接連結
Mastra 函式 Tool「Mastra 函式 Tool」的直接連結
使用 addTools() 加入的 Tool 會轉換成 xAI 函式 Tool,並納入 session.update。
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
const weatherTool = createTool({
id: 'getWeather',
description: 'Get current weather for a location.',
inputSchema: z.object({
location: z.string(),
}),
execute: async ({ location }) => {
return { location, temperature: 22 }
},
})
voice.addTools({ getWeather: weatherTool })
當 xAI 發出 response.function_call_arguments.done 時,Provider 會執行相符的 Mastra Tool,並傳送 function_call_output 項目。如果 xAI 在一個回應中發出多個函式呼叫,Provider 會等待所有 Tool 結果及該回應的 response.done 事件,再傳送一個接續的 response.create。
xAI 伺服器端 Tool「xAI 伺服器端 Tool」的直接連結
xAI 伺服器端 Tool 會原樣透過工作階段設定傳入,並由 xAI 執行。傳入 session.tools 與 serverTools 的 Tool 會合併:
const voice = new XAIRealtimeVoice({
apiKey: process.env.XAI_API_KEY,
serverTools: [
{ type: 'web_search' },
{ type: 'x_search', allowed_x_handles: ['xai'] },
{ type: 'file_search', vector_store_ids: ['collection_123'], max_num_results: 10 },
{
type: 'mcp',
server_url: 'https://mcp.example.com/mcp',
server_label: 'business-tools',
allowed_tools: ['lookup_order'],
},
],
})
音訊格式「音訊格式」的直接連結
預設輸入與輸出格式為 24 kHz PCM16。你也可以設定支援的 PCM 取樣率或電話語音 codec:
const voice = new XAIRealtimeVoice({
audio: {
input: { format: { type: 'audio/pcm', rate: 16000 } },
output: { format: { type: 'audio/pcm', rate: 16000 } },
},
})
支援的格式類型包括 audio/pcm、audio/pcmu 與 audio/pcma。PCM 支援文件所列的 8 kHz 至 48 kHz 取樣率。audio/pcmu 與 audio/pcma 是 G.711 電話語音 codec,並使用 8 kHz。