magi-openai 0.1.0

OpenAI compatible API SDK for Magi AI 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
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
use std::{collections::VecDeque, str::FromStr};

use serde::{Deserialize, Serialize};
use serde_json::json;
use thiserror::Error;

use super::{
    request::{ContentPart, Role},
    response::{OutputType, ResponseStatus, StatusDetails, Usage},
};

/// Errors that can arise while parsing streamed response chunks.
#[derive(Debug, Error)]
pub enum ParserError {
    #[error("Failed to parse JSON: {0}")]
    JsonError(#[from] serde_json::Error),
}

/// Representation of a streaming chunk returned by the Responses API.
#[derive(Debug, Clone, PartialEq)]
pub enum Chunk {
    Done,
    Data(Box<ChunkResponse>),
}

impl FromStr for Chunk {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "[DONE]" => Ok(Chunk::Done),
            _ => Ok(Chunk::Data(Box::new(
                serde_json::from_str::<ChunkResponse>(s)?,
            ))),
        }
    }
}

impl Chunk {
    /// Serialises the chunk back into the Server Sent Events payload format.
    pub fn try_to_string(&self) -> Result<String, serde_json::Error> {
        match self {
            Chunk::Done => Ok("[DONE]".to_string()),
            Chunk::Data(response) => serde_json::to_string(response.as_ref()),
        }
    }

    /// Convenience constructor for a `[DONE]` chunk.
    pub fn done() -> Self {
        Chunk::Done
    }

    /// Creates a starter chunk with a default assistant role delta.
    pub fn starter(id: impl Into<String>, model: impl Into<String>) -> Self {
        let now = current_timestamp();
        Chunk::Data(Box::new(ChunkResponse {
            id: id.into(),
            model: model.into(),
            object: "response.chunk".to_string(),
            created: now,
            output: vec![ChunkOutput {
                index: 0,
                r#type: OutputType::Message,
                role: Some(Role::Assistant),
                delta: Some(Delta {
                    role: Some(Role::Assistant),
                    content: Some(VecDeque::from([json!({
                        "type": "output_text",
                        "text": "",
                    })])),
                    ..Default::default()
                }),
                ..Default::default()
            }],
            ..Default::default()
        }))
    }

    /// Creates a chunk containing textual content.
    pub fn with_content(
        id: impl Into<String>,
        model: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        let now = current_timestamp();
        Chunk::Data(Box::new(ChunkResponse {
            id: id.into(),
            model: model.into(),
            object: "response.chunk".to_string(),
            created: now,
            output: vec![ChunkOutput {
                index: 0,
                r#type: OutputType::Message,
                role: Some(Role::Assistant),
                delta: Some(Delta {
                    content: Some(VecDeque::from([json!({
                        "type": "output_text",
                        "text": content.into(),
                    })])),
                    ..Default::default()
                }),
                ..Default::default()
            }],
            ..Default::default()
        }))
    }

    /// Creates a configurable chunk builder.
    pub fn builder(id: impl Into<String>, model: impl Into<String>) -> ChunkBuilder {
        ChunkBuilder::new(id.into(), model.into())
    }
}

fn current_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

/// Builder used to progressively create streaming chunks.
#[derive(Debug, Default, Clone)]
pub struct ChunkBuilder {
    id: String,
    model: String,
    content: VecDeque<ContentPart>,
    role: Option<Role>,
    status: Option<ResponseStatus>,
    status_details: Option<StatusDetails>,
    usage: Option<Usage>,
    created: Option<u64>,
}

impl ChunkBuilder {
    /// Creates a new builder for the provided identifier and model.
    pub fn new(id: String, model: String) -> Self {
        Self {
            id,
            model,
            ..Default::default()
        }
    }

    /// Appends textual content to the chunk.
    pub fn push_text(mut self, text: impl Into<String>) -> Self {
        self.content.push_back(json!({
            "type": "output_text",
            "text": text.into(),
        }));
        self
    }

