Skip to main content

dynamo_protocols/types/
realtime.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Re-exports upstream async-openai realtime types and adds a narrow wrapper for
5// Dynamo-specific client events without replacing the upstream public enum.
6
7pub use async_openai::types::realtime::*;
8use serde::{Deserialize, Serialize};
9
10/// Append UTF-8 text to the current incremental input.
11///
12/// This is a Dynamo extension for clients that receive text progressively,
13/// such as cascaded ASR -> LLM pipelines. The event name follows NVIDIA Speech
14/// NIM's realtime TTS protocol. An append does not finalize a conversation item
15/// or request a response.
16#[derive(Debug, Serialize, Deserialize)]
17pub struct RealtimeClientEventInputTextAppend {
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub event_id: Option<String>,
20    pub text: String,
21}
22
23/// Finalize the current incremental text as a user conversation item.
24#[derive(Debug, Default, Serialize, Deserialize)]
25pub struct RealtimeClientEventInputTextCommit {
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub event_id: Option<String>,
28}
29
30/// Discard the current incremental text without creating an item.
31///
32/// This extends NVIDIA Speech NIM's append/commit lifecycle so clients can
33/// replace revisable ASR hypotheses.
34#[derive(Debug, Default, Serialize, Deserialize)]
35pub struct RealtimeClientEventInputTextClear {
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub event_id: Option<String>,
38}
39
40/// Replace the chat completion request fields applied to every response in the session.
41///
42/// OpenAI Realtime sessions have no sampling or chat template fields, so this
43/// Dynamo extension carries fields such as `temperature`, `top_p`, `seed`, and
44/// `chat_template_kwargs` to text workers that render chat completions. Workers
45/// validate the fields they support.
46#[derive(Debug, Default, Serialize, Deserialize)]
47pub struct RealtimeClientEventSessionChatCompletionOptionsUpdate {
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub event_id: Option<String>,
50    pub chat_completion_options: serde_json::Map<String, serde_json::Value>,
51}
52
53/// Experimental Dynamo extensions to the OpenAI Realtime client event set.
54///
55/// These events are not part of the OpenAI Realtime API and may change before
56/// stabilization.
57#[derive(Debug, Serialize, Deserialize)]
58#[serde(tag = "type")]
59pub enum RealtimeClientEventExtension {
60    #[serde(rename = "input_text.append")]
61    InputTextAppend(RealtimeClientEventInputTextAppend),
62    #[serde(rename = "input_text.commit")]
63    InputTextCommit(RealtimeClientEventInputTextCommit),
64    #[serde(rename = "input_text.clear")]
65    InputTextClear(RealtimeClientEventInputTextClear),
66    #[serde(rename = "session.chat_completion_options.update")]
67    SessionChatCompletionOptionsUpdate(RealtimeClientEventSessionChatCompletionOptionsUpdate),
68}
69
70/// OpenAI Realtime client events plus inference-serving extensions from Dynamo.
71#[derive(Debug, Serialize, Deserialize)]
72#[serde(untagged)]
73pub enum DynamoRealtimeClientEvent {
74    OpenAI(RealtimeClientEvent),
75    Extension(RealtimeClientEventExtension),
76}
77
78impl From<RealtimeClientEvent> for DynamoRealtimeClientEvent {
79    fn from(event: RealtimeClientEvent) -> Self {
80        Self::OpenAI(event)
81    }
82}
83
84/// Returns the `type` wire-tag string for a realtime event variant — useful
85/// for logging, error messages, and metric labels that need a stable name
86/// without reserializing the value.
87///
88/// `async-openai` ships an equivalent `crate::traits::EventType` trait, but it
89/// is gated on the `_api` feature, which pulls reqwest / tokio / secrecy /
90/// eventsource-stream into the build. `dynamo-protocols` is types-only by
91/// design (see the Cargo.toml banner), so we mirror the trait shape locally.
92/// If `_api` ever becomes affordable for this crate, swap `pub use
93/// async_openai::traits::EventType;` in here and remove the impls below; call
94/// sites need no changes.
95///
96/// [NOTE] Could be replaced with a serde-introspection helper (e.g. the
97/// `serde_variant` crate) that reads the wire tag from `#[serde(rename)]`
98/// at runtime; deferred until as clean up work.
99pub trait EventType {
100    fn event_type(&self) -> &'static str;
101}
102
103impl EventType for RealtimeClientEvent {
104    fn event_type(&self) -> &'static str {
105        // `RealtimeClientEvent` is not `#[non_exhaustive]`, so a future upstream
106        // variant breaks this match at compile time rather than silently
107        // returning a stale label.
108        match self {
109            RealtimeClientEvent::SessionUpdate(_) => "session.update",
110            RealtimeClientEvent::InputAudioBufferAppend(_) => "input_audio_buffer.append",
111            RealtimeClientEvent::InputAudioBufferCommit(_) => "input_audio_buffer.commit",
112            RealtimeClientEvent::InputAudioBufferClear(_) => "input_audio_buffer.clear",
113            RealtimeClientEvent::ConversationItemCreate(_) => "conversation.item.create",
114            RealtimeClientEvent::ConversationItemRetrieve(_) => "conversation.item.retrieve",
115            RealtimeClientEvent::ConversationItemTruncate(_) => "conversation.item.truncate",
116            RealtimeClientEvent::ConversationItemDelete(_) => "conversation.item.delete",
117            RealtimeClientEvent::ResponseCreate(_) => "response.create",
118            RealtimeClientEvent::ResponseCancel(_) => "response.cancel",
119            RealtimeClientEvent::OutputAudioBufferClear(_) => "output_audio_buffer.clear",
120        }
121    }
122}
123
124impl EventType for RealtimeClientEventExtension {
125    fn event_type(&self) -> &'static str {
126        match self {
127            RealtimeClientEventExtension::InputTextAppend(_) => "input_text.append",
128            RealtimeClientEventExtension::InputTextCommit(_) => "input_text.commit",
129            RealtimeClientEventExtension::InputTextClear(_) => "input_text.clear",
130            RealtimeClientEventExtension::SessionChatCompletionOptionsUpdate(_) => {
131                "session.chat_completion_options.update"
132            }
133        }
134    }
135}
136
137impl EventType for DynamoRealtimeClientEvent {
138    fn event_type(&self) -> &'static str {
139        match self {
140            DynamoRealtimeClientEvent::OpenAI(event) => event.event_type(),
141            DynamoRealtimeClientEvent::Extension(event) => event.event_type(),
142        }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn session_update_accepts_null_turn_detection() {
152        let event: RealtimeClientEvent = serde_json::from_value(serde_json::json!({
153            "type": "session.update",
154            "session": {
155                "type": "transcription",
156                "audio": {
157                    "input": {
158                        "format": { "type": "audio/pcm", "rate": 24000 },
159                        "transcription": { "model": "whisper-1" },
160                        "turn_detection": null
161                    }
162                }
163            }
164        }))
165        .expect("null turn_detection should be accepted");
166
167        let RealtimeClientEvent::SessionUpdate(update) = event else {
168            panic!("expected session.update");
169        };
170        let Session::RealtimeTranscriptionSession(session) = update.session else {
171            panic!("expected transcription session");
172        };
173        assert!(session.audio.input.turn_detection.is_none());
174    }
175
176    #[test]
177    fn text_events_round_trip() {
178        let values = [
179            (
180                serde_json::json!({
181                    "type": "input_text.append",
182                    "event_id": "append-1",
183                    "text": "hello "
184                }),
185                "input_text.append",
186            ),
187            (
188                serde_json::json!({
189                    "type": "input_text.commit",
190                    "event_id": "commit-1"
191                }),
192                "input_text.commit",
193            ),
194            (
195                serde_json::json!({
196                    "type": "input_text.clear",
197                    "event_id": "clear-1"
198                }),
199                "input_text.clear",
200            ),
201            (
202                serde_json::json!({
203                    "type": "session.chat_completion_options.update",
204                    "event_id": "options-1",
205                    "chat_completion_options": {
206                        "temperature": 0.3,
207                        "seed": 7,
208                        "chat_template_kwargs": { "enable_thinking": true }
209                    }
210                }),
211                "session.chat_completion_options.update",
212            ),
213        ];
214
215        for (value, event_type) in values {
216            let event: DynamoRealtimeClientEvent =
217                serde_json::from_value(value.clone()).expect("event should deserialize");
218            assert_eq!(event.event_type(), event_type);
219            assert_eq!(serde_json::to_value(event).unwrap(), value);
220        }
221    }
222
223    #[test]
224    fn text_append_requires_non_null_text() {
225        for value in [
226            serde_json::json!({"type": "input_text.append"}),
227            serde_json::json!({"type": "input_text.append", "text": null}),
228        ] {
229            assert!(serde_json::from_value::<DynamoRealtimeClientEvent>(value).is_err());
230        }
231    }
232
233    #[test]
234    fn chat_completion_options_update_requires_an_object() {
235        for value in [
236            serde_json::json!({"type": "session.chat_completion_options.update"}),
237            serde_json::json!({
238                "type": "session.chat_completion_options.update",
239                "chat_completion_options": [0.3]
240            }),
241        ] {
242            assert!(serde_json::from_value::<DynamoRealtimeClientEvent>(value).is_err());
243        }
244    }
245}