模型能力

Speech to Text

通过一次 API 调用将音频文件转录为文本,或通过 WebSocket 实时 streaming 音频。API 支持 12 种音频格式、word-level timestamp、multichannel transcription 和文本格式化。

快速开始

通过一次 API 调用转录音频文件:

curl -X POST https://api.x.ai/v1/stt \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -F format=true \
  -F language=en \
  -F "keyterm=Understand The Universe" \
  -F file=@audio.mp3

注意:file 参数必须位于 multipart form 中所有其他参数之后。

获取 API Key →

实时 Voice Demo

支持的语言

language 参数可为以下语言启用格式化。无论是否设置 language 参数,model 都能转录这些语言;设置该参数会将数字、货币和单位格式化为书面形式。

语言代码语言代码
阿拉伯语ar马其顿语mk
捷克语cs马来语ms
丹麦语da波斯语fa
荷兰语nl波兰语pl
英语en葡萄牙语pt
菲律宾语fil罗马尼亚语ro
法语fr俄语ru
德语de西班牙语es
印地语hi瑞典语sv
印度尼西亚语id泰语th
意大利语it土耳其语tr
日语ja越南语vi
韩语ko

Request Body

请求使用 multipart/form-data。必须提供 fileurl 其中之一。

参数类型默认值必填说明
filefile✓†要转录的音频文件。最大 500 MB。详见 支持的格式。必须是 multipart form 中的最后一个字段。
urlstring✓†要在服务端下载并转录的音频文件 URL。
audio_formatstring用于 raw/headerless 音频的格式提示:pcmmulawalaw。Container 格式会自动检测,因此不要为 MP3、WAV 等设置该字段。
sample_rateinteger以 Hz 为单位的 sample rate。仅 raw 音频(pcmmulawalaw)需要。支持:80001600022050240004410048000
languagestring语言代码(例如 enfrde)。与 format=true 一起使用以启用文本格式化。详见 支持的语言
formatbooleanfalse设为 true 时,启用 Inverse Text Normalization,将口语形式的数字/货币转换为书面形式(例如 "one hundred dollars" → "$100")。需要 language
multichannelbooleanfalse设为 true 时,分别转录每个 audio channel。结果在 channels array 中返回。
channelsintegerAudio channel 数量(2–8)。仅 multichannel raw 音频需要。Container 格式会自动检测。
diarizebooleanfalse设为 true 时,启用 speaker diarization。Response 中的每个词都包含一个 speaker 字段(integer),用于标识检测到的说话者。
keytermstring用于引导 transcription 的 key term(例如产品名、专有名词)。多个 term 可重复传入该字段(例如 keyterm=Understand+The+Universe)。最多 100 个 term,每个最长 50 个字符。
filler_wordsbooleanfalse设为 true 时,transcript 会包含 filler word(例如 "uh"、"um"、"er")。设为 false(默认)时,filler word 会自动从 transcript 文本和 words array 中返回。
vad_thresholdnumber0.5voice-activity gate 的语音概率 threshold(0.0–1.0)。得分低于 threshold 的音频 segment 会被视为非语音并跳过 transcription。较低的值可转录更安静或噪声更大的语音(例如 narrowband telephony),但背景噪声可能产生错误文本。0 会禁用该 gate。

† 必须提供 fileurl 其中之一。

Option 字段应位于 file 之前;对于 streamable upload,在 file 之后发送的字段可能会被忽略。

文本格式化示例

Bash

curl -X POST https://api.x.ai/v1/stt \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -F format=true \
  -F language=en \
  -F "keyterm=Understand The Universe" \
  -F file=@meeting.mp3

file 参数必须位于 multipart form 中所有其他参数之后。

Response

Response 包含完整 transcript、音频 duration 和 word-level timestamp。

JSON