    /// Sets the role associated with the chunk delta.
    pub fn role(mut self, role: Role) -> Self {
        self.role = Some(role);
        self
    }

    /// Sets the status associated with the chunk.
    pub fn status(mut self, status: ResponseStatus) -> Self {
        self.status = Some(status);
        self
    }

    /// Supplies detailed status metadata.
    pub fn status_details(mut self, details: StatusDetails) -> Self {
        self.status_details = Some(details);
        self
    }

    /// Attaches usage statistics to the chunk.
    pub fn usage(mut self, usage: Usage) -> Self {
        self.usage = Some(usage);
        self
    }

    /// Overrides the timestamp for the chunk.
    pub fn created(mut self, created: u64) -> Self {
        self.created = Some(created);
        self
    }

    /// Consumes the builder and returns the constructed chunk.
    pub fn build(self) -> Chunk {
        let created = self.created.unwrap_or_else(current_timestamp);
        Chunk::Data(Box::new(ChunkResponse {
            id: self.id,
            model: self.model,
            object: "response.chunk".to_string(),
            created,
            status: self.status,
            status_details: self.status_details,
            usage: self.usage,
            output: if self.content.is_empty() {
                Vec::new()
            } else {
                vec![ChunkOutput {
                    index: 0,
                    r#type: OutputType::Message,
                    role: self.role,
                    delta: Some(Delta {
                        role: self.role,
                        content: Some(self.content),
                        ..Default::default()
                    }),
                    ..Default::default()
                }]
            },
            ..Default::default()
        }))
    }
}

/// Streaming response payload.
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct ChunkResponse {
    /// Unique identifier for the response.
    #[serde(default)]
    pub id: String,
    /// The model used for the response.
    #[serde(default)]
    pub model: String,
    /// Object type for the streaming event.
    #[serde(default)]
    pub object: String,
    /// The type of streaming event.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub event_type: Option<StreamEventType>,
    /// Unix timestamp of when the chunk was created.
    #[serde(default, alias = "created_at")]
    pub created: u64,
    /// Status of the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<ResponseStatus>,
    /// Detailed status information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_details: Option<StatusDetails>,
    /// Usage statistics (typically in final chunk).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
    /// Output items in this chunk.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub output: Vec<ChunkOutput>,
    /// Backend configuration fingerprint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_fingerprint: Option<String>,
    /// The full response object (for response.completed events).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<Box<super::response::Response>>,
    /// Index of the output item this event relates to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_index: Option<usize>,
    /// Index of the content part this event relates to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_index: Option<usize>,
    /// ID of the item this event relates to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_id: Option<String>,
    /// Text delta for text streaming events.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta: Option<String>,
    /// Full text content (for done events).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// The output item (for output_item events).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item: Option<super::response::Output>,
    /// The content part (for content_part events).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub part: Option<serde_json::Value>,
}

