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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! Constructors and streaming context builders for ServerEvent
//!
//! # One-shot events
//!
//! Simple events are constructed via associated functions on `ServerEvent`:
//!
//! ```ignore
//! ServerEvent::session_created("evt_1", config)
//! ServerEvent::error_event("evt_2", error)
//! ```
//!
//! # Streaming events (hierarchical context builders)
//!
//! Response-streaming events share stable fields (`response_id`, `item_id`,
//! `output_index`, `content_index`). Context builders capture this shared
//! state and can be reused across many events — only `event_id` varies per call:
//!
//! ```ignore
//! // One-shot chaining:
//! ResponseEventBuilder::new("resp_1")
//!     .for_item("item_1", 0)
//!     .for_content(0)
//!     .output_text_delta("evt_1", "Hello")
//!
//! // Streaming hot path — reuse the context, no rebuild:
//! let ctx = ResponseEventBuilder::new("resp_1")
//!     .for_item("item_1", 0)
//!     .for_content(0);
//! for chunk in chunks {
//!     send(ctx.output_text_delta(next_event_id(), chunk));
//! }
//! ```

use crate::{
    realtime_conversation::RealtimeConversationItem,
    realtime_events::{
        Conversation, LogProbProperties, RealtimeError, RealtimeRateLimit, ResponseContentPart,
        ServerEvent, SessionConfig, TranscriptionError, TranscriptionUsage,
    },
    realtime_response::RealtimeResponse,
};

// ============================================================================
// ServerEvent associated constructors (one-shot events)
// ============================================================================

impl ServerEvent {
    // ---- Session events ----

    /// Build a `session.created` event.
    pub fn session_created(event_id: impl Into<String>, session: SessionConfig) -> Self {
        Self::SessionCreated {
            event_id: event_id.into(),
            session: Box::new(session),
        }
    }

    /// Build a `session.updated` event.
    pub fn session_updated(event_id: impl Into<String>, session: SessionConfig) -> Self {
        Self::SessionUpdated {
            event_id: event_id.into(),
            session: Box::new(session),
        }
    }

    // ---- Conversation events ----

    /// Build a `conversation.created` event.
    pub fn conversation_created(event_id: impl Into<String>, conversation: Conversation) -> Self {
        Self::ConversationCreated {
            event_id: event_id.into(),
            conversation,
        }
    }

    /// Build a `conversation.item.created` event.
    pub fn conversation_item_created(
        event_id: impl Into<String>,
        previous_item_id: Option<String>,
        item: RealtimeConversationItem,
    ) -> Self {
        Self::ConversationItemCreated {
            event_id: event_id.into(),
            previous_item_id,
            item,
        }
    }

    /// Build a `conversation.item.added` event.
    pub fn conversation_item_added(
        event_id: impl Into<String>,
        previous_item_id: Option<String>,
        item: RealtimeConversationItem,
    ) -> Self {
        Self::ConversationItemAdded {
            event_id: event_id.into(),
            previous_item_id,
            item,
        }
    }

    /// Build a `conversation.item.done` event.
    pub fn conversation_item_done(
        event_id: impl Into<String>,
        previous_item_id: Option<String>,
        item: RealtimeConversationItem,
    ) -> Self {
        Self::ConversationItemDone {
            event_id: event_id.into(),
            previous_item_id,
            item,
        }
    }

    /// Build a `conversation.item.deleted` event.
    pub fn conversation_item_deleted(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
    ) -> Self {
        Self::ConversationItemDeleted {
            event_id: event_id.into(),
            item_id: item_id.into(),
        }
    }

    /// Build a `conversation.item.retrieved` event.
    pub fn conversation_item_retrieved(
        event_id: impl Into<String>,
        item: RealtimeConversationItem,
    ) -> Self {
        Self::ConversationItemRetrieved {
            event_id: event_id.into(),
            item,
        }
    }

    /// Build a `conversation.item.truncated` event.
    pub fn conversation_item_truncated(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        content_index: u32,
        audio_end_ms: u32,
    ) -> Self {
        Self::ConversationItemTruncated {
            event_id: event_id.into(),
            item_id: item_id.into(),
            content_index,
            audio_end_ms,
        }
    }

    // ---- Input audio transcription events ----

    /// Build a `conversation.item.input_audio_transcription.completed` event.
    pub fn input_audio_transcription_completed(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        content_index: u32,
        transcript: impl Into<String>,
        usage: TranscriptionUsage,
    ) -> Self {
        Self::InputAudioTranscriptionCompleted {
            event_id: event_id.into(),
            item_id: item_id.into(),
            content_index,
            transcript: transcript.into(),
            logprobs: None,
            usage,
        }
    }

