FastAPI WebSocket
WebSocket transport implementation for FastAPI web applications
Overview
FastAPIWebsocketTransport
provides WebSocket support for FastAPI web applications, enabling real-time audio communication. It supports bidirectional audio streams and voice activity detection (VAD).
FastAPIWebsocketTransport is best suited for server-side applications and prototyping client/server apps.
For client/server production applications, we strongly recommend using a WebRTC-based transport for robust network and media handling.
Installation
To use FastAPIWebsocketTransport
, install the required dependencies:
Configuration
Constructor Parameters
FastAPI WebSocket connection instance
Transport configuration parameters
FastAPIWebsocketParams Configuration
Add WAV header to audio frames
Frame serializer for WebSocket messages. Common options include: -
ProtobufFrameSerializer()
- TwilioFrameSerializer(stream_sid)
Session timeout in seconds. If set, triggers timeout event when no activity is detected
Audio Output Configuration
Enable audio output capabilities
Audio output sample rate in Hz
Number of audio output channels
Voice Activity Detection (VAD)
Enable voice activity detection
Pass through audio during VAD
Voice Activity Detection analyzer. You can set this to either
SileroVADAnalyzer()
or WebRTCVADAnalyzer()
. SileroVADAnalyzer is the
recommended option. Learn more about the
SileroVADAnalyzer.
Basic Usage
Check out the Twilio Chatbot example to see how to use the FastAPI transport in a phone application.
Event Callbacks
FastAPIWebsocketTransport
provides callbacks for handling client connection events. Register callbacks using the @transport.event_handler()
decorator.
Connection Events
Called when a client connects to the WebSocket endpoint.
Parameters:
transport
: The FastAPIWebsocketTransport instanceclient
: FastAPI WebSocket connection object
Called when a client disconnects from the WebSocket endpoint.
Parameters:
transport
: The FastAPIWebsocketTransport instanceclient
: FastAPI WebSocket connection object
Called when a session times out (if session_timeout is configured).
Parameters:
transport
: The FastAPIWebsocketTransport instanceclient
: FastAPI WebSocket connection object
Frame Types
Input Frames
Raw audio data from the WebSocket client
Output Frames
Audio data to be sent to the WebSocket client
Notes
- Integrates with FastAPI web applications
- Supports real-time audio communication
- Handles WebSocket connection management
- Provides voice activity detection
- Supports session timeouts
- All callbacks are asynchronous
- Compatible with various frame serializers