> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # xAI Realtime Voice `XAIRealtimeVoice` 类使用 xAI Grok Voice Agent API 提供实时 Voice 交互能力。它实现了 Mastra 的 `MastraVoice` 实时契约,并支持双向音频流、文本轮次、server VAD、xAI Voice、function Tool 和 xAI server-side Tool。 ## 使用示例 ```typescript 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** (`string`): xAI API key。未提供时使用 XAI\_API\_KEY 环境变量。 **ephemeralToken** (`string`): 通过 WebSocket protocol 发送的短期 xAI token,用于替代 authorization header。 **model** (`XAIRealtimeModel`): 要使用的 Grok Voice 模型。 (Default: `'grok-voice-think-fast-1.0'`) **speaker** (`XAIVoice`): 用于语音输出的 Voice ID。内置值包括 eve、ara、rex、sal 和 leo,也支持自定义 xAI Voice ID。 (Default: `'eve'`) **instructions** (`string`): 在 session.update 中发送的系统指令。 **turnDetection** (`XAITurnDetection`): 语音活动检测配置。 (Default: `{ type: 'server_vad' }`) **audio** (`XAIAudioConfig`): 输入和输出音频格式配置。 (Default: `24 kHz audio/pcm input and output`) **serverTools** (`XAIServerTool[]`): 在 session.update 中发送的 xAI server-side Tool。支持 file\_search、web\_search、x\_search 和 mcp。这些 Tool 会与 session.tools 合并。 **session** (`Partial`): 要合并到初始 session.update 事件中的其他 xAI session 字段。 **url** (`string`): 覆盖 xAI Realtime WebSocket URL。 (Default: `'wss://api.x.ai/v1/realtime'`) **debug** (`boolean`): 为接收到的 xAI 事件启用 debug 日志。Debug 日志可能包含转录文本和 Tool 调用参数。 (Default: `false`) ### VoiceConfig 模式 还可以使用 Mastra 共享的 Voice 配置结构: ```typescript 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 }, }, }, }) ``` ## 身份验证 server-side 应用请使用 `apiKey` 或 `XAI_API_KEY`。此 Provider 面向 Node.js server-side runtime 构建。如果你的服务器已签发 xAI ephemeral token,可以通过 `ephemeralToken` 传入;Provider 会使用 `xai-client-secret.` WebSocket protocol,而不是 authorization header。如果同时配置了 `apiKey` 和 `ephemeralToken`,Provider 会使用 ephemeral token。 ## 方法 ### `connect()` 建立 WebSocket 连接并发送初始 `session.update`。 **requestContext** (`RequestContext`): 传给 function Tool 执行过程的可选 Mastra request context。 返回:`Promise` ### `close()` 关闭 WebSocket 连接、结束活跃的 speaker 流,并清除排队事件、待处理的 function-call 状态和 request context。`disconnect()` 是 `close()` 的别名。 返回:`void` ### `addInstructions()` 设置 session 指令。如果 WebSocket 已打开,Provider 会发送 `session.update`。传入 `undefined` 会存储空字符串,并清除当前 session 或下次连接中的活跃指令。 **instructions** (`string`): 要发送给 xAI 的系统指令。 返回:`void` ### `addTools()` 注册 Mastra function Tool,并在已连接时通过 `session.update` 刷新 session Tool。 **tools** (`ToolsInput`): 要作为 xAI function Tool 公开的 Mastra Tool。 返回:`void` ### `updateConfig()` 发送包含其他 xAI session 字段的 `session.update` 事件。 **sessionConfig** (`Partial`): 要更新的 session 字段。 返回:`void` ### `speak()` 使用 `conversation.item.create` 发送一个文本轮次,然后请求响应。 **input** (`string | NodeJS.ReadableStream`): 要作为用户输入发送的文本或文本可读流。 **options.speaker** (`XAIVoice`): Voice 覆盖项。它会更新活跃 xAI session 的 Voice,并用于后续轮次。 **options.response** (`Record`): 其他 xAI response.create 字段。 返回:`Promise` ### `send()` 使用 `input_audio_buffer.append` 流式传输实时音频块。 `send()` 要求连接处于打开状态。请在 `connect()` 解析完成后,用它处理麦克风实时音频。可读流块必须是二进制音频块(`Buffer`、`ArrayBuffer` 或 typed array)。 **audioData** (`NodeJS.ReadableStream | Int16Array`): PCM 音频流或 Int16Array 音频数据。 **eventId** (`string`): 可选的 xAI event ID。 返回:`Promise` ### `listen()` 使用 `input_audio_buffer.append` 发送有限音频流。默认情况下,它会提交输入 buffer 并请求响应。 **audioData** (`NodeJS.ReadableStream`): 要发送的音频流。 **options.commit** (`boolean`): 是否在音频 item 之后发送 input\_audio\_buffer.commit。 (Default: `true`) **options.createResponse** (`boolean`): 是否在音频 item 之后发送 response.create。 (Default: `true`) 返回:`Promise` ### `answer()` 发送 `response.create`,让 xAI 继续对话。 返回:`Promise` ### `commitAudioBuffer()` 和 `clearAudioBuffer()` 发送对应的 xAI Realtime client 事件,以便手动控制轮次。 返回:`Promise` ### `cancelResponse()` 发送 `response.cancel` 以中断正在处理的响应。 **responseId** (`string`): 要取消的可选 xAI response ID。 **eventId** (`string`): 可选的 xAI event ID。 返回:`Promise` ## 事件 `XAIRealtimeVoice` 将 xAI Realtime server 事件映射到 Mastra Voice 事件: - `speaker`:发出助手音频的可读流。 - `speaking`:发出助手音频增量。 - `speaking.done`:助手音频响应完成时发出。 - `writing`:发出助手文本增量和用户输入转录。 - `error`:发出 xAI 和 Provider 执行错误。它也会发出 Tool 执行错误和格式错误的 function-call 参数。Tool 错误包含 `details.call_id` 和 `details.name`。 - `close`:WebSocket 关闭时发出。 - `tool-call-start`:在执行 Mastra function Tool 前发出。 - `tool-call-result`:Mastra function Tool 返回后发出。 原始 xAI 事件名称也会发出,因此你可以订阅 `response.output_audio.delta`、`response.text.delta`、`response.function_call_arguments.done` 和 `response.done` 等事件。 ## Tool ### Mastra 函数 Tool 通过 `addTools()` 添加的 Tool 会转换为 xAI function Tool,并包含在 `session.update` 中。 ```typescript 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` item。如果 xAI 为一个响应发出多个 function call,Provider 会等待所有 Tool 结果和该响应的 `response.done` 事件,然后再发送一个用于继续的 `response.create`。 ### xAI server-side Tool(服务端 Tool) xAI server-side Tool 会在 session 配置中透传并由 xAI 执行。传入 `session.tools` 和 `serverTools` 的 Tool 会合并: ```typescript 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 采样率或电话编解码器: ```typescript 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。