openai-protocol 1.7.0

OpenAI-compatible API protocol definitions and types
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
// OpenAI Realtime Session API types
// https://platform.openai.com/docs/api-reference/realtime

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use validator::{Validate, ValidationError};

use crate::{
    common::{Redacted, ResponsePrompt, ToolReference},
    validated::Normalizable,
};

// ============================================================================
// Session Configuration
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
#[validate(schema(function = "validate_session_create_request"))]
pub struct RealtimeSessionCreateRequest {
    #[serde(rename = "type")]
    pub r#type: RealtimeSessionType,
    pub audio: Option<RealtimeAudioConfig>,
    pub include: Option<Vec<RealtimeIncludeOption>>,
    pub instructions: Option<String>,
    pub max_output_tokens: Option<MaxOutputTokens>,
    pub model: Option<String>,
    #[serde(default = "audio")]
    pub output_modalities: Option<Vec<OutputModality>>,
    pub prompt: Option<ResponsePrompt>,
    pub tool_choice: Option<RealtimeToolChoiceConfig>,
    pub tools: Option<RealtimeToolsConfig>,
    pub tracing: Option<RealtimeTracingConfig>,
    pub truncation: Option<RealtimeTruncation>,
}

impl Normalizable for RealtimeSessionCreateRequest {}

fn validate_session_create_request(
    req: &RealtimeSessionCreateRequest,
) -> Result<(), ValidationError> {
    let has_model = req.model.as_deref().is_some_and(|m| !m.trim().is_empty());
    if !has_model {
        return Err(ValidationError::new("model is required"));
    }
    Ok(())
}

// ============================================================================
// Session Object
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeSessionCreateResponse {
    pub client_secret: RealtimeSessionClientSecret,
    #[serde(rename = "type")]
    pub r#type: RealtimeSessionType,
    pub audio: Option<RealtimeAudioConfig>,
    pub include: Option<Vec<RealtimeIncludeOption>>,
    pub instructions: Option<String>,
    pub max_output_tokens: Option<MaxOutputTokens>,
    pub model: Option<String>,
    #[serde(default = "audio")]
    pub output_modalities: Option<Vec<OutputModality>>,
    pub prompt: Option<ResponsePrompt>,
    pub tool_choice: Option<RealtimeToolChoiceConfig>,
    pub tools: Option<Vec<RealtimeToolsConfig>>,
    pub tracing: Option<RealtimeTracingConfig>,
    pub truncation: Option<RealtimeTruncation>,
}

// ============================================================================
// Transcription Session Configuration
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
#[validate(schema(function = "validate_transcription_session_create_request"))]
pub struct RealtimeTranscriptionSessionCreateRequest {
    #[serde(rename = "type")]
    pub r#type: RealtimeTranscriptionSessionType,
    pub audio: Option<RealtimeTranscriptionSessionAudio>,
    pub include: Option<Vec<RealtimeIncludeOption>>,
    pub model: Option<String>,
    pub language: Option<String>,
    pub prompt: Option<String>,
}

impl Normalizable for RealtimeTranscriptionSessionCreateRequest {
    // Use default no-op implementation
}

fn validate_transcription_session_create_request(
    req: &RealtimeTranscriptionSessionCreateRequest,
) -> Result<(), ValidationError> {
    let has_model = req.model.as_deref().is_some_and(|m| !m.trim().is_empty());
    if !has_model {
        return Err(ValidationError::new("model is required"));
    }
    Ok(())
}

// ============================================================================
// Transcription Session Object from Create Response
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeTranscriptionSessionCreateResponse {
    pub id: String,
    pub object: String,
    #[serde(rename = "type")]
    pub r#type: RealtimeTranscriptionSessionType,
    pub audio: Option<RealtimeTranscriptionSessionResponseAudio>,
    pub expires_at: Option<i64>,
    pub include: Option<Vec<RealtimeIncludeOption>>,
}

// ============================================================================
// Audio Formats
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RealtimeAudioFormats {
    #[serde(rename = "audio/pcm")]
    Pcm {
        /// Sample rate. Only 24000 is supported.
        #[serde(skip_serializing_if = "Option::is_none")]
        rate: Option<u32>,
    },
    #[serde(rename = "audio/pcmu")]
    Pcmu,
    #[serde(rename = "audio/pcma")]
    Pcma,
}

// ============================================================================
// Audio Transcription
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioTranscription {
    pub language: Option<String>,
    pub model: Option<String>,
    pub prompt: Option<String>,
}

