Quick Start
Creating Client Tokens
When your Python backend serves client applications (browsers, mobile apps), create client tokens for secure client-side authentication.Learn more about client tokens and why they’re important for security.
Backend Examples
Connecting
Getting Camera Access
Request access to the user’s camera using your platform’s camera API:Establishing Connection
Connect to the Realtime API with your media stream:base_url(required) - API base URL from clientapi_key(required) - Your Decart API keylocal_track(required) - Video MediaStreamTrack from cameraoptions(required) - RealtimeConnectOptions with:model(required) - Realtime model frommodels.realtime()on_remote_stream(required) - Callback that receives the transformed video streaminitial_state(optional) - ModelState with:prompt- Prompt object (text, enhance)image- Initial image asbytes, URL string, or file path string (used withlive_avatarmodel)
Managing Prompts
Change the transformation style dynamically without reconnecting:prompt: str(required) - Text description of desired styleenhance: bool(optional) - Whether to enhance the prompt (default: True)
None (async method)
Prompt enhancement uses Decart’s AI to expand simple prompts for better results. Disable it if you want full control over the exact prompt.
Unified State Update
Theset() method lets you update the prompt, reference image, or both in a single atomic call. For Lucy 2 (lucy_2_rt), it ensures prompt and image changes are applied together.
SetInput):
prompt: Optional[str]- Text description of desired style (at least one ofpromptorimageis required)enhance: bool- Whether to enhance the prompt (default:True)image: Optional[Union[bytes, str]]- Reference image asbytesor URL string, orNoneto clear
Connection State
Monitor and react to connection state changes:"connecting"— Initial connection in progress"connected"— Connected and ready to send prompts"generating"— Actively generating transformed video (sticky until disconnected)"reconnecting"— Connection was lost unexpectedly; the SDK is automatically retrying"disconnected"— Not connected (initial state, afterdisconnect(), or after reconnect failure)
The SDK automatically reconnects when an unexpected disconnection occurs (e.g., network interruption). During auto-reconnect, the state transitions to
"reconnecting" while the SDK retries with exponential backoff (up to 5 attempts). If all retries fail, the state moves to "disconnected" and an error event is emitted.Error Handling
Handle errors with the error event:InvalidAPIKeyError- API key is invalid or missingWebRTCError- WebRTC connection failedModelNotFoundError- Specified model doesn’t existInvalidInputError- Invalid input parametersDecartSDKError- Base class for all SDK errors
Session Management
Access the current session ID:Session Viewing (Subscribe)
You can let other clients watch an active realtime session as read-only viewers using the subscribe feature. The producer session exposes asubscribe_token that viewers use to connect.
Getting a Subscribe Token
After connecting, the producer’ssubscribe_token is automatically populated:
Subscribing to a Session
Viewers use the subscribe token to receive the transformed video stream in read-only mode:Subscribe clients are receive-only — they cannot send prompts or modify the session. The subscriber sees exactly what the producer’s
on_remote_stream receives.Cleanup
Always disconnect when done to free up resources:Complete Example
Here’s a full application with all features:Best Practices
Use model properties for video constraints
Use model properties for video constraints
Always use the model’s
fps, width, and height properties when requesting camera access to ensure optimal performance and compatibility.Enable prompt enhancement
Enable prompt enhancement
For best results, keep
enhance=True (default) to let Decart’s AI enhance your prompts. Only disable it if you need exact prompt control.Handle connection state changes
Handle connection state changes
Always listen to
connection_change events to update your UI and handle reconnection logic gracefully.Clean up properly
Clean up properly
Always call
disconnect() and stop media streams when done to avoid memory leaks and unnecessary resource usage.API Reference
RealtimeClient.connect(base_url, api_key, local_track, options)
Classmethod that connects to the realtime transformation service.
Parameters:
base_url: str- API base URL (from client.base_url)api_key: str- Your Decart API keylocal_track: MediaStreamTrack- Video track from camera streamoptions: RealtimeConnectOptions- Connection optionsmodel: ModelDefinition- Realtime model frommodels.realtime()on_remote_stream: Callable[[MediaStreamTrack], None]- Callback for transformed videoinitial_state: ModelState(optional) - Initial stateprompt: Prompt- Prompt object (text, enhance)image: Optional[Union[bytes, str]]- Initial image as bytes, URL, or file path (used withlive_avatar) Returns:RealtimeClient- Connected realtime client instance
await realtime_client.set(input)
Updates the prompt, reference image, or both atomically (async method).
Parameters:
input: SetInput- Object with at least one of:prompt: Optional[str]- Text description of desired styleenhance: bool- Whether to enhance the prompt (default:True)image: Optional[Union[bytes, str]]- Reference image, orNoneto clear
None
await realtime_client.set_prompt(prompt, enhance=True)
Changes the transformation style (async method).
Parameters:
prompt: str- Text description of desired styleenhance: bool- Whether to enhance the prompt (default: True)
None
realtime_client.is_connected()
Check if currently connected.
Returns: bool
realtime_client.get_connection_state()
Get current connection state.
Returns: Literal["connected", "connecting", "generating", "reconnecting", "disconnected"]
realtime_client.session_id
The ID of the current realtime inference session.
Type: Optional[str]
realtime_client.subscribe_token
An opaque token that can be shared with other clients to let them watch this session in read-only mode via RealtimeClient.subscribe().
Type: Optional[str]
await realtime_client.disconnect()
Closes the connection and cleans up resources (async method).
Returns: None
await RealtimeClient.subscribe(base_url, api_key, options)
Classmethod that connects to an existing realtime session as a read-only viewer.
Parameters:
base_url: str- API base URL (from client.base_url)api_key: str- Your Decart API keyoptions: SubscribeOptions- Subscribe optionstoken: str- Subscribe token from the producer’srealtime_client.subscribe_tokenon_remote_stream: Callable[[MediaStreamTrack], None]- Callback for the video stream
SubscribeClient - Connected subscribe client
The subscribe client exposes:
is_connected()- Check connection statusget_connection_state()- Get current stateawait disconnect()- Close the connectionon(event, callback)/off(event, callback)- Listen toconnection_changeanderrorevents
Events
connection_change
Fired when connection state changes.
Callback: (state: Literal["connected", "connecting", "generating", "reconnecting", "disconnected"]) -> None
error
Fired when an error occurs.
Callback: (error: DecartSDKError) -> None
generation_tick
Fired periodically during generation with billing information. Use this to track session duration and display usage to users.
Callback: (message: GenerationTickMessage) -> None