1use std::sync::Arc;
7
8use parking_lot::Mutex;
9use serde::{Deserialize, Serialize};
10
11use super::{ContentPart, OutputItem, Response, ResponseId};
12
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(tag = "type")]
19pub enum ResponseStreamEvent {
20 #[serde(rename = "response.created")]
25 ResponseCreated {
26 response: Response,
28 },
29
30 #[serde(rename = "response.in_progress")]
32 ResponseInProgress {
33 response: Response,
35 },
36
37 #[serde(rename = "response.completed")]
39 ResponseCompleted {
40 response: Response,
42 },
43
44 #[serde(rename = "response.failed")]
46 ResponseFailed {
47 response: Response,
49 },
50
51 #[serde(rename = "response.incomplete")]
53 ResponseIncomplete {
54 response: Response,
56 },
57
58 #[serde(rename = "response.output_item.added")]
63 OutputItemAdded {
64 response_id: ResponseId,
66 output_index: usize,
68 item: OutputItem,
70 },
71
72 #[serde(rename = "response.output_item.done")]
74 OutputItemDone {
75 response_id: ResponseId,
77 output_index: usize,
79 item: OutputItem,
81 },
82
83 #[serde(rename = "response.content_part.added")]
88 ContentPartAdded {
89 response_id: ResponseId,
91 item_id: String,
93 output_index: usize,
95 content_index: usize,
97 part: ContentPart,
99 },
100
101 #[serde(rename = "response.content_part.done")]
103 ContentPartDone {
104 response_id: ResponseId,
106 item_id: String,
108 output_index: usize,
110 content_index: usize,
112 part: ContentPart,
114 },
115
116 #[serde(rename = "response.output_text.delta")]
121 OutputTextDelta {
122 response_id: ResponseId,
124 item_id: String,
126 output_index: usize,
128 content_index: usize,
130 delta: String,
132 },
133
134 #[serde(rename = "response.output_text.done")]
136 OutputTextDone {
137 response_id: ResponseId,
139 item_id: String,
141 output_index: usize,
143 content_index: usize,
145 text: String,
147 },
148
149 #[serde(rename = "response.function_call_arguments.delta")]
154 FunctionCallArgumentsDelta {
155 response_id: ResponseId,
157 item_id: String,
159 output_index: usize,
161 delta: String,
163 },
164
165 #[serde(rename = "response.function_call_arguments.done")]
167 FunctionCallArgumentsDone {
168 response_id: ResponseId,
170 item_id: String,
172 output_index: usize,
174 arguments: String,
176 },
177
178 #[serde(rename = "response.reasoning.delta")]
183 ReasoningDelta {
184 response_id: ResponseId,
186 item_id: String,
188 output_index: usize,
190 delta: String,
192 },
193
194 #[serde(rename = "response.reasoning.done")]
196 ReasoningDone {
197 response_id: ResponseId,
199 item_id: String,
201 output_index: usize,
203 item: OutputItem,
205 },
206
207 #[serde(rename = "response.custom_event")]
215 CustomEvent {
216 response_id: ResponseId,
218 event_type: String,
220 sequence_number: u64,
222 data: serde_json::Value,
224 },
225 #[serde(other)]
227 Unknown,
228}
229
230impl ResponseStreamEvent {
231 #[must_use]
233 pub fn response_id(&self) -> Option<&ResponseId> {
234 match self {
235 Self::ResponseCreated { response, .. }
236 | Self::ResponseInProgress { response, .. }
237 | Self::ResponseCompleted { response, .. }
238 | Self::ResponseFailed { response, .. }
239 | Self::ResponseIncomplete { response, .. } => Some(&response.id),
240
241 Self::OutputItemAdded { response_id, .. }
242 | Self::OutputItemDone { response_id, .. }
243 | Self::ContentPartAdded { response_id, .. }
244 | Self::ContentPartDone { response_id, .. }
245 | Self::OutputTextDelta { response_id, .. }
246 | Self::OutputTextDone { response_id, .. }
247 | Self::FunctionCallArgumentsDelta { response_id, .. }
248 | Self::FunctionCallArgumentsDone { response_id, .. }
249 | Self::ReasoningDelta { response_id, .. }
250 | Self::ReasoningDone { response_id, .. }
251 | Self::CustomEvent { response_id, .. } => Some(response_id),
252 Self::Unknown => None,
253 }
254 }
255
256 pub fn event_type(&self) -> &'static str {
258 match self {
259 Self::ResponseCreated { .. } => "response.created",
260 Self::ResponseInProgress { .. } => "response.in_progress",
261 Self::ResponseCompleted { .. } => "response.completed",
262 Self::ResponseFailed { .. } => "response.failed",
263 Self::ResponseIncomplete { .. } => "response.incomplete",
264 Self::OutputItemAdded { .. } => "response.output_item.added",
265 Self::OutputItemDone { .. } => "response.output_item.done",
266 Self::ContentPartAdded { .. } => "response.content_part.added",
267 Self::ContentPartDone { .. } => "response.content_part.done",
268 Self::OutputTextDelta { .. } => "response.output_text.delta",
269 Self::OutputTextDone { .. } => "response.output_text.done",
270 Self::FunctionCallArgumentsDelta { .. } => "response.function_call_arguments.delta",
271 Self::FunctionCallArgumentsDone { .. } => "response.function_call_arguments.done",
272 Self::ReasoningDelta { .. } => "response.reasoning.delta",
273 Self::ReasoningDone { .. } => "response.reasoning.done",
274 Self::CustomEvent { .. } => "response.custom_event",
275 Self::Unknown => "unknown",
276 }
277 }
278
279 pub fn is_response_event(&self) -> bool {
281 matches!(
282 self,
283 Self::ResponseCreated { .. }
284 | Self::ResponseInProgress { .. }
285 | Self::ResponseCompleted { .. }
286 | Self::ResponseFailed { .. }
287 | Self::ResponseIncomplete { .. }
288 )
289 }
290
291 fn is_terminal(&self) -> bool {
293 matches!(self, Self::ResponseCompleted { .. } | Self::ResponseFailed { .. } | Self::ResponseIncomplete { .. })
294 }
295
296 pub fn is_unknown(&self) -> bool {
298 matches!(self, Self::Unknown)
299 }
300}
301
302#[expect(
304 dead_code,
305 reason = "Intentional compatibility, platform, test, or API-shape suppression."
306)]
307pub type StreamEventCallback = Arc<Mutex<Box<dyn FnMut(&ResponseStreamEvent) + Send>>>;
308
309pub trait StreamEventEmitter: Send {
311 fn emit(&mut self, event: ResponseStreamEvent);
313
314 fn response_created(&mut self, response: Response) {
316 self.emit(ResponseStreamEvent::ResponseCreated { response });
317 }
318
319 fn response_in_progress(&mut self, response: Response) {
321 self.emit(ResponseStreamEvent::ResponseInProgress { response });
322 }
323
324 fn response_completed(&mut self, response: Response) {
326 self.emit(ResponseStreamEvent::ResponseCompleted { response });
327 }
328
329 fn response_failed(&mut self, response: Response) {
331 self.emit(ResponseStreamEvent::ResponseFailed { response });
332 }
333
334 fn output_item_added(&mut self, response_id: &ResponseId, output_index: usize, item: OutputItem) {
336 self.emit(ResponseStreamEvent::OutputItemAdded {
337 response_id: response_id.clone(),
338 output_index,
339 item,
340 });
341 }
342
343 fn output_item_done(&mut self, response_id: &ResponseId, output_index: usize, item: OutputItem) {
345 self.emit(ResponseStreamEvent::OutputItemDone {
346 response_id: response_id.clone(),
347 output_index,
348 item,
349 });
350 }
351
352 fn output_text_delta(
354 &mut self,
355 response_id: &ResponseId,
356 item_id: &str,
357 output_index: usize,
358 content_index: usize,
359 delta: &str,
360 ) {
361 self.emit(ResponseStreamEvent::OutputTextDelta {
362 response_id: response_id.clone(),
363 item_id: item_id.to_string(),
364 output_index,
365 content_index,
366 delta: delta.to_string(),
367 });
368 }
369
370 fn reasoning_delta(&mut self, response_id: &ResponseId, item_id: &str, output_index: usize, delta: &str) {
372 self.emit(ResponseStreamEvent::ReasoningDelta {
373 response_id: response_id.clone(),
374 item_id: item_id.to_string(),
375 output_index,
376 delta: delta.to_string(),
377 });
378 }
379}
380
381#[derive(Debug, Default)]
383pub struct VecStreamEmitter {
384 events: Vec<ResponseStreamEvent>,
385}
386
387impl VecStreamEmitter {
388 pub fn new() -> Self {
390 Self::default()
391 }
392
393 fn events(&self) -> &[ResponseStreamEvent] {
395 &self.events
396 }
397
398 pub fn into_events(self) -> Vec<ResponseStreamEvent> {
400 self.events
401 }
402}
403
404impl StreamEventEmitter for VecStreamEmitter {
405 fn emit(&mut self, event: ResponseStreamEvent) {
406 self.events.push(event);
407 }
408}
409
410#[derive(Debug, Clone, Serialize)]
413pub struct SequencedEvent<'a> {
414 sequence_number: u64,
416 #[serde(flatten)]
418 event: &'a ResponseStreamEvent,
419}
420
421impl<'a> SequencedEvent<'a> {
422 pub fn new(sequence_number: u64, event: &'a ResponseStreamEvent) -> Self {
424 Self { sequence_number, event }
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431
432 #[test]
433 fn test_event_type() {
434 let response = Response::new("resp_1", "gpt-5");
435 let event = ResponseStreamEvent::ResponseCreated { response };
436 assert_eq!(event.event_type(), "response.created");
437 }
438
439 #[test]
440 fn test_terminal_events() {
441 let response = Response::new("resp_1", "gpt-5");
442 let created = ResponseStreamEvent::ResponseCreated { response: response.clone() };
443 let completed = ResponseStreamEvent::ResponseCompleted { response };
444 assert!(!created.is_terminal());
445 assert!(completed.is_terminal());
446 }
447
448 #[test]
449 fn test_vec_emitter() {
450 let mut emitter = VecStreamEmitter::new();
451 let response = Response::new("resp_1", "gpt-5");
452 emitter.response_created(response);
453 assert_eq!(emitter.events().len(), 1);
454 }
455}