adk-realtime 3.0.0

Real-time bidirectional audio/video streaming for Rust Agent Development Kit (ADK-Rust) agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Configuration types for realtime sessions.

use crate::audio::AudioEncoding;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::ops::{Deref, DerefMut};

/// Controls how the realtime session handles user interruptions during agent
/// audio output.
///
/// When set to [`Automatic`](InterruptionDetection::Automatic), the session
/// uses voice activity detection to detect user speech onset and immediately
/// cancels the current agent audio output, enabling natural conversational
/// turn-taking.
///
/// When set to [`Manual`](InterruptionDetection::Manual) (the default), the
/// session relies on explicit API calls (e.g. `response.cancel`) to signal
/// that the user is interrupting. This gives the application full control
/// over interruption behavior.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InterruptionDetection {
    /// Rely on explicit API calls to signal interruptions.
    ///
    /// The application is responsible for detecting user speech and calling
    /// the appropriate cancellation method on the session. No automatic
    /// voice activity detection is performed for interruption purposes.
    #[default]
    Manual,
    /// Detect user speech onset and cancel the current agent audio output.
    ///
    /// The session monitors incoming audio for voice activity. When user
    /// speech is detected while the agent is producing audio, the agent's
    /// audio output is automatically cancelled, allowing the user to
    /// take the conversational turn.
    Automatic,
}

/// Voice Activity Detection mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum VadMode {
    /// Server-side VAD (default for most providers).
    #[default]
    ServerVad,
    /// Semantic VAD (OpenAI-specific).
    SemanticVad,
    /// No automatic VAD - manual turn management.
    ///
    /// **The application becomes responsible for turn detection.** On Gemini
    /// Live this sends
    /// `setup.realtimeInputConfig.automaticActivityDetection.disabled = true`,
    /// after which the server performs no turn detection at all and the client
    /// must send `activityStart` / `activityEnd` itself, via the
    /// `ActivitySignaller` that a Gemini session offers only in this mode.
    /// Selecting this and never signalling leaves a session that never takes
    /// a turn.
    None,
}

/// VAD configuration options.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VadConfig {
    /// VAD mode to use.
    #[serde(rename = "type")]
    pub mode: VadMode,
    /// Silence duration (ms) before considering speech ended.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub silence_duration_ms: Option<u32>,
    /// Detection threshold (0.0 - 1.0).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f32>,
    /// Prefix padding (ms) to include before detected speech.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix_padding_ms: Option<u32>,
    /// Whether to interrupt the model when user starts speaking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interrupt_response: Option<bool>,
    /// Eagerness of turn detection (OpenAI-specific).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub eagerness: Option<String>,
}

impl Default for VadConfig {
    fn default() -> Self {
        Self {
            mode: VadMode::ServerVad,
            silence_duration_ms: Some(500),
            threshold: None,
            prefix_padding_ms: None,
            interrupt_response: Some(true),
            eagerness: None,
        }
    }
}

impl VadConfig {
    /// Create a server VAD config with default settings.
    pub fn server_vad() -> Self {
        Self::default()
    }

    /// Create a semantic VAD config (OpenAI).
    pub fn semantic_vad() -> Self {
        Self { mode: VadMode::SemanticVad, ..Default::default() }
    }

    /// Create a config with VAD disabled.
    pub fn disabled() -> Self {
        Self { mode: VadMode::None, ..Default::default() }
    }

    /// Set silence duration threshold.
    pub fn with_silence_duration(mut self, ms: u32) -> Self {
        self.silence_duration_ms = Some(ms);
        self
    }

    /// Set whether to interrupt on user speech.
    pub fn with_interrupt(mut self, interrupt: bool) -> Self {
        self.interrupt_response = Some(interrupt);
        self
    }
}