    /// Build a `conversation.item.input_audio_transcription.completed` event with logprobs.
    pub fn input_audio_transcription_completed_with_logprobs(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        content_index: u32,
        transcript: impl Into<String>,
        usage: TranscriptionUsage,
        logprobs: Vec<LogProbProperties>,
    ) -> Self {
        Self::InputAudioTranscriptionCompleted {
            event_id: event_id.into(),
            item_id: item_id.into(),
            content_index,
            transcript: transcript.into(),
            logprobs: Some(logprobs),
            usage,
        }
    }

    /// Build a `conversation.item.input_audio_transcription.delta` event.
    pub fn input_audio_transcription_delta(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        content_index: Option<u32>,
        delta: Option<String>,
        logprobs: Option<Vec<LogProbProperties>>,
    ) -> Self {
        Self::InputAudioTranscriptionDelta {
            event_id: event_id.into(),
            item_id: item_id.into(),
            content_index,
            delta,
            logprobs,
        }
    }

    /// Build a `conversation.item.input_audio_transcription.failed` event.
    pub fn input_audio_transcription_failed(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        content_index: u32,
        error: TranscriptionError,
    ) -> Self {
        Self::InputAudioTranscriptionFailed {
            event_id: event_id.into(),
            item_id: item_id.into(),
            content_index,
            error,
        }
    }

    /// Build a `conversation.item.input_audio_transcription.segment` event.
    #[expect(clippy::too_many_arguments)]
    pub fn input_audio_transcription_segment(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        content_index: u32,
        text: impl Into<String>,
        id: impl Into<String>,
        speaker: impl Into<String>,
        start: f32,
        end: f32,
    ) -> Self {
        Self::InputAudioTranscriptionSegment {
            event_id: event_id.into(),
            item_id: item_id.into(),
            content_index,
            text: text.into(),
            id: id.into(),
            speaker: speaker.into(),
            start,
            end,
        }
    }

    // ---- Input audio buffer events ----

    /// Build an `input_audio_buffer.cleared` event.
    pub fn input_audio_buffer_cleared(event_id: impl Into<String>) -> Self {
        Self::InputAudioBufferCleared {
            event_id: event_id.into(),
        }
    }

    /// Build an `input_audio_buffer.committed` event.
    pub fn input_audio_buffer_committed(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        previous_item_id: Option<String>,
    ) -> Self {
        Self::InputAudioBufferCommitted {
            event_id: event_id.into(),
            previous_item_id,
            item_id: item_id.into(),
        }
    }

    /// Build an `input_audio_buffer.speech_started` event.
    pub fn input_audio_buffer_speech_started(
        event_id: impl Into<String>,
        audio_start_ms: u32,
        item_id: impl Into<String>,
    ) -> Self {
        Self::InputAudioBufferSpeechStarted {
            event_id: event_id.into(),
            audio_start_ms,
            item_id: item_id.into(),
        }
    }

    /// Build an `input_audio_buffer.speech_stopped` event.
    pub fn input_audio_buffer_speech_stopped(
        event_id: impl Into<String>,
        audio_end_ms: u32,
        item_id: impl Into<String>,
    ) -> Self {
        Self::InputAudioBufferSpeechStopped {
            event_id: event_id.into(),
            audio_end_ms,
            item_id: item_id.into(),
        }
    }

    /// Build an `input_audio_buffer.timeout_triggered` event.
    pub fn input_audio_buffer_timeout_triggered(
        event_id: impl Into<String>,
        audio_start_ms: u32,
        audio_end_ms: u32,
        item_id: impl Into<String>,
    ) -> Self {
        Self::InputAudioBufferTimeoutTriggered {
            event_id: event_id.into(),
            audio_start_ms,
            audio_end_ms,
            item_id: item_id.into(),
        }
    }

    /// Build an `input_audio_buffer.dtmf_event_received` event.
    ///
    /// DTMF events have no `event_id` per the OpenAI spec.
    pub fn dtmf_event_received(event: impl Into<String>, received_at: i64) -> Self {
        Self::InputAudioBufferDtmfEventReceived {
            event: event.into(),
            received_at,
        }
    }

    // ---- MCP list tools events ----

    /// Build an `mcp_list_tools.in_progress` event.
    pub fn mcp_list_tools_in_progress(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
    ) -> Self {
        Self::McpListToolsInProgress {
            event_id: event_id.into(),
            item_id: item_id.into(),
        }
    }