// ============================================================================
// Noise Reduction
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NoiseReductionType {
    NearField,
    FarField,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoiseReduction {
    #[serde(rename = "type")]
    pub r#type: NoiseReductionType,
}

// ============================================================================
// Turn Detection
// ============================================================================
/// Used only for `semantic_vad` mode. The eagerness of the model to respond.
/// `low` will wait longer for the user to continue speaking, `high` will respond more quickly.
/// `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum SemanticVadEagerness {
    Low,
    Medium,
    High,
    #[default]
    Auto,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum TurnDetection {
    #[serde(rename = "server_vad")]
    ServerVad {
        create_response: Option<bool>,
        idle_timeout_ms: Option<u32>,
        interrupt_response: Option<bool>,
        prefix_padding_ms: Option<u32>,
        silence_duration_ms: Option<u32>,
        threshold: Option<f64>,
    },
    #[serde(rename = "semantic_vad")]
    SemanticVad {
        create_response: Option<bool>,
        eagerness: Option<SemanticVadEagerness>,
        interrupt_response: Option<bool>,
    },
}

/// Turn detection for transcription sessions. Only `server_vad` is currently supported.
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RealtimeTranscriptionSessionTurnDetection {
    #[serde(rename = "server_vad")]
    ServerVad {
        prefix_padding_ms: Option<u32>,
        silence_duration_ms: Option<u32>,
        threshold: Option<f64>,
    },
}

// ============================================================================
// Voice
// ============================================================================

/// Built-in voice name (e.g. "alloy", "ash") or custom voice reference.
///
/// Variant order matters for `#[serde(untagged)]`: a bare JSON string (e.g. `"alloy"`)
/// always deserializes as `BuiltIn`. A JSON object `{"id": "..."}` fails `BuiltIn`
/// and falls through to `Custom`. The two forms are structurally distinct (string vs
/// object) per the OpenAI spec, so there is no ambiguity.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Voice {
    VoiceIDsShared(String),
    Custom { id: String },
}

// ============================================================================
// Output Modality
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OutputModality {
    Text,
    Audio,
}

#[expect(
    clippy::unnecessary_wraps,
    reason = "must return Option to match serde default field type"
)]
fn audio() -> Option<Vec<OutputModality>> {
    Some(vec![OutputModality::Audio])
}

// ============================================================================
// Tracing
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracingConfig {
    pub group_id: Option<String>,
    pub metadata: Option<Value>,
    pub workflow_name: Option<String>,
}

/// The tracing mode. Always `"auto"`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TracingMode {
    #[serde(rename = "auto")]
    Auto,
}

/// Either the string `"auto"` or a granular tracing configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RealtimeTracingConfig {
    Mode(TracingMode),
    Config(TracingConfig),
}

// ============================================================================
// Connector ID
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[expect(
    clippy::enum_variant_names,
    reason = "variant names match OpenAI Realtime API spec"
)]
pub enum ConnectorId {
    ConnectorDropbox,
    ConnectorGmail,
    ConnectorGooglecalendar,
    ConnectorGoogledrive,
    ConnectorMicrosoftteams,
    ConnectorOutlookcalendar,
    ConnectorOutlookemail,
    ConnectorSharepoint,
}

// ============================================================================
// Tools
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RealtimeToolsConfig {
    #[serde(rename = "function")]
    RealtimeFunctionTool {
        description: Option<String>,
        name: Option<String>,
        parameters: Option<Value>,
    },
    #[serde(rename = "mcp")]
    McpTool {
        server_label: String,
        allowed_tools: Option<McpAllowedTools>,
        authorization: Option<Redacted>,
        connector_id: Option<ConnectorId>,
        headers: Option<HashMap<String, Redacted>>,
        require_approval: Option<McpToolApproval>,
        server_description: Option<String>,
        server_url: Option<String>,
    },
}

// ============================================================================
// MCP Tool Filter
// ============================================================================

/// List of allowed tool names or a filter object.
///
/// Variant order matters for `#[serde(untagged)]`: serde tries `List` first
/// (JSON array). A JSON object falls through to `Filter`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum McpAllowedTools {
    List(Vec<String>),
    Filter(McpToolFilter),
}

/// A filter object to specify which tools are allowed.
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolFilter {
    pub read_only: Option<bool>,
    pub tool_names: Option<Vec<String>>,
}

/// Approval policy for MCP tools: a filter object or `"always"`/`"never"`.
///
/// Variant order matters for `#[serde(untagged)]`: serde tries `Setting` first
/// (plain string). A JSON object falls through to `Filter`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum McpToolApproval {
    Setting(McpToolApprovalSetting),
    Filter(McpToolApprovalFilter),
}

/// Single approval policy for all tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum McpToolApprovalSetting {
    Always,
    Never,
}

/// Granular approval filter specifying which tools always/never require approval.
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolApprovalFilter {
    pub always: Option<McpToolFilter>,
    pub never: Option<McpToolFilter>,
}

