livespeech_sdk/types/
events.rs

1//! Event types for the LiveSpeech SDK
2
3use serde::{Deserialize, Serialize};
4
5/// Disconnect reason
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum DisconnectReason {
8    /// Normal disconnection (client initiated)
9    Normal,
10    /// Error occurred
11    Error,
12    /// Connection timeout
13    Timeout,
14    /// Server closed connection
15    ServerClose,
16    /// Max reconnection attempts reached
17    ReconnectFailed,
18}
19
20/// Error codes
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum ErrorCode {
24    ConnectionFailed,
25    ConnectionTimeout,
26    AuthenticationFailed,
27    SessionError,
28    AudioError,
29    StreamingError,
30    SttError,
31    LlmError,
32    TtsError,
33    RateLimit,
34    InternalError,
35    InvalidMessage,
36    UserIdUpdateError,
37}
38
39impl std::fmt::Display for ErrorCode {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        let s = match self {
42            ErrorCode::ConnectionFailed => "connection_failed",
43            ErrorCode::ConnectionTimeout => "connection_timeout",
44            ErrorCode::AuthenticationFailed => "authentication_failed",
45            ErrorCode::SessionError => "session_error",
46            ErrorCode::AudioError => "audio_error",
47            ErrorCode::StreamingError => "streaming_error",
48            ErrorCode::SttError => "stt_error",
49            ErrorCode::LlmError => "llm_error",
50            ErrorCode::TtsError => "tts_error",
51            ErrorCode::RateLimit => "rate_limit",
52            ErrorCode::InternalError => "internal_error",
53            ErrorCode::InvalidMessage => "invalid_message",
54            ErrorCode::UserIdUpdateError => "user_id_update_error",
55        };
56        write!(f, "{}", s)
57    }
58}
59
60/// Connected event
61#[derive(Debug, Clone)]
62pub struct ConnectedEvent {
63    pub connection_id: String,
64    pub timestamp: String,
65}
66
67/// Disconnected event
68#[derive(Debug, Clone)]
69pub struct DisconnectedEvent {
70    pub reason: DisconnectReason,
71    pub code: Option<u16>,
72    pub timestamp: String,
73}
74
75/// Session started event
76#[derive(Debug, Clone)]
77pub struct SessionStartedEvent {
78    pub session_id: String,
79    pub timestamp: String,
80}
81
82/// Session ended event
83#[derive(Debug, Clone)]
84pub struct SessionEndedEvent {
85    pub session_id: String,
86    pub timestamp: String,
87}
88
89/// Ready event - session is ready for audio input
90#[derive(Debug, Clone)]
91pub struct ReadyEvent {
92    pub timestamp: String,
93}
94
95/// User transcript event - user's speech transcription
96#[derive(Debug, Clone)]
97pub struct UserTranscriptEvent {
98    pub text: String,
99    pub timestamp: String,
100}
101
102/// Response event - AI's text response
103#[derive(Debug, Clone)]
104pub struct ResponseEvent {
105    pub text: String,
106    pub is_final: bool,
107    pub timestamp: String,
108}
109
110/// Audio event - AI's audio response
111#[derive(Debug, Clone)]
112pub struct AudioEvent {
113    pub data: Vec<u8>,
114    pub format: String,
115    pub sample_rate: u32,
116    pub timestamp: String,
117}
118
119/// Turn complete event - AI has finished its response turn
120#[derive(Debug, Clone)]
121pub struct TurnCompleteEvent {
122    pub timestamp: String,
123}
124
125/// Tool call event - AI wants to call a function
126/// 
127/// When the AI decides to execute a function you defined in `tools`,
128/// you'll receive this event. You must call `send_tool_response()`
129/// with the function result.
130#[derive(Debug, Clone)]
131pub struct ToolCallEvent {
132    /// Unique ID for this tool call - use with send_tool_response
133    pub id: String,
134    /// Function name to execute
135    pub name: String,
136    /// Function arguments from AI
137    pub args: serde_json::Value,
138    /// Event timestamp
139    pub timestamp: String,
140}
141
142/// User ID updated event - guest messages migrated to user partition
143/// 
144/// When a guest user logs in during a session, call `update_user_id()`
145/// to migrate conversation history. This event confirms the migration.
146#[derive(Debug, Clone)]
147pub struct UserIdUpdatedEvent {
148    /// The new user ID that was set
149    pub user_id: String,
150    /// Number of messages migrated from guest to user partition
151    pub migrated_messages: usize,
152    /// Event timestamp
153    pub timestamp: String,
154}
155
156/// Interrupted event - AI response was interrupted by user speech (barge-in)
157///
158/// This event is emitted when the user starts speaking while the AI is responding.
159/// **Critical**: When you receive this event, immediately clear your audio playback
160/// buffer to stop the AI audio from continuing to play.
161#[derive(Debug, Clone)]
162pub struct InterruptedEvent {
163    /// Event timestamp
164    pub timestamp: String,
165}
166
167/// Error event
168#[derive(Debug, Clone)]
169pub struct ErrorEvent {
170    pub code: ErrorCode,
171    pub message: String,
172    pub details: Option<String>,
173    pub timestamp: String,
174}
175
176/// Reconnecting event
177#[derive(Debug, Clone)]
178pub struct ReconnectingEvent {
179    pub attempt: u32,
180    pub max_attempts: u32,
181    pub delay_ms: u64,
182    pub timestamp: String,
183}
184
185/// LiveSpeech event enum - all events emitted by the SDK
186#[derive(Debug, Clone)]
187pub enum LiveSpeechEvent {
188    Connected(ConnectedEvent),
189    Disconnected(DisconnectedEvent),
190    Reconnecting(ReconnectingEvent),
191    SessionStarted(SessionStartedEvent),
192    SessionEnded(SessionEndedEvent),
193    Ready(ReadyEvent),
194    UserTranscript(UserTranscriptEvent),
195    Response(ResponseEvent),
196    Audio(AudioEvent),
197    TurnComplete(TurnCompleteEvent),
198    ToolCall(ToolCallEvent),
199    UserIdUpdated(UserIdUpdatedEvent),
200    /// AI response was interrupted by user speech (barge-in)
201    Interrupted(InterruptedEvent),
202    Error(ErrorEvent),
203}
204
205/// Type alias for response handler
206pub type ResponseHandler = Box<dyn Fn(&str, bool) + Send + Sync>;
207
208/// Type alias for audio handler
209pub type AudioHandler = Box<dyn Fn(&[u8]) + Send + Sync>;
210
211/// Type alias for error handler
212pub type ErrorHandler = Box<dyn Fn(&ErrorEvent) + Send + Sync>;