    /// Build an `mcp_list_tools.completed` event.
    pub fn mcp_list_tools_completed(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
    ) -> Self {
        Self::McpListToolsCompleted {
            event_id: event_id.into(),
            item_id: item_id.into(),
        }
    }

    /// Build an `mcp_list_tools.failed` event.
    pub fn mcp_list_tools_failed(event_id: impl Into<String>, item_id: impl Into<String>) -> Self {
        Self::McpListToolsFailed {
            event_id: event_id.into(),
            item_id: item_id.into(),
        }
    }

    // ---- MCP call lifecycle events ----

    /// Build a `response.mcp_call.in_progress` event.
    pub fn mcp_call_in_progress(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        output_index: u32,
    ) -> Self {
        Self::ResponseMcpCallInProgress {
            event_id: event_id.into(),
            output_index,
            item_id: item_id.into(),
        }
    }

    /// Build a `response.mcp_call.completed` event.
    pub fn mcp_call_completed(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        output_index: u32,
    ) -> Self {
        Self::ResponseMcpCallCompleted {
            event_id: event_id.into(),
            output_index,
            item_id: item_id.into(),
        }
    }

    /// Build a `response.mcp_call.failed` event.
    pub fn mcp_call_failed(
        event_id: impl Into<String>,
        item_id: impl Into<String>,
        output_index: u32,
    ) -> Self {
        Self::ResponseMcpCallFailed {
            event_id: event_id.into(),
            output_index,
            item_id: item_id.into(),
        }
    }

    // ---- Rate limits ----

    /// Build a `rate_limits.updated` event.
    pub fn rate_limits_updated(
        event_id: impl Into<String>,
        rate_limits: Vec<RealtimeRateLimit>,
    ) -> Self {
        Self::RateLimitsUpdated {
            event_id: event_id.into(),
            rate_limits,
        }
    }

    // ---- Response lifecycle events ----

    /// Build a `response.created` event.
    pub fn response_created(event_id: impl Into<String>, response: RealtimeResponse) -> Self {
        Self::ResponseCreated {
            event_id: event_id.into(),
            response: Box::new(response),
        }
    }

    /// Build a `response.done` event.
    pub fn response_done(event_id: impl Into<String>, response: RealtimeResponse) -> Self {
        Self::ResponseDone {
            event_id: event_id.into(),
            response: Box::new(response),
        }
    }

    // ---- Error ----

    /// Build an `error` event.
    pub fn error_event(event_id: impl Into<String>, error: RealtimeError) -> Self {
        Self::Error {
            event_id: event_id.into(),
            error,
        }
    }
}

// ============================================================================
// Level 2: ResponseEventBuilder (response_id)
// ============================================================================

/// Reusable context for response-scoped server events.
///
/// Holds `response_id`. Terminal methods take `event_id` per call, so the
/// builder can be reused across many events in a streaming loop.
/// Call `.for_item()` to descend into item-scoped events.
#[derive(Clone, Debug)]
pub struct ResponseEventBuilder {
    response_id: String,
}

impl ResponseEventBuilder {
    /// Create a new response-scoped context.
    pub fn new(response_id: impl Into<String>) -> Self {
        Self {
            response_id: response_id.into(),
        }
    }

    // ---- Transition ----

    /// Descend into item-scoped events.
    pub fn for_item(&self, item_id: impl Into<String>, output_index: u32) -> ItemEventBuilder {
        ItemEventBuilder {
            response_id: self.response_id.clone(),
            item_id: item_id.into(),
            output_index,
        }
    }

    // ---- Output audio buffer events (WebRTC/SIP only) ----

    /// Build an `output_audio_buffer.started` event.
    pub fn output_audio_buffer_started(&self, event_id: impl Into<String>) -> ServerEvent {
        ServerEvent::OutputAudioBufferStarted {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
        }
    }

    /// Build an `output_audio_buffer.stopped` event.
    pub fn output_audio_buffer_stopped(&self, event_id: impl Into<String>) -> ServerEvent {
        ServerEvent::OutputAudioBufferStopped {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
        }
    }

    /// Build an `output_audio_buffer.cleared` event.
    pub fn output_audio_buffer_cleared(&self, event_id: impl Into<String>) -> ServerEvent {
        ServerEvent::OutputAudioBufferCleared {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
        }
    }
}

// ============================================================================
// Level 3: ItemEventBuilder (response_id + item_id + output_index)
// ============================================================================

/// Reusable context for item-scoped server events.
///
/// Holds `response_id`, `item_id`, and `output_index`. Terminal methods take
/// `event_id` per call. Call `.for_content()` to descend into content-scoped events.
#[derive(Clone, Debug)]
pub struct ItemEventBuilder {
    response_id: String,
    item_id: String,
    output_index: u32,
}