/// Whether the model waits for a tool's result before it continues the conversation.
///
/// Gemini Live sends it as the function declaration's `behavior`. The OpenAI Realtime API
/// has no such setting and ignores it.
///
/// # Example
///
/// ```rust
/// use adk_realtime::config::{ToolBehavior, ToolDefinition};
///
/// let notify = ToolDefinition::new("notify_team").with_behavior(ToolBehavior::NonBlocking);
/// assert_eq!(notify.behavior, Some(ToolBehavior::NonBlocking));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolBehavior {
    /// The model pauses until the result arrives, then answers with it in the same turn.
    Blocking,
    /// The model keeps talking while the tool runs and takes the result when it arrives,
    /// usually in a later turn.
    NonBlocking,
}

/// Tool/function definition for realtime sessions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// Tool name.
    pub name: String,
    /// Tool description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// JSON Schema for parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Value>,
    /// Whether the model waits for this tool's result.
    ///
    /// `None` lets the session decide: on `gemini-3.8-live` the tool is declared
    /// [`Blocking`](ToolBehavior::Blocking), so a turn that calls it answers with its result;
    /// on `gemini-3.8-live-extended-thinking`, which accepts only non-blocking calls,
    /// [`NonBlocking`](ToolBehavior::NonBlocking); on other models no behavior is declared
    /// and the model's own default applies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub behavior: Option<ToolBehavior>,
}

impl ToolDefinition {
    /// Create a new tool definition.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into(), description: None, parameters: None, behavior: None }
    }

    /// Set whether the model waits for this tool's result.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_realtime::config::{ToolBehavior, ToolDefinition};
    ///
    /// // The model keeps talking while the report is sent.
    /// let send_report =
    ///     ToolDefinition::new("send_report").with_behavior(ToolBehavior::NonBlocking);
    /// assert_eq!(send_report.behavior, Some(ToolBehavior::NonBlocking));
    /// ```
    pub fn with_behavior(mut self, behavior: ToolBehavior) -> Self {
        self.behavior = Some(behavior);
        self
    }

    /// Set the tool description.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set the parameters schema.
    pub fn with_parameters(mut self, schema: Value) -> Self {
        self.parameters = Some(schema);
        self
    }

    /// The [`ToolOrigin`](adk_core::ToolOrigin) of governed calls to the native handler a
    /// [`RealtimeRunner`](crate::RealtimeRunner) registers under this definition:
    /// [`REALTIME_HANDLER_ORIGIN`](crate::runner::REALTIME_HANDLER_ORIGIN) and a digest of
    /// the name, description, and parameters.
    ///
    /// The origin is part of a held call's
    /// [fingerprint](adk_core::ToolConfirmationRequest::fingerprint), so build a pre-approval
    /// for a handler's call with it.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::{RunConfig, ToolApproval, ToolConfirmationRequest};
    /// use adk_realtime::config::ToolDefinition;
    /// use adk_realtime::runner::REALTIME_HANDLER_ORIGIN;
    /// use serde_json::json;
    ///
    /// let refund = ToolDefinition::new("refund").with_description("Refunds an order");
    /// assert_eq!(refund.handler_origin().source, REALTIME_HANDLER_ORIGIN);
    /// let reworded = refund.clone().with_description("Refunds any order");
    /// assert_ne!(refund.handler_origin(), reworded.handler_origin());
    ///
    /// // A runner whose `agent_name` is "voice", in app "shop", acts as this agent.
    /// let acting = RunConfig::default().acting_context_for("shop", "voice", "alice");
    /// let key = ToolConfirmationRequest::new("refund", json!({ "order": "A-1" }))
    ///     .with_origin(refund.handler_origin())
    ///     .with_acting_context(acting)
    ///     .fingerprint();
    /// let config = RunConfig::builder().tool_approval(key, ToolApproval::approve()).build();
    /// assert_eq!(config.tool_approvals.len(), 1);
    /// ```
    pub fn handler_origin(&self) -> adk_core::ToolOrigin {
        let declaration = serde_json::json!({
            "name": self.name,
            "description": self.description,
            "parameters": self.parameters,
        });
        adk_core::ToolOrigin::new(crate::runner::REALTIME_HANDLER_ORIGIN, &declaration, None)
    }
}