{
  "text": "The balance is $167,983.15.",
  "language": "English",
  "duration": 3.45,
  "words": [
    { "text": "The", "start": 0.24, "end": 0.48 },
    { "text": "balance", "start": 0.48, "end": 0.96 },
    { "text": "is", "start": 0.96, "end": 1.12 },
    { "text": "$167,983.15.", "start": 1.12, "end": 3.20 }
  ]
}
字段类型说明
textstring完整 transcript 文本。
languagestring检测到的语言名称(例如 "English""French")。
durationnumber音频 duration,以秒为单位(保留 2 位小数)。
wordsarray包含 textstartendspeaker 的 word-level segment(integer,仅当 diarize=true)。
channelsarray每个 channel 的 transcript(仅当 multichannel=true)。每个条目包含 indextextwords

支持的音频格式

Container 格式(自动检测)

格式扩展名说明
WAV.wavWaveform Audio,无损、最佳质量输入
MP3.mp3MPEG Audio Layer 3,广泛支持
OGG.oggOgg container,开放格式
Opus.opusOpus codec,低延迟、高质量
FLAC.flacFree Lossless Audio Codec,无损压缩
AAC.aacAdvanced Audio Coding
MP4.mp4MPEG-4 container
M4A.m4aMPEG-4 Audio,Apple 生态标准
MKV.mkvMatroska container,支持 MP3、AAC 和 FLAC audio codec

