Note
The Chinese and English guides cover the same model capabilities and main workflows. Sample inputs, prompts, output fields, and validation details may differ; follow the code in the guide you are reading. The companion Python scripts and Notebooks follow the Chinese guide.
1. Understand realtime voice models and conversation turns
StepAudio 3 Realtime supports two-way realtime voice interaction. It receives audio over a persistent WebSocket connection and returns text and audio events. The service handles speech understanding, turn management, and responses within one session, and allows the user to start speaking again while the assistant is talking. Model overview
Two concepts are central to tuning. Voice activity detection (VAD) determines when speech starts and ends. A turn consists of a user input and its corresponding response. VAD affects how pauses divide speech, while turn handling requires the client to associate transcripts and audio with the correct response. Natural interruption also requires the local player to discard buffered audio from the previous response promptly.
This guide uses stepaudio-3-realtime-preview to implement a minimal voice conversation in a standard Python project. You will tune VAD parameters and assistant instructions, with recording, response handling, and connection lifecycle code separated by responsibility so you can integrate them into your own interface.
Workflow: Prepare devices → Configure audio and VAD → Exchange session events → Start a conversation → Compare parameters → Integrate a player.
2. Prerequisites and setup
2.1 Prerequisites
Required knowledge: Python functions, dictionaries, and JSON, plus a basic understanding of the request–response flow. The audio implementation also uses callbacks and queues; this guide explains their roles in recording and playback.
- Python 3.10 or later.
- A StepFun API key with access to stepaudio-3-realtime-preview.
- Audio devices: a microphone and headphones, with microphone access granted to your terminal or IDE.
2.2 Create a Python environment
For an existing project, you can use its current virtual environment. For a new project, create an environment in any working directory. Run the following in a macOS or Linux terminal:
In Windows PowerShell, run:
After activation, confirm the Python version with the following command. All subsequent python commands refer to this environment’s interpreter.
2.3 Install dependencies
Use websocket-client for the realtime connection and sounddevice for audio devices. Install them in the activated environment:
If PortAudio is missing, install the required system component according to the sounddevice installation guide.
2.4 Configure credentials and run the example
Set STEP_API_KEY in the terminal that will run the example. Replace YOUR_STEP_API_KEY with your API key.
macOS / Linux:
Windows PowerShell:
Run the Python commands below in the same terminal. For a Notebook, start Jupyter from that terminal so its kernel inherits the variable. If the variable is unset, the code prompts for the key with input hidden.
Set REGION = "cn" for the China region, which uses .com endpoints, or "global" for the international region, which uses .ai endpoints. Use a key issued for the selected region.
Create realtime_demo.py in your project and copy this guide's Python code blocks into that file in order. Run the bash and powershell blocks only in a terminal. After adding the definitions and calls, run:
2.5 Configure the connection and audio devices
MODEL and REGION select the service. input_device and output_device select devices on the local machine; None uses the system default. You can select device IDs from the list shown later. block_ms sets the duration of each local audio callback block, starting at 20 milliseconds.
Both input and output use mono 16-bit PCM. PCM has no file header, so input_rate and output_rate must match the server requirements and device settings. Changing a local value does not make the server resample audio automatically. This example retains 24000 Hz as its starting point; verify it against the current session format before integration.
2.6 Identify devices and check the format
sounddevice accesses devices on the machine running the Python process. Run the following checks in a local terminal before connecting to the model. To change devices, update only the device IDs in AUDIO_CONFIG.
3. Configure a session and complete a conversation
3.1 Parameter group: assistant instructions and VAD
instructions controls the response language and style, while voice selects the output voice. VAD settings are grouped in VAD_CONFIG:
Change one VAD parameter at a time while keeping the device and spoken input fixed. For field definitions, see the session API.
3.2 Client configuration: audio buffers and chunks
The recording callback places PCM in a send queue, and the playback callback consumes PCM from a buffer. Queue capacity limits memory use; block_ms controls the chunk size passed to the device. These are client audio settings and should be tuned separately from the server VAD silence interval.
Devices open only after the server confirms the session configuration. The following functions handle device formats and resource cleanup. To integrate another player, replace this layer while keeping the session parameters above.
3.3 Connect the recording queue to the WebSocket
The sending thread continuously reads PCM and wraps it in input_audio_buffer.append events. It does not decide when the user has finished speaking; the server VAD configured above makes that decision. A stop flag controls both the sending thread and the devices.
3.4 Turn events: VAD and local interruption handling
On speech_started, clear the previous playback buffer and mark any response still being generated for discard. This prevents late audio from the previous response from entering the new turn. On speech_stopped, record a timestamp to measure the interval until the first audio chunk arrives.
3.5 Response events: transcripts, audio, and response IDs
response_id associates each audio chunk with a specific response. The client plays only responses that remain valid. When a completion event arrives, release that response's state and save its completion status and chunk count. To integrate a transcript panel, replace the text output here with UI updates.
3.6 Initialize the session and dispatch events
The server first sends session.created, then the client sends its configuration. The microphone opens only after session.updated arrives. This sequence ensures that the voice and VAD settings are active. The following entry point dispatches session events to the corresponding handlers.
3.7 Combine the components in a connection object
RealtimeSession holds the state for one connection and exposes start(), stop(), and summary(). You can use it in a terminal program, web backend, or desktop application. The calling project determines when to start and stop the connection.
3.8 Start a conversation in the terminal
Finally, define the entry point for a standard Python script. It waits for configuration confirmation, then keeps the program running in the terminal. Say a few sentences and listen to the replies, then press Enter to stop. The finally block releases the connection and devices. You can use the same flow in an IDE terminal.
4. Tune VAD parameters individually
4.1 silence_duration_ms: wait for the user to finish
After the first session ends, change silence_duration_ms to 300 and hold all other conditions constant. Start the second session through the same entry point, say the same phrases as in session A, and press Enter to stop. A longer silence interval allows more time for pauses within a sentence and also affects when the assistant starts replying.
In both sessions, try a complete short sentence, a sentence with a pause, and speaking again while the assistant is replying. Check whether the beginning is captured fully, whether sentences end prematurely, and whether the previous response stops promptly when you resume speaking.
4.2 prefix_padding_ms: preserve the start of speech
This parameter determines how much preceding audio to retain after speech onset is detected. Focus on initial syllables and the first transcribed word. It does not set the wait at the end of a sentence. Keep the chosen silence interval fixed, change only this value in VAD_CONFIG, and run another session using the same short opening phrase.
4.3 energy_awakeness_threshold: match the recording environment
The energy threshold affects which sounds are more likely to count as speech activity. Keep microphone distance, gain, and background sound fixed while tuning it. Observe whether quiet periods trigger turns and whether normal speech is transcribed completely. Changing the audio device and threshold together makes it difficult to attribute the effect.
4.4 instructions: change the response style
VAD controls input turns, while instructions controls how the assistant responds. To compare response lengths, change only the requirements in ASSISTANT_CONFIG and use the same question and VAD settings. After changing a configuration dictionary, rebuild SETTINGS and create a new session. Existing connections do not automatically adopt changes to local values.
5. Interpret event records and listening results
first_audio_after_speech_stopped_ms measures the interval from the client's receipt of the turn-end event to the arrival of the first valid audio chunk, including network effects. It differs from the end-to-end time between the user stopping speech and sound actually coming from the device. Device buffering and VAD waiting time require separate measurements.
The following code saves both sessions' configurations, transcripts, response statuses, and event intervals. It does not save the API key or raw microphone audio.
Compare transcript completeness, turn events, response statuses, and what you hear. Event counts help explain what happened; playback and natural interruption behavior require an actual conversation on the target device.
6. Integrate the example into your project
Reuse the code along these boundaries:
- Configuration: Map ASSISTANT_CONFIG and VAD_CONFIG to your application's settings. Keep audio format and device settings in AUDIO_CONFIG.
- Session lifecycle: Call RealtimeSession.start() to connect and stop() from your application's exit or disconnect logic. The terminal example uses input() only to wait for the user to finish. A service can replace it with a button action or connection lifecycle event.
- Output: Route text from handle_response() to a transcript panel and pass valid PCM to your existing player. Retain response association and cleanup of old playback buffers.
First complete a short session with this guide's settings, then change one variable at a time for your pause patterns and devices. Available model names and session formats are governed by the official model documentation and your account configuration.
7. Companion code and starter project
This example includes a Jupyter Notebook, an editable Python script, and a starter project for running and adapting the code. Browse the example directory for all files, or see the setup and launch guide for instructions.
To use the launchers, obtain the complete example directory from the current repository and keep its relative paths intact. Initial setup requires an internet connection. The supplied Notebook, Python script, launch menu, and setup guide currently follow the Chinese version. To reproduce this guide's English prompts, sample inputs, and result fields, use the Python code blocks in this guide.