/// Configuration for a realtime session.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct RealtimeConfig {
    /// Model to use (provider-specific).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,

    /// System instruction for the agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instruction: Option<String>,

    /// Voice to use for audio output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub voice: Option<String>,

    /// Output modalities: ["text"], ["audio"], or ["text", "audio"].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modalities: Option<Vec<String>>,

    /// Input audio format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_audio_format: Option<AudioEncoding>,

    /// Output audio format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_audio_format: Option<AudioEncoding>,

    /// VAD configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub turn_detection: Option<VadConfig>,

    /// Available tools/functions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<ToolDefinition>>,

    /// Tool selection mode: "auto", "none", "required".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<String>,

    /// Whether to include input audio transcription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_audio_transcription: Option<TranscriptionConfig>,

    /// Temperature for response generation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// Maximum output tokens.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_response_output_tokens: Option<u32>,

    /// Cached content resource name (e.g. `cachedContents/1234`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cached_content: Option<String>,

    /// Interruption detection mode for voice sessions.
    ///
    /// Controls whether the session automatically detects user speech to
    /// cancel agent audio output, or relies on explicit API calls.
    /// Defaults to [`Manual`](InterruptionDetection::Manual) when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interruption_detection: Option<InterruptionDetection>,

    /// Enable emotion-aware ("affective") dialog, where the model adapts its
    /// tone to the user's emotional state. Gemini Live native-audio models only
    /// (requires the v1alpha endpoint); ignored by other providers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub affective_dialog: Option<bool>,

    /// Provider-specific options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra: Option<Value>,
}

/// A delta payload for safely updating an active realtime session.
///
/// Wraps `RealtimeConfig` to prevent struct duplication. Since all fields are
/// `Option<T>` and skip serialization if `None`, omitting fields preserves
/// the server's active state.
///
/// **⚠️ WARNING:** You must construct a *fresh* configuration containing **only**
/// the fields to modify. Wrapping your original startup config will resend
/// immutable fields (like `model`), causing the provider to reject the update.
///
/// This is the idiomatic mechanism for dynamic Finite State Machine (FSM) state
/// transitions, allowing seamless "persona shifts" or tool swaps without
/// dropping the audio connection.
///
/// # Example
///
/// ```rust
/// use adk_realtime::config::{SessionUpdateConfig, RealtimeConfig};
///
/// // Update *only* the instruction mid-session.
/// let delta = SessionUpdateConfig(
///     RealtimeConfig::default().with_instruction("You are now a travel agent.")
/// );
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionUpdateConfig(pub RealtimeConfig);

impl Deref for SessionUpdateConfig {
    type Target = RealtimeConfig;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for SessionUpdateConfig {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl From<RealtimeConfig> for SessionUpdateConfig {
    fn from(config: RealtimeConfig) -> Self {
        Self(config)
    }
}

/// Transcription configuration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TranscriptionConfig {
    /// Transcription model to use.
    pub model: String,
}

impl TranscriptionConfig {
    /// Use whisper-1 for transcription.
    pub fn whisper() -> Self {
        Self { model: "whisper-1".to_string() }
    }
}

impl RealtimeConfig {
    /// Create a new empty configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for RealtimeConfig.
    pub fn builder() -> RealtimeConfigBuilder {
        RealtimeConfigBuilder::new()
    }

    /// Set the model.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Set the system instruction.
    pub fn with_instruction(mut self, instruction: impl Into<String>) -> Self {
        self.instruction = Some(instruction.into());
        self
    }

    /// Set the voice.
    pub fn with_voice(mut self, voice: impl Into<String>) -> Self {
        self.voice = Some(voice.into());
        self
    }

    /// Set output modalities.
    pub fn with_modalities(mut self, modalities: Vec<String>) -> Self {
        self.modalities = Some(modalities);
        self
    }

    /// Enable text and audio output.
    pub fn with_text_and_audio(mut self) -> Self {
        self.modalities = Some(vec!["text".to_string(), "audio".to_string()]);
        self
    }

    /// Enable audio-only output.
    pub fn with_audio_only(mut self) -> Self {
        self.modalities = Some(vec!["audio".to_string()]);
        self
    }