impl ItemEventBuilder {
    /// Create a new item-scoped context directly.
    pub fn new(
        response_id: impl Into<String>,
        item_id: impl Into<String>,
        output_index: u32,
    ) -> Self {
        Self {
            response_id: response_id.into(),
            item_id: item_id.into(),
            output_index,
        }
    }

    // ---- Transition ----

    /// Descend into content-scoped events.
    pub fn for_content(&self, content_index: u32) -> ContentEventBuilder {
        ContentEventBuilder {
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index,
        }
    }

    // ---- Response output item events ----

    /// Build a `response.output_item.added` event.
    pub fn output_item_added(
        &self,
        event_id: impl Into<String>,
        item: RealtimeConversationItem,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputItemAdded {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            output_index: self.output_index,
            item,
        }
    }

    /// Build a `response.output_item.done` event.
    pub fn output_item_done(
        &self,
        event_id: impl Into<String>,
        item: RealtimeConversationItem,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputItemDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            output_index: self.output_index,
            item,
        }
    }

    // ---- Response function call events ----

    /// Build a `response.function_call_arguments.delta` event.
    pub fn function_call_arguments_delta(
        &self,
        event_id: impl Into<String>,
        call_id: impl Into<String>,
        delta: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseFunctionCallArgumentsDelta {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            call_id: call_id.into(),
            delta: delta.into(),
        }
    }

    /// Build a `response.function_call_arguments.done` event.
    pub fn function_call_arguments_done(
        &self,
        event_id: impl Into<String>,
        call_id: impl Into<String>,
        name: impl Into<String>,
        arguments: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseFunctionCallArgumentsDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            call_id: call_id.into(),
            name: name.into(),
            arguments: arguments.into(),
        }
    }

    // ---- Response MCP call events ----

    /// Build a `response.mcp_call_arguments.delta` event.
    pub fn mcp_call_arguments_delta(
        &self,
        event_id: impl Into<String>,
        delta: impl Into<String>,
        obfuscation: Option<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseMcpCallArgumentsDelta {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            delta: delta.into(),
            obfuscation,
        }
    }

    /// Build a `response.mcp_call_arguments.done` event.
    pub fn mcp_call_arguments_done(
        &self,
        event_id: impl Into<String>,
        arguments: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseMcpCallArgumentsDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            arguments: arguments.into(),
        }
    }
}

// ============================================================================
// Level 4: ContentEventBuilder
//   (response_id + item_id + output_index + content_index)
// ============================================================================

/// Reusable context for content-scoped server events.
///
/// Holds `response_id`, `item_id`, `output_index`, and `content_index`.
/// Terminal methods take `event_id` per call, enabling reuse in streaming loops.
#[derive(Clone, Debug)]
pub struct ContentEventBuilder {
    response_id: String,
    item_id: String,
    output_index: u32,
    content_index: u32,
}

impl ContentEventBuilder {
    /// Create a new content-scoped context directly.
    pub fn new(
        response_id: impl Into<String>,
        item_id: impl Into<String>,
        output_index: u32,
        content_index: u32,
    ) -> Self {
        Self {
            response_id: response_id.into(),
            item_id: item_id.into(),
            output_index,
            content_index,
        }
    }

    // ---- Response content part events ----

    /// Build a `response.content_part.added` event.
    pub fn content_part_added(
        &self,
        event_id: impl Into<String>,
        part: ResponseContentPart,
    ) -> ServerEvent {
        ServerEvent::ResponseContentPartAdded {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            part,
        }
    }