/// Types of streaming events emitted by the Responses API.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub enum StreamEventType {
    /// Response object has been created.
    #[serde(rename = "response.created")]
    ResponseCreated,
    /// Response generation is in progress.
    #[serde(rename = "response.in_progress")]
    ResponseInProgress,
    /// Response generation completed successfully.
    #[serde(rename = "response.completed")]
    ResponseCompleted,
    /// Response generation failed.
    #[serde(rename = "response.failed")]
    ResponseFailed,
    /// Response generation was incomplete.
    #[serde(rename = "response.incomplete")]
    ResponseIncomplete,
    /// A new output item was added.
    #[serde(rename = "response.output_item.added")]
    OutputItemAdded,
    /// An output item is complete.
    #[serde(rename = "response.output_item.done")]
    OutputItemDone,
    /// A new content part was added.
    #[serde(rename = "response.content_part.added")]
    ContentPartAdded,
    /// A content part is complete.
    #[serde(rename = "response.content_part.done")]
    ContentPartDone,
    /// Text content delta.
    #[serde(rename = "response.output_text.delta")]
    OutputTextDelta,
    /// Text content is complete.
    #[serde(rename = "response.output_text.done")]
    OutputTextDone,
    /// Function call arguments delta.
    #[serde(rename = "response.function_call_arguments.delta")]
    FunctionCallArgumentsDelta,
    /// Function call arguments complete.
    #[serde(rename = "response.function_call_arguments.done")]
    FunctionCallArgumentsDone,
    /// File search call in progress.
    #[serde(rename = "response.file_search_call.in_progress")]
    FileSearchCallInProgress,
    /// File search call searching.
    #[serde(rename = "response.file_search_call.searching")]
    FileSearchCallSearching,
    /// File search call completed.
    #[serde(rename = "response.file_search_call.completed")]
    FileSearchCallCompleted,
    /// Web search call in progress.
    #[serde(rename = "response.web_search_call.in_progress")]
    WebSearchCallInProgress,
    /// Web search call searching.
    #[serde(rename = "response.web_search_call.searching")]
    WebSearchCallSearching,
    /// Web search call completed.
    #[serde(rename = "response.web_search_call.completed")]
    WebSearchCallCompleted,
    /// Code interpreter call in progress.
    #[serde(rename = "response.code_interpreter_call.in_progress")]
    CodeInterpreterCallInProgress,
    /// Code interpreter call interpreting.
    #[serde(rename = "response.code_interpreter_call.interpreting")]
    CodeInterpreterCallInterpreting,
    /// Code interpreter call completed.
    #[serde(rename = "response.code_interpreter_call.completed")]
    CodeInterpreterCallCompleted,
    /// Code interpreter code delta.
    #[serde(rename = "response.code_interpreter_call.code.delta")]
    CodeInterpreterCallCodeDelta,
    /// Code interpreter code done.
    #[serde(rename = "response.code_interpreter_call.code.done")]
    CodeInterpreterCallCodeDone,
    /// Audio delta.
    #[serde(rename = "response.audio.delta")]
    AudioDelta,
    /// Audio done.
    #[serde(rename = "response.audio.done")]
    AudioDone,
    /// Audio transcript delta.
    #[serde(rename = "response.audio.transcript.delta")]
    AudioTranscriptDelta,
    /// Audio transcript done.
    #[serde(rename = "response.audio.transcript.done")]
    AudioTranscriptDone,
    /// Refusal delta.
    #[serde(rename = "response.refusal.delta")]
    RefusalDelta,
    /// Refusal done.
    #[serde(rename = "response.refusal.done")]
    RefusalDone,
    /// Reasoning summary part added.
    #[serde(rename = "response.reasoning_summary_part.added")]
    ReasoningSummaryPartAdded,
    /// Reasoning summary part done.
    #[serde(rename = "response.reasoning_summary_part.done")]
    ReasoningSummaryPartDone,
    /// Reasoning summary text delta.
    #[serde(rename = "response.reasoning_summary_text.delta")]
    ReasoningSummaryTextDelta,
    /// Reasoning summary text done.
    #[serde(rename = "response.reasoning_summary_text.done")]
    ReasoningSummaryTextDone,
    /// Text annotation added.
    #[serde(rename = "response.output_text.annotation.added")]
    OutputTextAnnotationAdded,
    /// Error event.
    #[serde(rename = "error")]
    Error,
}

/// Individual chunk output entries.
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct ChunkOutput {
    pub index: usize,
    #[serde(rename = "type")]
    pub r#type: OutputType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<Role>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta: Option<Delta>,
}