    /// Set VAD configuration.
    pub fn with_vad(mut self, vad: VadConfig) -> Self {
        self.turn_detection = Some(vad);
        self
    }

    /// Enable server-side VAD with default settings.
    pub fn with_server_vad(self) -> Self {
        self.with_vad(VadConfig::server_vad())
    }

    /// Disable automatic VAD, taking ownership of turn detection.
    ///
    /// See [`VadMode::None`] — on Gemini Live this is also what unlocks client
    /// `activityStart` / `activityEnd` signalling, which the protocol permits
    /// only while server-side detection is disabled.
    pub fn without_vad(mut self) -> Self {
        self.turn_detection = Some(VadConfig::disabled());
        self
    }

    /// Add a tool definition.
    pub fn with_tool(mut self, tool: ToolDefinition) -> Self {
        self.tools.get_or_insert_with(Vec::new).push(tool);
        self
    }

    /// Set multiple tools.
    pub fn with_tools(mut self, tools: Vec<ToolDefinition>) -> Self {
        self.tools = Some(tools);
        self
    }

    /// Enable input audio transcription.
    pub fn with_transcription(mut self) -> Self {
        self.input_audio_transcription = Some(TranscriptionConfig::whisper());
        self
    }

    /// Set temperature.
    pub fn with_temperature(mut self, temp: f32) -> Self {
        self.temperature = Some(temp);
        self
    }

    /// Enable emotion-aware ("affective") dialog. Only honored by Gemini Live
    /// native-audio models (v1alpha); a no-op for other providers/models.
    pub fn with_affective_dialog(mut self, enabled: bool) -> Self {
        self.affective_dialog = Some(enabled);
        self
    }

    /// Pins the spoken language (BCP-47, e.g. `"en-US"`).
    ///
    /// Gemini Live sends it as `speechConfig.languageCode`, which steers both the voice and
    /// the input/output transcription; without it the model detects the language per turn
    /// and short or accented utterances can be transcribed in the wrong one. Gemini
    /// native-audio output models choose the language automatically and do not honor it.
    ///
    /// Stored under `extra.language_code`. An `extra` value that is not a JSON object is
    /// replaced. The OpenAI Realtime session copies every `extra` key into its
    /// `session.update`, so set it only for a Gemini Live model.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_realtime::RealtimeConfig;
    ///
    /// let config = RealtimeConfig::default().with_voice("Kore").with_language("en-US");
    /// assert_eq!(config.extra.unwrap()["language_code"], "en-US");
    /// ```
    pub fn with_language(self, code: impl Into<String>) -> Self {
        self.with_extra("language_code", Value::String(code.into()))
    }

    /// Sets how much the Gemini Live model reasons, as `generationConfig.thinkingConfig`.
    ///
    /// [`Effort::Low`](adk_core::Effort::Low), `Medium` and `High` are sent as the thinking
    /// levels `low`, `medium` and `high`. `gemini-3.8-live-extended-thinking` requires a
    /// level (its server closes a setup without one with 1007), so ADK sends `medium` unless
    /// you set one. `gemini-3.1-flash-live-preview` takes one. `gemini-3.8-live` reasons on
    /// its own and closes the socket with 1007 on one, so it is not sent there.
    ///
    /// Stored under `extra.thinking_level`. An `extra` value that is not a JSON object is
    /// replaced. The OpenAI Realtime session copies every `extra` key into its
    /// `session.update`, so set it only for a Gemini Live model.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_core::Effort;
    /// use adk_realtime::RealtimeConfig;
    ///
    /// let config = RealtimeConfig::default().with_thinking_level(Effort::Medium);
    /// assert_eq!(config.extra.unwrap()["thinking_level"], "medium");
    /// ```
    pub fn with_thinking_level(self, effort: adk_core::Effort) -> Self {
        self.with_extra("thinking_level", Value::String(effort.as_str().to_string()))
    }