Raw 格式(需要 audio_formatsample_rate

格式audio_format说明
PCMpcmSigned 16-bit little-endian(2 bytes/sample)
µ-lawmulawG.711 µ-law(1 byte/sample)
A-lawalawG.711 A-law(1 byte/sample)

限制

  • 最大文件大小: 500 MB

  • Channels: Mono、stereo,或最多 8 个 channel(使用 multichannel=true

  • Sample rate: 8000、16000、22050、24000、44100、48000 Hz

Streaming Speech-to-Text(WebSocket)

实时 transcription 请使用位于 wss://api.x.ai/v1/stt 的 WebSocket API。Client 将 raw 音频作为 binary WebSocket frame streaming,并在处理音频时接收 JSON transcript event。

Endpoint: wss://api.x.ai/v1/stt

通过 URL query parameter 完成配置,无需 setup message。音频以 raw binary frame 发送(不使用 base64 encoding)。

Query Parameters

参数类型默认值说明
sample_rateinteger16000以 Hz 为单位的 audio sample rate。
encodingstringpcm音频 encoding:pcmmulawalaw
interim_resultsbooleanfalse设为 true 时,每约 500 ms 发出 partial transcript is_final=false
endpointinginteger10utterance-final event 前的静音时长(ms)。范围:0–5000。0 表示在任意 VAD 静音边界触发。
languagestring用于文本格式化的语言代码。详见 支持的语言
diarizeboolean设为 true 时启用 speaker diarization。Word 包含 speaker 字段,用于标识检测到的说话者。
filler_wordsbooleanfalse设为 true 时,transcript 包含 filler word(例如 uhumer)。设为 false(默认)时,filler word 会被自动移除。
multichannelbooleanfalsePer-channel transcription。需要 channels ≥ 2。
channelsinteger1交错 audio channel 数量(最多 8 个)。
keytermstring用于引导 transcription 的 key term(例如产品名、专有名词)。多个 term 可重复传入参数(例如 keyterm=Understand+The+Universe)。最多 100 个 term,每个最长 50 个字符。
smart_turnnumber轮次结束检测 threshold(0.0–1.0)。设置后启用 Smart Turn,由 ML model 在每个静音边界预测说话者是否已完成表达。详见 Smart Turn
smart_turn_timeoutinteger强制 speech_final 前的最长静音时长(ms),即使 Smart Turn model 预测说话者尚未结束也会强制触发。范围:1–5000。仅在启用 smart_turn 时适用。详见 Smart Turn
vad_thresholdnumber0.08voice-activity gate 的语音概率 threshold(0.0–1.0)。得分低于 threshold 的 audio chunk 会被视为非语音并跳过 transcription。较低的值可转录更安静或噪声更大的语音(例如 narrowband telephony),但背景噪声可能产生错误文本。0 会禁用 gate。不会影响 endpointing 或 speech_final 的 timing。

Server Events

Event说明
transcript.createdServer 已就绪,发送音频前请等待该 event。
transcript.partial包含 textwordsis_finalspeech_finalstartduration 的 transcript 结果。包含 channel_index,当 multichannel=true 的 transcript 结果。包含 end_of_turn_confidence,当 smart_turn 启用时。
transcript.doneaudio.done 之后的最终 transcript。duration 始终存在。当 channel_index,当 multichannel=true 时包含该字段,每个 channel 发送一个 event。之后连接关闭。
error带有 message 字段的错误。连接保持打开。

transcript.partial event 使用 is_finalspeech_final 表示三种状态:

is_finalspeech_final含义
falsefalseInterim — 文本可能变化(仅当 interim_results=true
truefalseChunk final — 文本已锁定,约 3 秒语音完成。启用 smart_turn 时,model confidence 低于 threshold 的静音停顿会降级为 chunk final,而不是 utterance final。
truetrueUtterance final — 说话者已停止,形成完整拼接 utterance。启用 smart_turn 时,仅当 model 的 end-of-turn confidence 超过 threshold,或 smart_turn_timeout 被超过时触发。

Client Messages

  • Binary frame — 使用指定 encoding 的 raw 音频(按实时节奏 streaming chunk,例如 100 ms)

  • {"type": "finalize"} — 强制当前 utterance 立即以 speech_final 完成,用于 PTT

  • {"type": "audio.done"} — 表示音频结束,触发 transcript.done

transcript.done 告知 server 不再发送音频,flush 剩余 transcript 并关闭 WebSocket。

Push-to-talk 示例(释放按钮时 finalize,然后继续 session):

JSON

{"type": "Finalize"}

Per-channel finalize(仅 multichannel,例如 agent 位于 channel 0):

JSON

{"type": "Finalize", "channel": 0}

Multichannel Streaming

设为 multichannel=truechannels ≥ 2 时,server 分别转录每个 audio channel。将交错的 multichannel PCM(例如 stereo 的 L,R,L,R,…)作为 binary frame 发送,server 会 de-interleave 并并行处理每个 channel。

工作原理:

  • transcript.created 发送一次(session 级别,无 channel_index)。

  • transcript.partial event 包含 channel_index 字段(从 0 开始),用于标识源 channel。不同 channel 的 event 会交错到达。

  • transcript.done每个 channel 发送一次,位于 audio.done 之后,每个都包含自己的 channel_index

  • Client Finalize 不带 channel 时会一次 finalize 所有 channel;{"type": "Finalize", "channel": N} 仅 finalize channel N(从 0 开始)。

  • Chunk 大小应考虑所有 channel,例如 16 kHz stereo PCM16 中,100 ms = 6,400 bytes(每个 channel 3,200 × 2 个 channel)。

示例 URL:

Text

wss://api.x.ai/v1/stt?sample_rate=16000&encoding=pcm&multichannel=true&channels=2&interim_results=true

典型用例: Call center 录音,agent 位于 channel 0,客户位于 channel 1,无需 speaker diarization 即可实现 per-speaker transcription。

Smart Turn

Smart Turn 使用轻量 ML model,在静音停顿时预测说话者是否已完成表达,减少句中停顿(例如口述数字或在从句间思考)导致的错误 endpointing。

工作原理:

  • 通过 smart_turn=<threshold> 启用后,model 会在每个 VAD 静音边界评估累计音频。

  • 如果 end-of-turn confidence 超过 threshold,speech_final=true 会正常触发。

  • 如果 confidence 低于 threshold,event 会降级为 chunk_finalis_final=truespeech_final=false),transcript 文本锁定,但 utterance 继续。

  • 每个 transcript.partial event 都包含 end_of_turn_confidence 字段(0.0–1.0),前提是启用了 Smart Turn。

  • 在 active speech 期间,end_of_turn_confidence0.0(model 仅在静音边界运行)。

Threshold行为
0.5均衡,可识别大多数自然轮次结束
0.7保守,需要更高 confidence 才结束轮次,更适合听写和数字序列
0.9非常保守,仅在轮次完成 confidence 很高时结束

静音 timeout(smart_turn_timeout):

启用 Smart Turn 后,model 完全控制 speech_final 的触发时机。为防止 session 在长时间静音时挂起(例如用户离开),请设置 smart_turn_timeout 为最长静音时长(毫秒,1–5000)。如果 model 持续预测 "not done" 超过该时长,speech_final 仍会触发,作为安全保障。

Text

wss://api.x.ai/v1/stt?sample_rate=16000&encoding=pcm&interim_results=true&smart_turn=0.7&smart_turn_timeout=3000

不设置 smart_turn_timeout 时,model 拥有无限控制权,speech_final 仅在 confidence 超过 threshold 时触发。

启用 Smart Turn 的 event 示例:

JSON

{
  "type": "transcript.partial",
  "text": "I will buy two of those, please.",
  "words": [...],
  "is_final": true,
  "speech_final": true,
  "start": 0.0,
  "duration": 2.4,
  "end_of_turn_confidence": 0.983
}

典型用例: 适用于希望避免在用户句中打断的 Voice assistant 和 conversational AI。没有 Smart Turn 时,口述电话号码或在从句间思考的短暂停顿会触发 speech_final。启用 Smart Turn 后,model 会等待检测到自然轮次结束(confidence 0.95+),并在句中停顿期间正确抑制触发(confidence ~0.005)。

完整示例

import asyncio
import json
import os

import websockets

API_KEY = os.environ["XAI_API_KEY"]
WS_URL = "wss://api.x.ai/v1/stt?sample_rate=16000&encoding=pcm&interim_results=true&language=en&keyterm=Understand+The+Universe"

async def transcribe_stream(audio_file: str):
    headers = {"Authorization": f"Bearer {API_KEY}"}

    async with websockets.connect(WS_URL, additional_headers=headers) as ws:
        # Wait for server ready signal
        msg = json.loads(await ws.recv())
        assert msg["type"] == "transcript.created"
        print("Server ready")

        # Read raw PCM from a WAV file (skip 44-byte header)
        with open(audio_file, "rb") as f:
            f.read(44)  # Skip WAV header
            chunk_size = 16000 * 2 // 10  # 100ms of PCM16 at 16kHz

            while chunk := f.read(chunk_size):
                await ws.send(chunk)  # Send raw binary — no base64
                await asyncio.sleep(0.1)

        # Signal end of audio
        await ws.send(json.dumps({"type": "audio.done"}))

        # Collect events until transcript.done
        async for message in ws:
            event = json.loads(message)
            if event["type"] == "transcript.partial":
                prefix = "FINAL" if event["is_final"] else "partial"
                print(f"[{prefix}] {event['text']}")
            elif event["type"] == "transcript.done":
                print(f"\nFull transcript: {event['text']}")
                print(f"Duration: {event['duration']}s")
                break

asyncio.run(transcribe_stream("audio.wav"))

用例

  • 实时字幕 — 为视频通话、会议和直播提供实时字幕

  • Voice assistant — 转录用户语音,供自然语言理解 pipeline 使用

  • Call center — 通过 multichannel per-speaker transcription 提供实时 agent 辅助

  • 无障碍 — 为听障用户提供实时 transcription

  • Voice command — 为免手持界面提供低延迟 speech-to-action

Streaming STT 提示

  • 使用 16 kHz sample rate 和 PCM encodingsample_rate=16000&encoding=pcm),这是 model 的原生 rate,可避免在 server 上 resampling

  • 启用 interim_results以获得响应迅速的 UX,在用户说话时显示 transcription

  • 使用 language=en启用文本格式化,数字和货币会以标准形式书写

  • 发送 100 ms audio chunk(16 kHz PCM16 时为 3,200 bytes),在延迟和效率之间取得良好平衡

  • 等待 transcript.created 后再发送音频,server 需要初始化 ASR backend

错误处理

Status含义操作
200成功Transcription 位于 response body 中
400错误请求缺少 file/url、格式不受支持、raw 音频缺少 sample_rateformat=true 不带 language
401未授权API key 缺失或无效
413Payload 过大文件超过 500 MB
429达到 rate limit使用 exponential delay backoff 后重试
502Bad gatewayURL 下载失败(使用 url
503服务不可用Backend 不可用,请重试