/// Delta payload inside a streaming chunk.
#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq)]
pub struct Delta {
    /// Role of the message author.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<Role>,
    /// Content parts being streamed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<VecDeque<ContentPart>>,
    /// Tool call identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// Text delta for text content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Function call arguments delta.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

/// Parser for accumulating streaming response chunks into a complete [`Response`].
///
/// This parser is the Responses API equivalent of the `OpenAIChunkParser` from
/// the completions module. It accumulates text deltas, function call arguments,
/// and other streamed data and produces a final `Response` when the stream ends.
#[derive(Debug, Default, Clone)]
pub struct ResponseChunkParser {
    /// Response identifier accumulated from chunks.
    pub id: String,
    /// Object type from the response.
    pub object: String,
    /// Unix timestamp of the response creation.
    pub created: u64,
    /// Model identifier from the response.
    pub model: String,
    /// Backend system fingerprint.
    system_fingerprint: Option<String>,
    /// Response status accumulated from events.
    status: ResponseStatus,
    /// Detailed status information.
    status_details: Option<StatusDetails>,
    /// Usage statistics from the final chunk.
    usage: Option<Usage>,
    /// Accumulated text content.
    pub content: String,
    /// Accumulated reasoning/thinking content.
    pub reasoning_content: String,
    /// Current function call being accumulated.
    current_function_call: Option<FunctionCallAccumulator>,
    /// Completed output items.
    outputs: Vec<super::response::Output>,
}

/// Internal helper for accumulating function call chunks.
#[derive(Debug, Default, Clone)]
struct FunctionCallAccumulator {
    id: String,
    name: String,
    call_id: String,
    arguments: String,
}

impl ResponseChunkParser {
    /// Parses a single chunk and updates internal state.
    ///
    /// Returns `Ok((Some(response), None))` when parsing a `[DONE]` chunk or a
    /// `response.completed` event, indicating that the stream has finished.
    ///
    /// Returns `Ok((None, Some(output)))` when a complete function call output
    /// is ready to be processed.
    ///
    /// Returns `Ok((None, None))` for intermediate chunks.
    pub fn parse(
        &mut self,
        data: &str,
    ) -> Result<
        (
            Option<super::response::Response>,
            Option<super::response::Output>,
        ),
        ParserError,
    > {
        let chunk = Chunk::from_str(data)?;

        match chunk {
            Chunk::Done => {
                let response = self.build_response();
                Ok((Some(response), None))
            }
            Chunk::Data(response) => {
                self.update_basic_info(&response);

                let completed_output = match response.event_type {
                    Some(StreamEventType::ResponseCompleted) => {
                        // If we have a full response object, use it directly
                        if let Some(full_response) = response.response {
                            return Ok((Some(*full_response), None));
                        }
                        // Otherwise build from accumulated state
                        let resp = self.build_response();
                        return Ok((Some(resp), None));
                    }
                    Some(StreamEventType::OutputTextDelta) => {
                        if let Some(delta) = &response.delta {
                            self.content.push_str(delta);
                        }
                        None
                    }
                    Some(StreamEventType::ReasoningSummaryTextDelta) => {
                        if let Some(delta) = &response.delta {
                            self.reasoning_content.push_str(delta);
                        }
                        None
                    }
                    Some(StreamEventType::OutputItemAdded) => {
                        // Start tracking a new output item if it's a function call
                        if let Some(item) = &response.item {
                            if item.r#type == super::response::OutputType::FunctionCall {
                                self.current_function_call = Some(FunctionCallAccumulator {
                                    id: item.id.clone(),
                                    name: item.name.clone().unwrap_or_default(),
                                    call_id: item.call_id.clone().unwrap_or_default(),
                                    arguments: item.arguments.clone().unwrap_or_default(),
                                });
                            }
                        }
                        None
                    }
                    Some(StreamEventType::FunctionCallArgumentsDelta) => {
                        if let Some(ref mut fc) = self.current_function_call {
                            if let Some(delta) = &response.delta {
                                fc.arguments.push_str(delta);
                            }
                        }
                        None
                    }
                    Some(StreamEventType::FunctionCallArgumentsDone)
                    | Some(StreamEventType::OutputItemDone) => {
                        // Complete the current function call if present
                        self.finalize_function_call()
                    }
                    Some(StreamEventType::ResponseFailed)
                    | Some(StreamEventType::ResponseIncomplete) => {
                        self.status =
                            if response.event_type == Some(StreamEventType::ResponseFailed) {
                                ResponseStatus::Failed
                            } else {
                                ResponseStatus::Incomplete
                            };
                        None
                    }
                    _ => {
                        // Handle legacy/non-typed chunks with output array
                        for output in &response.output {
                            if let Some(delta) = &output.delta {
                                // Text content from delta
                                if let Some(text) = &delta.text {
                                    self.content.push_str(text);
                                }
                                // Content array processing
                                if let Some(content_parts) = &delta.content {
                                    for part in content_parts {
                                        if let Some(text) =
                                            part.get("text").and_then(|v| v.as_str())
                                        {
                                            self.content.push_str(text);
                                        }
                                    }
                                }
                                // Function call arguments
                                if let Some(args) = &delta.arguments {
                                    if let Some(ref mut fc) = self.current_function_call {
                                        fc.arguments.push_str(args);
                                    }
                                }
                            }
                        }
                        None
                    }
                };

                Ok((None, completed_output))
            }
        }
    }

