stt
xAI speech-to-text service implementation.
This module provides integration with xAI’s real-time speech-to-text WebSocket API documented at https://docs.x.ai/developers/rest-api-reference/inference/voice.
- pipecat.services.xai.stt.language_to_xai_stt_language(language: Language) str[source]
Convert a Language enum to the xAI STT language code.
xAI STT accepts two-letter language codes (e.g.
en,fr,de,ja). When set, the server applies Inverse Text Normalization.- Parameters:
language – The Language enum value to convert.
- Returns:
The corresponding service language code. If
languageis not in the verified mapping, falls back to the base language code (e.g.,enfromen-US) and logs a warning (viaresolve_language(..., use_base_code=True)).
- class pipecat.services.xai.stt.XAISTTSettings(model: str | None | NotGiven = <factory>, extra: dict[str, ~typing.Any]=<factory>, language: Language | str | None | NotGiven = <factory>, interim_results: bool | NotGiven = <factory>, endpointing: int | None | NotGiven = <factory>, multichannel: bool | None | NotGiven = <factory>, channels: int | None | NotGiven = <factory>, diarize: bool | None | NotGiven = <factory>, keyterm: list[str] | None | NotGiven = <factory>, filler_words: bool | None | NotGiven = <factory>, vad_threshold: float | None | NotGiven = <factory>, smart_turn: float | None | NotGiven = <factory>, smart_turn_timeout: int | None | NotGiven = <factory>, speaker_format: str | None | NotGiven = <factory>)[source]
Bases:
STTSettingsSettings for XAISTTService.
- Parameters:
interim_results – When True, partial transcripts are emitted approximately every 500ms.
endpointing – Silence duration in milliseconds that triggers the speech-final event carrying the utterance’s
TranscriptionFrame. Range 0-5000. Server default is 400ms.multichannel – When True, transcribes each interleaved channel independently. Requires
channels>= 2.channels – Number of interleaved channels (2-8). Required when
multichannelis True.diarize – When True, the server attaches a
speakerfield to each word identifying the detected speaker. Each contiguous speaker run of a final transcript is emitted as its own frame with that speaker asspeaker.label. Interim transcripts are not labelled.keyterm – Terms to bias recognition towards, such as product or proper names. Up to 100 terms of 50 characters each.
filler_words – When True, transcripts keep disfluencies such as “uh” and “um” instead of dropping them.
vad_threshold – Speech probability, 0.0-1.0, above which audio is sent for transcription. Server default is 0.08; lower it for quiet or noisy speech.
smart_turn – Confidence threshold, 0.0-1.0, for the server’s semantic end-of-turn detection. When set,
speech_finalfollows the detected turn rather than theendpointingsilence timer.smart_turn_timeout – Milliseconds, 1-5000, after which the server marks the turn final even if end-of-turn detection has not fired.
speaker_format – Optional format string for diarized speaker runs. Use
{speaker}for the speaker label,{text}for the transcript text, and{speaker_number}for the speaker’s order of first appearance in the session (1,2, …), e.g."{speaker}: {text}". IfNone, transcript text is not modified. Applied locally, so changing it does not reconnect.
- class pipecat.services.xai.stt.XAISTTService(*, api_key: str, ws_url: str = 'wss://api.x.ai/v1/stt', sample_rate: int | None = None, encoding: str = 'pcm', settings: XAISTTSettings | None = None, ttfs_p99_latency: float | None = 2.14, **kwargs)[source]
Bases:
WebsocketSTTServicexAI real-time speech-to-text service.
Streams audio to xAI’s WebSocket STT endpoint and emits interim and final transcription frames. The
XAI_API_KEYis passed directly as a Bearer token on the WebSocket handshake.The connection is persistent: audio is streamed continuously and the server emits
transcript.partialevents withis_finalandspeech_finalflags. Interim results (is_final=false) and chunk finals (is_final=true, speech_final=false) are pushed asInterimTranscriptionFrame. Only the utterance final (speech_final=true) is pushed as aTranscriptionFrame, because it restates the entire utterance, including the text of every earlier chunk final. If the connection drops mid-session, the base class reconnects automatically.- Settings
alias of
XAISTTSettings
- __init__(*, api_key: str, ws_url: str = 'wss://api.x.ai/v1/stt', sample_rate: int | None = None, encoding: str = 'pcm', settings: XAISTTSettings | None = None, ttfs_p99_latency: float | None = 2.14, **kwargs)[source]
Initialize the xAI STT service.
- Parameters:
api_key – xAI API key (used as Bearer for the WebSocket handshake).
ws_url – WebSocket endpoint URL. Defaults to
wss://api.x.ai/v1/stt.sample_rate – Audio sample rate in Hz. Supported values: 8000, 16000, 22050, 24000, 44100, 48000. If None, uses the input sample rate from the start frame.
encoding – Audio encoding. One of
"pcm"(signed 16-bit LE),"mulaw","alaw", or"opus". Defaults to"pcm".settings – Runtime-updatable settings overriding defaults.
ttfs_p99_latency – P99 latency from speech end to final transcript in seconds. See https://github.com/pipecat-ai/stt-benchmark.
**kwargs – Additional arguments passed to WebsocketSTTService.
- can_generate_metrics() bool[source]
Check if the service can generate metrics.
- Returns:
True if metrics generation is supported.
- language_to_service_language(language: Language) str | None[source]
Convert a Language enum to the xAI STT language code.
- async setup(setup: FrameProcessorSetup)[source]
Set up the service and connect.
- Parameters:
setup – Configuration object containing setup parameters.
- async cancel(frame: CancelFrame)[source]
Cancel the speech-to-text service.
- async run_stt(audio: bytes) AsyncGenerator[Frame | None, None][source]
Forward raw audio bytes to the xAI STT WebSocket.
Transcription frames are pushed from the receive task, not yielded from this coroutine.
- async push_frame(frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM)
Push a frame downstream, tracking TranscriptionFrame timestamps for TTFB.
Stores the timestamp of each TranscriptionFrame for TTFB calculation. If the frame is marked as finalized (via request_finalize/confirm_finalize), reports TTFB immediately and cancels any pending timeout. Otherwise, TTFB is reported after a timeout.
- Parameters:
frame – The frame to push.
direction – The direction to push the frame.