// ============================================================================
// Tool Choice
// ============================================================================

/// `"none"`, `"auto"`, `"required"`, or a specific function/MCP tool reference.
///
/// Variant order matters for `#[serde(untagged)]`: serde tries `Options` first
/// (plain string). A JSON object fails and falls through to `Reference`.
/// Reuses [`ToolReference`] from `common` for the tagged object forms.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RealtimeToolChoiceConfig {
    Options(ToolChoiceOptions),
    Reference(ToolReference),
}

/// Controls which (if any) tool is called by the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolChoiceOptions {
    None,
    Auto,
    Required,
}

// ============================================================================
// Max Output Tokens
// ============================================================================

/// Integer token limit (1–4096) or `"inf"` for the maximum available tokens.
/// Defaults to `"inf"`.
///
/// Variant order matters for `#[serde(untagged)]`: serde tries `Integer` first.
/// A JSON number succeeds immediately; the string `"inf"` fails `Integer` and
/// falls through to `Inf`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MaxOutputTokens {
    /// An integer between 1 and 4096.
    Integer(u32),
    Inf(InfMarker),
}

impl Default for MaxOutputTokens {
    fn default() -> Self {
        Self::Inf(InfMarker::Inf)
    }
}

/// The literal string `"inf"`. Used by [`MaxOutputTokens::Inf`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum InfMarker {
    #[serde(rename = "inf")]
    Inf,
}

// ============================================================================
// Truncation
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TruncationTokenLimits {
    pub post_instructions: Option<u32>,
}

/// The retention ratio truncation type. Always `"retention_ratio"`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RetentionRatioTruncationType {
    #[serde(rename = "retention_ratio")]
    RetentionRatio,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetentionRatioTruncation {
    pub retention_ratio: f64,
    #[serde(rename = "type")]
    pub r#type: RetentionRatioTruncationType,
    pub token_limits: Option<TruncationTokenLimits>,
}

/// The truncation mode.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TruncationMode {
    #[default]
    Auto,
    Disabled,
}

/// `"auto"`, `"disabled"`, or a retention ratio configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RealtimeTruncation {
    Mode(TruncationMode),
    RetentionRatio(RetentionRatioTruncation),
}

// ============================================================================
// Client Secret
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
#[validate(schema(function = "validate_client_secret_create_request"))]
pub struct RealtimeClientSecretCreateRequest {
    pub session: RealtimeSessionCreateRequest,
}

impl Normalizable for RealtimeClientSecretCreateRequest {}

fn validate_client_secret_create_request(
    req: &RealtimeClientSecretCreateRequest,
) -> Result<(), ValidationError> {
    let has_model = req
        .session
        .model
        .as_deref()
        .is_some_and(|m| !m.trim().is_empty());
    if !has_model {
        return Err(ValidationError::new("session.model is required"));
    }
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeSessionClientSecret {
    pub expires_at: i64,
    pub value: Redacted,
}

// ============================================================================
// Audio Configuration
// ============================================================================

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeAudioConfigInput {
    pub format: Option<RealtimeAudioFormats>,
    pub noise_reduction: Option<NoiseReduction>,
    pub transcription: Option<AudioTranscription>,
    pub turn_detection: Option<TurnDetection>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeAudioConfigOutput {
    pub format: Option<RealtimeAudioFormats>,
    pub speed: Option<f64>,
    pub voice: Option<Voice>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeAudioConfig {
    pub input: Option<RealtimeAudioConfigInput>,
    pub output: Option<RealtimeAudioConfigOutput>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeTranscriptionSessionAudio {
    pub input: Option<RealtimeAudioConfigInput>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeTranscriptionSessionResponseAudio {
    pub input: Option<RealtimeTranscriptionSessionResponseAudioConfigInput>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeTranscriptionSessionResponseAudioConfigInput {
    pub format: Option<RealtimeAudioFormats>,
    pub noise_reduction: Option<NoiseReduction>,
    pub transcription: Option<AudioTranscription>,
    pub turn_detection: Option<RealtimeTranscriptionSessionTurnDetection>,
}

// ============================================================================
// Include Options
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RealtimeIncludeOption {
    #[serde(rename = "item.input_audio_transcription.logprobs")]
    InputAudioTranscriptionLogprobs,
}

// ============================================================================
// Session Type
// ============================================================================

/// The type of session. Always `"realtime"` for the Realtime API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RealtimeSessionType {
    #[serde(rename = "realtime")]
    Realtime,
}

// ============================================================================
// TranscriptionSession Type
// ============================================================================

/// The type of session. Always `"transcription"` for the Realtime API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RealtimeTranscriptionSessionType {
    #[serde(rename = "transcription")]
    Transcription,
}