    /// Turns on Gemini Live context window compression (a sliding window).
    ///
    /// The server drops the oldest turns once the context reaches `trigger_tokens` (default:
    /// 80% of the model's context window). Google documents that without it a session ends
    /// after about 15 minutes of audio, or about 2 once video frames are sent, and that with
    /// it the session has no length limit (each connection still lasts about 10 minutes).
    ///
    /// Stored under `extra.context_window_compression`: `true`, or
    /// `{"trigger_tokens": n}` when a threshold is given. The object form also accepts
    /// `target_tokens`, the size to cut back to (default: half of `trigger_tokens`). An
    /// `extra` value that is not a JSON object is replaced. The OpenAI Realtime session
    /// copies every `extra` key into its `session.update`, so set it only for a Gemini Live
    /// model.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_realtime::RealtimeConfig;
    ///
    /// let config = RealtimeConfig::default().with_context_window_compression(None);
    /// assert_eq!(config.extra.unwrap()["context_window_compression"], true);
    /// ```
    pub fn with_context_window_compression(self, trigger_tokens: Option<u64>) -> Self {
        let value = match trigger_tokens {
            Some(tokens) => serde_json::json!({ "trigger_tokens": tokens }),
            None => Value::Bool(true),
        };
        self.with_extra("context_window_compression", value)
    }

    /// Sets one key in `extra`, keeping the others; a non-object `extra` is replaced.
    fn with_extra(mut self, key: &str, value: Value) -> Self {
        let mut extra = match self.extra.take() {
            Some(Value::Object(map)) => map,
            _ => serde_json::Map::new(),
        };
        extra.insert(key.to_string(), value);
        self.extra = Some(Value::Object(extra));
        self
    }

    /// Set cached content resource.
    pub fn with_cached_content(mut self, content: impl Into<String>) -> Self {
        self.cached_content = Some(content.into());
        self
    }

    /// Set the interruption detection mode.
    ///
    /// See [`InterruptionDetection`] for details on each variant.
    pub fn with_interruption_detection(mut self, mode: InterruptionDetection) -> Self {
        self.interruption_detection = Some(mode);
        self
    }

    /// Enable automatic interruption detection.
    ///
    /// The session will detect user speech onset and cancel the current
    /// agent audio output automatically.
    pub fn with_automatic_interruption(self) -> Self {
        self.with_interruption_detection(InterruptionDetection::Automatic)
    }
}

/// Builder for RealtimeConfig.
#[derive(Debug, Clone, Default)]
pub struct RealtimeConfigBuilder {
    config: RealtimeConfig,
}

impl RealtimeConfigBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the model.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.config.model = Some(model.into());
        self
    }

    /// Set the system instruction.
    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
        self.config.instruction = Some(instruction.into());
        self
    }

    /// Set the voice.
    pub fn voice(mut self, voice: impl Into<String>) -> Self {
        self.config.voice = Some(voice.into());
        self
    }

    /// Enable VAD.
    pub fn vad_enabled(mut self, enabled: bool) -> Self {
        if enabled {
            self.config.turn_detection = Some(VadConfig::server_vad());
        } else {
            self.config.turn_detection = Some(VadConfig::disabled());
        }
        self
    }

    /// Set VAD configuration.
    pub fn vad(mut self, vad: VadConfig) -> Self {
        self.config.turn_detection = Some(vad);
        self
    }

    /// Add a tool.
    pub fn tool(mut self, tool: ToolDefinition) -> Self {
        self.config.tools.get_or_insert_with(Vec::new).push(tool);
        self
    }

    /// Set temperature.
    pub fn temperature(mut self, temp: f32) -> Self {
        self.config.temperature = Some(temp);
        self
    }

    /// Set cached content resource.
    pub fn cached_content(mut self, content: impl Into<String>) -> Self {
        self.config.cached_content = Some(content.into());
        self
    }

    /// Set the interruption detection mode.
    pub fn interruption_detection(mut self, mode: InterruptionDetection) -> Self {
        self.config.interruption_detection = Some(mode);
        self
    }

    /// Build the configuration.
    pub fn build(self) -> RealtimeConfig {
        self.config
    }
}