    /// Build a `response.content_part.done` event.
    pub fn content_part_done(
        &self,
        event_id: impl Into<String>,
        part: ResponseContentPart,
    ) -> ServerEvent {
        ServerEvent::ResponseContentPartDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            part,
        }
    }

    // ---- Response text events ----

    /// Build a `response.output_text.delta` event.
    pub fn output_text_delta(
        &self,
        event_id: impl Into<String>,
        delta: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputTextDelta {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            delta: delta.into(),
        }
    }

    /// Build a `response.output_text.done` event.
    pub fn output_text_done(
        &self,
        event_id: impl Into<String>,
        text: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputTextDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            text: text.into(),
        }
    }

    // ---- Response audio events ----

    /// Build a `response.output_audio.delta` event.
    pub fn output_audio_delta(
        &self,
        event_id: impl Into<String>,
        delta: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputAudioDelta {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            delta: delta.into(),
        }
    }

    /// Build a `response.output_audio.done` event.
    pub fn output_audio_done(&self, event_id: impl Into<String>) -> ServerEvent {
        ServerEvent::ResponseOutputAudioDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
        }
    }

    // ---- Response audio transcript events ----

    /// Build a `response.output_audio_transcript.delta` event.
    pub fn output_audio_transcript_delta(
        &self,
        event_id: impl Into<String>,
        delta: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputAudioTranscriptDelta {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            delta: delta.into(),
        }
    }

    /// Build a `response.output_audio_transcript.done` event.
    pub fn output_audio_transcript_done(
        &self,
        event_id: impl Into<String>,
        transcript: impl Into<String>,
    ) -> ServerEvent {
        ServerEvent::ResponseOutputAudioTranscriptDone {
            event_id: event_id.into(),
            response_id: self.response_id.clone(),
            item_id: self.item_id.clone(),
            output_index: self.output_index,
            content_index: self.content_index,
            transcript: transcript.into(),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::realtime_session::{
        OutputModality, RealtimeSessionCreateRequest, RealtimeSessionType,
    };

    // One-shot events via ServerEvent associated functions
    #[test]
    fn test_session_created() {
        let config = SessionConfig::Realtime(Box::new(RealtimeSessionCreateRequest {
            r#type: RealtimeSessionType::Realtime,
            output_modalities: Some(vec![OutputModality::Audio]),
            model: None,
            instructions: None,
            audio: None,
            include: None,
            tracing: None,
            tools: None,
            tool_choice: None,
            max_output_tokens: None,
            truncation: None,
            prompt: None,
        }));

        let event = ServerEvent::session_created("evt_1", config);
        assert_eq!(event.event_type(), "session.created");
        let json = serde_json::to_string(&event).expect("serialization failed");
        assert!(json.contains("\"type\":\"session.created\""));
    }

    // Full hierarchy — verifies context propagation at every level
    #[test]
    fn test_full_hierarchy() {
        let l2 = ResponseEventBuilder::new("resp_1");

        // Level 2 terminal — only needs response_id
        let event = l2.output_audio_buffer_started("evt_1");
        assert_eq!(event.event_type(), "output_audio_buffer.started");
        if let ServerEvent::OutputAudioBufferStarted { response_id, .. } = &event {
            assert_eq!(response_id, "resp_1");
        } else {
            panic!("Expected OutputAudioBufferStarted");
        }

        // Level 3 terminal — needs response_id + item context
        let l3 = l2.for_item("item_1", 0);
        let item = RealtimeConversationItem::FunctionCallOutput {
            call_id: "call_1".into(),
            output: "result".into(),
            id: None,
            object: None,
            status: None,
        };
        let event = l3.output_item_done("evt_2", item);
        assert_eq!(event.event_type(), "response.output_item.done");
        if let ServerEvent::ResponseOutputItemDone {
            response_id,
            output_index,
            ..
        } = &event
        {
            assert_eq!(response_id, "resp_1");
            assert_eq!(*output_index, 0);
        } else {
            panic!("Expected ResponseOutputItemDone");
        }

        // Level 4 terminal — needs response_id + item + content context
        let l4 = l3.for_content(0);
        let event = l4.output_text_delta("evt_3", "Hello");
        assert_eq!(event.event_type(), "response.output_text.delta");
        if let ServerEvent::ResponseOutputTextDelta {
            response_id,
            item_id,
            output_index,
            content_index,
            delta,
            ..
        } = &event
        {
            assert_eq!(response_id, "resp_1");
            assert_eq!(item_id, "item_1");
            assert_eq!(*output_index, 0);
            assert_eq!(*content_index, 0);
            assert_eq!(delta, "Hello");
        } else {
            panic!("Expected ResponseOutputTextDelta");
        }
    }

    // Streaming reuse test — the main motivation for this refactoring
    #[test]
    fn test_streaming_reuse() {
        let ctx = ResponseEventBuilder::new("resp_1")
            .for_item("item_1", 0)
            .for_content(0);

        let chunks = ["Hello", " ", "world"];
        let events: Vec<_> = chunks
            .iter()
            .enumerate()
            .map(|(i, chunk)| ctx.output_text_delta(format!("evt_{i}"), *chunk))
            .collect();

        assert_eq!(events.len(), 3);
        for (i, event) in events.iter().enumerate() {
            assert_eq!(event.event_type(), "response.output_text.delta");
            if let ServerEvent::ResponseOutputTextDelta {
                event_id, delta, ..
            } = event
            {
                assert_eq!(event_id, &format!("evt_{i}"));
                assert_eq!(delta, chunks[i]);
            }
        }
    }
}