    /// Builds the final response from accumulated state.
    pub fn build_response(&self) -> super::response::Response {
        use super::response::{Output, OutputType, Response};

        let mut outputs = self.outputs.clone();

        // Add text content as a message output if we have any
        if !self.content.is_empty() {
            outputs.push(Output {
                id: format!("output-{}", outputs.len()),
                r#type: OutputType::Message,
                role: Some(Role::Assistant),
                content: vec![json!({
                    "type": "output_text",
                    "text": self.content.clone(),
                })],
                ..Default::default()
            });
        }

        // Add reasoning content if present
        if !self.reasoning_content.is_empty() {
            outputs.push(Output {
                id: format!("output-{}", outputs.len()),
                r#type: OutputType::Reasoning,
                summary: vec![json!({
                    "type": "summary_text",
                    "text": self.reasoning_content.clone(),
                })],
                ..Default::default()
            });
        }

        Response {
            id: self.id.clone(),
            object: if self.object.is_empty() {
                "response".to_string()
            } else {
                self.object.clone()
            },
            created_at: self.created,
            model: self.model.clone(),
            status: self.status.clone(),
            system_fingerprint: self.system_fingerprint.clone(),
            usage: self.usage.clone(),
            output: outputs,
            output_text: if self.content.is_empty() {
                None
            } else {
                Some(self.content.clone())
            },
            ..Default::default()
        }
    }

    /// Updates the response ID if it hasn't been set yet.
    pub fn update_id_if_empty(&mut self, id: &str) {
        if self.id.is_empty() {
            self.id = id.to_string();
        }
    }

    /// Updates the model if it hasn't been set yet.
    pub fn update_model_if_empty(&mut self, model: &str) {
        if self.model.is_empty() {
            self.model = model.to_string();
        }
    }

    /// Sets the system fingerprint.
    pub fn set_system_fingerprint(&mut self, fingerprint: Option<String>) {
        self.system_fingerprint = fingerprint;
    }

    /// Sets the response status.
    pub fn set_status(&mut self, status: ResponseStatus) {
        self.status = status;
    }

    /// Appends text content.
    pub fn push_content(&mut self, content: &str) {
        self.content.push_str(content);
    }

    /// Appends reasoning content.
    pub fn push_reasoning(&mut self, content: &str) {
        self.reasoning_content.push_str(content);
    }

    /// Adds a completed output item.
    pub fn push_output(&mut self, output: super::response::Output) {
        self.outputs.push(output);
    }

