xAI Realtime Voice
XAIRealtimeVoice クラスは、xAI Grok Voice Agent API を使用したリアルタイム Voice 対話機能を提供します。Mastra の MastraVoice リアルタイムコントラクトを実装し、双方向音声ストリーミング、テキストターン、サーバー VAD、xAI Voice、関数 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 の共通 Voice 設定形式も使用できます。
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 の一時トークンを発行している場合は、ephemeralToken として渡せます。Provider は認証ヘッダーの代わりに xai-client-secret.<token> WebSocket プロトコルを使用します。apiKey と ephemeralToken の両方を設定した場合、Provider は一時トークンを使用します。
メソッドメソッドへの直接リンク
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() の解決後、ライブマイク音声に使用します。読み取り可能なストリームのチャンクは、バイナリ音声チャンク(Buffer、ArrayBuffer、型付き配列のいずれか)である必要があります。
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() and clearAudioBuffer()commitaudiobuffer-and-clearaudiobufferへの直接リンク
手動のターン制御用に、対応する xAI Realtime クライアントイベントを送信します。
戻り値: Promise<void>
cancelResponse()cancelresponseへの直接リンク
response.cancel を送信し、処理中の応答を中断します。
responseId?:
eventId?:
戻り値: Promise<void>
イベントイベントへの直接リンク
XAIRealtimeVoice は xAI Realtime サーバーイベントを Mastra Voice イベントにマッピングします。
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 などのイベントを購読できます。
ToolToolへの直接リンク
Mastra 関数 ToolMastra 関数 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 が1つの応答に対して複数の関数呼び出しを送出した場合、Provider はすべての Tool 結果と応答の response.done イベントを待ってから、続行用の response.create を1つ送信します。
xAI サーバー側 ToolxAI サーバー側 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 サンプルレートまたはテレフォニーコーデックも設定できます。
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 テレフォニーコーデックで、8 kHz を使用します。