Python SDK for building voice-enabled applications using Speechmatics Real-Time API. Optimized for specific use cases: conversational AI, voice agents, transcription services, and real-time captioning.
The Voice SDK is a higher-level abstraction built on top of the Speechmatics Real-Time API (speechmatics-rt). While the Real-Time API provides raw transcription events (words and utterances), the Voice SDK adds:
Intelligent Segmentation - Groups words into meaningful speech segments per speaker
Turn Detection - Automatically detects when speakers finish their turns using adaptive or ML-based methods
Speaker Management - Focus on or ignore specific speakers in multi-speaker scenarios
Preset Configurations - Ready-to-use configs for common use cases (conversation, note-taking, captions)
Simplified Event Handling - Receive clean, structured segments instead of raw word-level events
When to Use Voice SDK vs Real-Time API
Use Voice SDK when:
You are building conversational AI or voice agents
You need automatic turn detection
You want speaker-focused transcription
You need ready-to-use presets for common scenarios
Use Real-Time API when:
You only need raw, word-level events
You are building custom segmentation / aggregation logic
You want fine-grained control over every event
Installation
# Standard installation
pip install speechmatics-voice
# With VAD and SMART_TURN (ML-based turn detection)
pip install speechmatics-voice[smart]
Note: Some features require additional ML dependencies (ONNX runtime, transformers). If not installed, these features will be unavailable and a warning will be shown.
👉 Using Docker? Click to see how to install the required models.
Use within Docker
If you are using a Docker container with the Voice SDK installed and you require the smart features (SMART_TURN), then you can use the following in your Dockerfile to make sure the ML models are included and not downloaded at runtime.
"""
Download the Voice SDK required models during the build process.
"""
from speechmatics.voice import SileroVAD, SmartTurnDetector
def load_models():
SileroVAD.download_model()
SmartTurnDetector.download_model()
if __name__ == "__main__":
load_models()
Then, in your Dockerfile, include the following:
COPY ./models.py models.py
RUN uv run models.py
This copies the script and runs it as part of the build.
Quick Start
Basic Example
A simple example that shows complete sentences as they have been finalized, with different speakers shown with different IDs.
import asyncio
import os
from speechmatics.rt import Microphone
from speechmatics.voice import VoiceAgentClient, AgentServerMessageType
async def main():
"""Stream microphone audio to Speechmatics Voice Agent using 'scribe' preset"""
# Audio configuration
SAMPLE_RATE = 16000 # Hz
CHUNK_SIZE = 160 # Samples per read
PRESET = "scribe" # Configuration preset
# Create client with preset
client = VoiceAgentClient(
api_key=os.getenv("SPEECHMATICS_API_KEY"),
preset=PRESET
)
# Print finalised segments of speech with speaker ID
@client.on(AgentServerMessageType.ADD_SEGMENT)
def on_segment(message):
for segment in message["segments"]:
speaker = segment["speaker_id"]
text = segment["text"]
print(f"{speaker}: {text}")
# Setup microphone
mic = Microphone(SAMPLE_RATE, CHUNK_SIZE)
if not mic.start():
print("Error: Microphone not available")
return
# Connect to the Voice Agent
await client.connect()
# Stream microphone audio (interruptable using keyboard)
try:
while True:
audio_chunk = await mic.read(CHUNK_SIZE)
if not audio_chunk:
break # Microphone stopped producing data
await client.send_audio(audio_chunk)
except KeyboardInterrupt:
pass
finally:
await client.disconnect()
if __name__ == "__main__":
asyncio.run(main())
Configuring a Voice Agent Client
When creating a VoiceAgentClient, there are several ways to configure it:
Presets - optimised configurations for common use cases. These require no further configuration to be set.
# Low latency preset - for fast responses (may split speech in to smaller segments)
client = VoiceAgentClient(api_key=api_key, preset="fast")
# Conversation preset - for natural dialogue
client = VoiceAgentClient(api_key=api_key, preset="adaptive")
# Advanced conversation with ML turn detection
client = VoiceAgentClient(api_key=api_key, preset="smart_turn")
# External end of turn preset - endpointing handled by the client
client = VoiceAgentClient(api_key=api_key, preset="external")
# Scribe preset - for note-taking
client = VoiceAgentClient(api_key=api_key, preset="scribe")
# Captions preset - for live captioning
client = VoiceAgentClient(api_key=api_key, preset="captions")
# To view all available presets, use:
presets = VoiceAgentConfigPreset.list_presets()
Custom Configuration - for more control, you can also specify custom configuration in a VoiceAgentConfig object.
Controls how turn endings are detected. Options: - FIXED - Uses fixed silence threshold. Fast but may split slow speech. - ADAPTIVE - Adjusts delay based on speech rate, pauses, and disfluencies. Best for natural conversation. - EXTERNAL - Manual control via client.finalize(). For custom turn logic.
end_of_utterance_silence_trigger
float
0.2
Silence duration in seconds to trigger turn end (also used for the basis of adaptive delay).
Speaker Configuration
Parameter
Type
Default
Description
enable_diarization
bool
False
Enable speaker diarization to identify and label different speakers.
speaker_sensitivity
float
0.5
Diarization sensitivity between 0.0 and 1.0. Higher values detect more speakers.
max_speakers
int
None
Limit maximum number of speakers to detect.
prefer_current_speaker
bool
False
Give extra weight to current speaker for word grouping.
speaker_config
SpeakerFocusConfig
SpeakerFocusConfig()
Configure speaker focus/ignore rules.
known_speakers
list[SpeakerIdentifier]
[]
Pre-enrolled speaker identifiers for speaker identification.
Usage Examples
Using speaker_config, you can focus on only specific speakers but keep words from others, or ignore specific speakers.
from speechmatics.voice import SpeakerFocusConfig, SpeakerFocusMode
# Focus only on specific speakers, but keep words from other speakers
config = VoiceAgentConfig(
enable_diarization=True,
speaker_config=SpeakerFocusConfig(
focus_speakers=["S1", "S2"],
focus_mode=SpeakerFocusMode.RETAIN
)
)
# Ignore specific speakers
config = VoiceAgentConfig(
enable_diarization=True,
speaker_config=SpeakerFocusConfig(
ignore_speakers=["S3"]
)
)
Using known_speakers, you can use pre-enrolled speaker identifiers to identify specific speakers.
from speechmatics.voice import SpeakerIdentifier
# Use known speakers from previous session
config = VoiceAgentConfig(
enable_diarization=True,
known_speakers=[
SpeakerIdentifier(label="Alice", speaker_identifiers=["XX...XX"]),
SpeakerIdentifier(label="Bob", speaker_identifiers=["YY...YY"])
]
)
Language & Vocabulary
Parameter
Type
Default
Description
additional_vocab
list[AdditionalVocabEntry]
[]
Custom vocabulary for domain-specific terms.
punctuation_overrides
dict
None
Custom punctuation rules.
Usage Examples
Using additional_vocab, you can specify a dictionary of domain-specific terms.
Include interim (lower confidence) words in emitted segments. Set to False for final-only output.
Event Messages
The Voice SDK emits real-time, structured events as a session progresses via AgentServerMessageType.
These events fall into three main categories:
Core Events - high-level session and transcription updates.
Speaker Events - detected speech activity.
Additional - detailed, low-level events.
To handle events, register a callback using @client.on() decorator or client.on() method.
Note: The payloads shown below are the actual message payloads from the Voice SDK. When using the CLI example with --output-file, messages also include a ts timestamp field (e.g., "ts": "2025-11-11 23:18:35.909"), which is added by the CLI for logging purposes and is not part of the SDK payload.
High Level Overview
Core Events
Event
Description
Notes / Purpose
RECOGNITION_STARTED
Fired when a transcription session starts
Contains session ID, language pack info
ADD_PARTIAL_SEGMENT
Emitted continuously during speech
Provides interim, real-time transcription text
ADD_SEGMENT
Fired when a segment is finalized
Provides stable, final transcription text
END_OF_TURN
Fired when a speaker’s turn ends
Depends on end_of_utterance_mode; useful for turn tracking
Speaker Events
Event
When it fires
Purpose
SPEAKER_STARTED
Voice detected
Marks start of speech
SPEAKER_ENDED
Silence detected
Marks end of speech
SPEAKERS_RESULT
Enrollment completes
Provides speaker IDs and labels
Additional Events
Event
When it fires
Purpose
START_OF_TURN
New turn begins
Optional, low-level event for turn tracking
END_OF_TURN_PREDICTION
Predicts turn completion
Fires before END_OF_TURN in adaptive mode
END_OF_UTTERANCE
Silence threshold reached
Low-level STT engine trigger
ADD_PARTIAL_TRANSCRIPT
Word-level partial transcript
Legacy; use ADD_PARTIAL_SEGMENT instead
ADD_TRANSCRIPT
Word-level final transcript
Legacy; use ADD_SEGMENT instead
Core Events - Examples and Payloads
RECOGNITION_STARTED
@client.on(AgentServerMessageType.RECOGNITION_STARTED)
def on_started(message):
session_id = message["id"]
language = message["language_pack_info"]["language_description"]
print(f"Session {session_id} started - Language: {language}")
@client.on(AgentServerMessageType.ADD_PARTIAL_SEGMENT)
def on_partial(message):
for segment in message["segments"]:
print(f"[INTERIM] {segment['speaker_id']}: {segment['text']}")
@client.on(AgentServerMessageType.SPEAKER_STARTED)
def on_speaker_start(message):
speaker = message["speaker_id"]
time = message["time"]
print(f"{speaker} started speaking at {time}s")
# Listen for the result
@client.on(AgentServerMessageType.SPEAKERS_RESULT)
def on_speakers(message):
for speaker in message["speakers"]:
print(f"Speaker {speaker['label']}: {speaker['speaker_identifiers']}")
# Request speaker IDs at end of session
await client.send_message({"message": AgentClientMessageType.GET_SPEAKERS, "final": True})
# Request speaker IDs now
await client.send_message({"message": AgentClientMessageType.GET_SPEAKERS})
Common Usage Patterns
Simple Transcription
client = VoiceAgentClient(api_key=api_key, preset="scribe")
@client.on(AgentServerMessageType.ADD_SEGMENT)
def on_segment(message):
for segment in message["segments"]:
print(f"{segment['speaker_id']}: {segment['text']}")
Conversational AI with Turn Detection
config = VoiceAgentConfig(
language="en",
enable_diarization=True,
end_of_utterance_mode=EndOfUtteranceMode.ADAPTIVE,
)
client = VoiceAgentClient(api_key=api_key, config=config)
@client.on(AgentServerMessageType.ADD_SEGMENT)
def on_segment(message):
user_text = message["segments"][0]["text"]
# Process user input
@client.on(AgentServerMessageType.END_OF_TURN)
def on_turn_end(message):
# User finished speaking - generate AI response
pass
Live Captions with Timestamps
client = VoiceAgentClient(api_key=api_key, preset="captions")
@client.on(AgentServerMessageType.ADD_SEGMENT)
def on_segment(message):
start_time = message["metadata"]["start_time"]
for segment in message["segments"]:
print(f"[{start_time:.1f}s] {segment['text']}")
Speaker Identification
from speechmatics.voice import SpeakerIdentifier
# Use known speakers from previous session
known_speakers = [
SpeakerIdentifier(label="Alice", speaker_identifiers=["XX...XX"]),
SpeakerIdentifier(label="Bob", speaker_identifiers=["YY...YY"])
]
config = VoiceAgentConfig(
enable_diarization=True,
known_speakers=known_speakers
)
client = VoiceAgentClient(api_key=api_key, config=config)
@client.on(AgentServerMessageType.ADD_SEGMENT)
def on_segment(message):
for segment in message["segments"]:
# Will show "Alice" or "Bob" instead of "S1", "S2"
print(f"{segment['speaker_id']}: {segment['text']}")