    fn update_basic_info(&mut self, response: &ChunkResponse) {
        if self.id.is_empty() && !response.id.is_empty() {
            self.id = response.id.clone();
        }
        if !response.object.is_empty() {
            self.object = response.object.clone();
        }
        if response.created > 0 {
            self.created = response.created;
        }
        if !response.model.is_empty() {
            self.model = response.model.clone();
        }
        if response.system_fingerprint.is_some() {
            self.system_fingerprint = response.system_fingerprint.clone();
        }
        if let Some(status) = &response.status {
            self.status = status.clone();
        }
        if response.status_details.is_some() {
            self.status_details = response.status_details.clone();
        }
        if response.usage.is_some() {
            self.usage = response.usage.clone();
        }
    }

    fn finalize_function_call(&mut self) -> Option<super::response::Output> {
        let fc = self.current_function_call.take()?;
        let output = super::response::Output {
            id: fc.id,
            r#type: super::response::OutputType::FunctionCall,
            status: Some(super::response::OutputStatus::Completed),
            name: Some(fc.name),
            call_id: Some(fc.call_id),
            arguments: Some(fc.arguments),
            ..Default::default()
        };
        self.outputs.push(output.clone());
        Some(output)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn starter_chunk_serialises() {
        let chunk = Chunk::starter("resp_1", "gpt-4.1-mini");
        let serialised = chunk.try_to_string().unwrap();
        assert!(serialised.contains("response.chunk"));
    }

    #[test]
    fn builder_produces_chunk_with_text() {
        let chunk = Chunk::builder("resp_2", "gpt-4.1-mini")
            .push_text("hello")
            .build();

        match chunk {
            Chunk::Data(response) => {
                assert_eq!(response.output.len(), 1);
                let content = &response.output[0]
                    .delta
                    .as_ref()
                    .and_then(|delta| delta.content.clone())
                    .unwrap();
                assert_eq!(content.len(), 1);
                assert_eq!(
                    content[0].get("text").and_then(|value| value.as_str()),
                    Some("hello")
                );
            }
            Chunk::Done => panic!("expected chunk data"),
        }
    }

    #[test]
    fn test_parser_for_text_content() {
        let test_cases = vec![
            // response.created event
            r#"{"type":"response.created","response":{"id":"resp_123","object":"response","created_at":1700000000,"model":"gpt-4.1-mini","status":"in_progress","output":[]}}"#,
            // response.in_progress event
            r#"{"type":"response.in_progress","response":{"id":"resp_123","object":"response","created_at":1700000000,"model":"gpt-4.1-mini","status":"in_progress","output":[]}}"#,
            // output_item.added event
            r#"{"type":"response.output_item.added","output_index":0,"item":{"id":"item_0","type":"message","role":"assistant","content":[]}}"#,
            // content_part.added event
            r#"{"type":"response.content_part.added","output_index":0,"content_index":0,"part":{"type":"output_text","text":""}}"#,
            // text deltas
            r#"{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"Hello"}"#,
            r#"{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":" "}"#,
            r#"{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"world"}"#,
            r#"{"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"!"}"#,
            // text done
            r#"{"type":"response.output_text.done","output_index":0,"content_index":0,"text":"Hello world!"}"#,
            // content_part.done
            r#"{"type":"response.content_part.done","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Hello world!"}}"#,
            // output_item.done
            r#"{"type":"response.output_item.done","output_index":0,"item":{"id":"item_0","type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello world!"}]}}"#,
            // response.completed
            r#"{"type":"response.completed","response":{"id":"resp_123","object":"response","created_at":1700000000,"model":"gpt-4.1-mini","status":"completed","output":[{"id":"item_0","type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello world!"}]}],"usage":{"input_tokens":10,"output_tokens":5,"total_tokens":15}}}"#,
        ];

        let mut parser = ResponseChunkParser::default();
        let mut final_response = None;

        for data in test_cases {
            let (response, _output) = parser.parse(data).expect("parse should succeed");
            if let Some(resp) = response {
                final_response = Some(resp);
            }
        }

        let res = final_response.expect("Expected final response");
        assert_eq!(res.id, "resp_123");
        assert_eq!(res.model, "gpt-4.1-mini");
        assert_eq!(res.status, ResponseStatus::Completed);
    }

    #[test]
    fn test_parser_for_text_deltas_accumulated() {
        let test_cases = vec![
            r#"{"type":"response.output_text.delta","id":"resp_456","model":"gpt-4.1-mini","output_index":0,"content_index":0,"delta":"Hello"}"#,
            r#"{"type":"response.output_text.delta","id":"resp_456","model":"gpt-4.1-mini","output_index":0,"content_index":0,"delta":" "}"#,
            r#"{"type":"response.output_text.delta","id":"resp_456","model":"gpt-4.1-mini","output_index":0,"content_index":0,"delta":"world"}"#,
            r#"{"type":"response.output_text.delta","id":"resp_456","model":"gpt-4.1-mini","output_index":0,"content_index":0,"delta":"!"}"#,
            "[DONE]",
        ];

        let mut parser = ResponseChunkParser::default();
        let mut final_response = None;

        for data in test_cases {
            let (response, _) = parser.parse(data).expect("parse should succeed");
            if let Some(resp) = response {
                final_response = Some(resp);
            }
        }

        let res = final_response.expect("Expected final response from [DONE]");
        assert_eq!(res.id, "resp_456");
        assert_eq!(res.output_text, Some("Hello world!".to_string()));
    }

    #[test]
    fn test_parser_for_function_call() {
        let test_cases = vec![
            // Function call added
            r#"{"type":"response.output_item.added","output_index":0,"item":{"id":"fc_0","type":"function_call","name":"get_weather","call_id":"call_123","arguments":""}}"#,
            // Arguments streaming
            r#"{"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"loc"}"#,
            r#"{"type":"response.function_call_arguments.delta","output_index":0,"delta":"ation\""}"#,
            r#"{"type":"response.function_call_arguments.delta","output_index":0,"delta":": \"NYC"}"#,
            r#"{"type":"response.function_call_arguments.delta","output_index":0,"delta":"\"}"}"#,
            // Function call done
            r#"{"type":"response.function_call_arguments.done","output_index":0,"arguments":"{\"location\": \"NYC\"}"}"#,
        ];

        let mut parser = ResponseChunkParser::default();
        parser.update_id_if_empty("resp_fc");
        parser.update_model_if_empty("gpt-4.1-mini");

        let mut completed_output = None;

        for data in test_cases {
            let (_, output) = parser.parse(data).expect("parse should succeed");
            if output.is_some() {
                completed_output = output;
            }
        }

        let output = completed_output.expect("Expected completed function call output");
        assert_eq!(
            output.r#type,
            super::super::response::OutputType::FunctionCall
        );
        assert_eq!(output.name, Some("get_weather".to_string()));
        assert_eq!(output.call_id, Some("call_123".to_string()));
        assert_eq!(
            output.arguments,
            Some("{\"location\": \"NYC\"}".to_string())
        );
    }

    #[test]
    fn test_done_chunk() {
        let input = "[DONE]";
        let chunk: Chunk = input.parse().unwrap();
        assert_eq!(chunk, Chunk::Done);
    }

    #[test]
    fn test_parser_build_response() {
        let mut parser = ResponseChunkParser::default();
        parser.id = "resp_build".to_string();
        parser.model = "gpt-4.1-mini".to_string();
        parser.created = 1700000000;
        parser.push_content("Test content");

        let response = parser.build_response();
        assert_eq!(response.id, "resp_build");
        assert_eq!(response.model, "gpt-4.1-mini");
        assert_eq!(response.created_at, 1700000000);
        assert_eq!(response.output_text, Some("Test content".to_string()));
        assert_eq!(response.output.len(), 1);
    }
}