llmsim 0.3.0

LLM Traffic Simulator - A lightweight, high-performance LLM API simulator
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
// OpenAI Responses API Types
// These types are designed to be compatible with the OpenAI Responses API.
// Reference: https://platform.openai.com/docs/api-reference/responses

use crate::ids::{prefixed_id, unix_timestamp};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Input for a Responses API request - can be a string or array of items
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResponsesInput {
    /// Simple text input
    Text(String),
    /// Array of input items (messages, etc.)
    Items(Vec<InputItem>),
}

/// An input item in the Responses API.
/// Accepts both tagged (`{"type": "message", ...}`) and shorthand
/// (`{"role": "user", "content": "..."}`) formats for compatibility with
/// the OpenAI API and SDKs like LangChain.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InputItem {
    /// A message input item
    Message {
        role: InputRole,
        content: MessageContent,
    },
    /// A function call result (tool output)
    FunctionCallOutput { call_id: String, output: String },
}

impl<'de> serde::Deserialize<'de> for InputItem {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        let obj = value
            .as_object()
            .ok_or_else(|| serde::de::Error::custom("expected an object"))?;

        match obj.get("type").and_then(|v| v.as_str()) {
            Some("message") | None if obj.contains_key("role") => {
                // Tagged message or shorthand (no "type" but has "role")
                let role: InputRole = serde_json::from_value(
                    obj.get("role")
                        .cloned()
                        .ok_or_else(|| serde::de::Error::missing_field("role"))?,
                )
                .map_err(serde::de::Error::custom)?;
                let content: MessageContent = serde_json::from_value(
                    obj.get("content")
                        .cloned()
                        .ok_or_else(|| serde::de::Error::missing_field("content"))?,
                )
                .map_err(serde::de::Error::custom)?;
                Ok(InputItem::Message { role, content })
            }
            Some("function_call_output") => {
                let call_id = obj
                    .get("call_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| serde::de::Error::missing_field("call_id"))?
                    .to_string();
                let output = obj
                    .get("output")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| serde::de::Error::missing_field("output"))?
                    .to_string();
                Ok(InputItem::FunctionCallOutput { call_id, output })
            }
            Some(other) => Err(serde::de::Error::unknown_variant(
                other,
                &["message", "function_call_output"],
            )),
            None => Err(serde::de::Error::custom(
                "missing 'type' or 'role' field in input item",
            )),
        }
    }
}

/// Role for input messages
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum InputRole {
    User,
    Assistant,
    System,
    Developer,
}

/// Message content - can be a string or array of content parts
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContent {
    /// Simple text content
    Text(String),
    /// Array of content parts
    Parts(Vec<ContentPart>),
}

/// A content part in a message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    /// Text content
    InputText { text: String },
    /// Image content
    InputImage { image_url: String },
    /// File content
    InputFile {
        #[serde(skip_serializing_if = "Option::is_none")]
        file_url: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        file_id: Option<String>,
    },
}

/// Reasoning configuration for the Responses API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningConfig {
    /// Reasoning effort level: "none", "low", "medium", "high"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effort: Option<String>,
    /// Whether to include reasoning summary in output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

/// Responses API request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponsesRequest {
    /// Model to use for generation
    pub model: String,
    /// Input text or array of input items
    pub input: ResponsesInput,
    /// System instructions for this request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// Sampling temperature (0.0 - 2.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    /// Nucleus sampling parameter
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    /// Maximum tokens to generate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_output_tokens: Option<u32>,
    /// Enable streaming response
    #[serde(default)]
    pub stream: bool,
    /// Custom metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, String>>,
    /// Chain to a previous response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    /// Tools available for the model
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<ResponsesTool>>,
    /// Control tool usage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ResponsesToolChoice>,
    /// Reasoning configuration (for o-series and reasoning models)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ReasoningConfig>,
    /// Enable background/async processing for long-running tasks
    #[serde(default)]
    pub background: bool,
    /// Include additional data in response (e.g., "reasoning.encrypted_content")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include: Option<Vec<String>>,
}

/// A tool definition for the Responses API
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ResponsesTool {
    /// Function tool
    Function {
        name: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        parameters: Option<serde_json::Value>,
    },
    /// Web search tool
    WebSearch {},
    /// File search tool
    FileSearch {},
    /// Code interpreter tool
    CodeInterpreter {},
    /// Remote MCP server tool
    Mcp {
        /// MCP server URL
        server_url: String,
        /// Optional headers for authentication
        #[serde(skip_serializing_if = "Option::is_none")]
        headers: Option<std::collections::HashMap<String, String>>,
    },
    /// Image generation tool
    ImageGeneration {},
}

/// Tool choice option for Responses API
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResponsesToolChoice {
    /// String value: "auto", "none", "required"
    String(String),
    /// Specific function
    Function { r#type: String, name: String },
}

/// Response status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ResponseStatus {
    Completed,
    Failed,
    InProgress,
    Queued,
    Incomplete,
}

/// Responses API response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponsesResponse {
    /// Unique response identifier
    pub id: String,
    /// Object type (always "response")
    pub object: String,
    /// Creation timestamp
    pub created_at: i64,
    /// Model used
    pub model: String,
    /// Response status
    pub status: ResponseStatus,
    /// Output items
    pub output: Vec<OutputItem>,
    /// Simplified text output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_text: Option<String>,
    /// Token usage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<ResponsesUsage>,
    /// Error information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ResponsesError>,
    /// Metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, String>>,
}

impl ResponsesResponse {
    pub fn new(model: String, content: String, usage: ResponsesUsage) -> Self {
        let output_item = OutputItem::Message {
            id: prefixed_id("msg_"),
            role: OutputRole::Assistant,
            status: ItemStatus::Completed,
            content: vec![OutputContentPart::OutputText {
                text: content.clone(),
                annotations: vec![],
            }],
        };

        Self {
            id: prefixed_id("resp_"),
            object: "response".to_string(),
            created_at: unix_timestamp(),
            model,
            status: ResponseStatus::Completed,
            output: vec![output_item],
            output_text: Some(content),
            usage: Some(usage),
            error: None,
            metadata: None,
        }
    }

    /// Create a minimal response for WebSocket warmup (generate=false).
    pub fn warmup(model: String) -> Self {
        Self {
            id: prefixed_id("resp_"),
            object: "response".to_string(),
            created_at: unix_timestamp(),
            model,
            status: ResponseStatus::Completed,
            output: vec![],
            output_text: None,
            usage: None,
            error: None,
            metadata: None,
        }
    }

    /// Create a response with a reasoning output item before the message.
    /// The reasoning item includes an optional summary when `summary_text` is provided.
    pub fn with_reasoning(
        model: String,
        content: String,
        summary_text: Option<String>,
        usage: ResponsesUsage,
    ) -> Self {
        let reasoning_item = OutputItem::Reasoning {
            id: prefixed_id("rs_"),
            status: ItemStatus::Completed,
            summary: summary_text.map(|text| {
                vec![ReasoningSummary {
                    summary_type: "summary_text".to_string(),
                    text,
                }]
            }),
        };

        let message_item = OutputItem::Message {
            id: prefixed_id("msg_"),
            role: OutputRole::Assistant,
            status: ItemStatus::Completed,
            content: vec![OutputContentPart::OutputText {
                text: content.clone(),
                annotations: vec![],
            }],
        };

        Self {
            id: prefixed_id("resp_"),
            object: "response".to_string(),
            created_at: unix_timestamp(),
            model,
            status: ResponseStatus::Completed,
            output: vec![reasoning_item, message_item],
            output_text: Some(content),
            usage: Some(usage),
            error: None,
            metadata: None,
        }
    }
}

/// An output item in the response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OutputItem {
    /// A message output
    Message {
        id: String,
        role: OutputRole,
        status: ItemStatus,
        content: Vec<OutputContentPart>,
    },
    /// A function call
    FunctionCall {
        id: String,
        call_id: String,
        name: String,
        arguments: String,
        status: ItemStatus,
    },
    /// Reasoning output (for reasoning models)
    Reasoning {
        id: String,
        status: ItemStatus,
        #[serde(skip_serializing_if = "Option::is_none")]
        summary: Option<Vec<ReasoningSummary>>,
    },
}

/// Role for output messages
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum OutputRole {
    Assistant,
}

/// Status of an output item
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ItemStatus {
    Completed,
    InProgress,
    Failed,
}

/// An output content part
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OutputContentPart {
    /// Text output
    OutputText {
        text: String,
        /// Annotations on this text content (e.g. citations).
        /// Always present in the wire format as an array (defaults to empty).
        #[serde(default)]
        annotations: Vec<serde_json::Value>,
    },
    /// Refusal output
    Refusal { refusal: String },
}

/// Reasoning summary for reasoning models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningSummary {
    #[serde(rename = "type")]
    pub summary_type: String,
    pub text: String,
}

/// Token usage for Responses API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponsesUsage {
    pub input_tokens: u32,
    pub output_tokens: u32,
    pub total_tokens: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_tokens_details: Option<OutputTokensDetails>,
}

/// Details about output token usage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputTokensDetails {
    pub reasoning_tokens: u32,
}

/// Error in Responses API format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponsesError {
    #[serde(rename = "type")]
    pub error_type: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
}

impl ResponsesError {
    pub fn new(error_type: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            error_type: error_type.into(),
            message: message.into(),
            code: None,
        }
    }

    pub fn rate_limit() -> Self {
        Self {
            error_type: "rate_limit_error".to_string(),
            message: "Rate limit exceeded. Please retry after some time.".to_string(),
            code: Some("rate_limit_exceeded".to_string()),
        }
    }

    pub fn server_error() -> Self {
        Self {
            error_type: "server_error".to_string(),
            message: "The server had an error processing your request.".to_string(),
            code: Some("server_error".to_string()),
        }
    }
}

/// Responses API error response (for HTTP error responses)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponsesErrorResponse {
    pub error: ResponsesError,
}

// ============================================================================
// Streaming Types
// ============================================================================

/// Base streaming event structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamEvent {
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(flatten)]
    pub data: StreamEventData,
}

/// Data payload for different event types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StreamEventData {
    /// Response lifecycle events
    Response(ResponseEventData),
    /// Output item events
    OutputItem(OutputItemEventData),
    /// Content part events
    ContentPart(ContentPartEventData),
    /// Text delta events
    TextDelta(TextDeltaEventData),
    /// Error events
    Error(ErrorEventData),
}

/// Data for response lifecycle events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseEventData {
    pub response: ResponsesResponse,
}

/// Data for output item events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputItemEventData {
    pub output_index: u32,
    pub item: OutputItem,
}

/// Data for content part events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentPartEventData {
    pub output_index: u32,
    pub content_index: u32,
    pub part: OutputContentPart,
}

/// Data for text delta events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextDeltaEventData {
    pub output_index: u32,
    pub content_index: u32,
    pub delta: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sequence_number: Option<u32>,
}

/// Data for error events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorEventData {
    pub error: ResponsesError,
}

/// Helper to create streaming events.
///
/// Every server event includes a `sequence_number` field — a monotonically
/// increasing integer that allows the SDK to order events even if transport
/// delivery is re-ordered. Content/text events also include `item_id` for
/// correlating events to their parent output item.
pub struct ResponsesStreamEvent;

impl ResponsesStreamEvent {
    pub fn response_created(response: ResponsesResponse, seq: u32) -> String {
        let event = serde_json::json!({
            "type": "response.created",
            "response": response,
            "sequence_number": seq
        });
        format!("event: response.created\ndata: {}\n\n", event)
    }

    pub fn response_in_progress(response: ResponsesResponse, seq: u32) -> String {
        let event = serde_json::json!({
            "type": "response.in_progress",
            "response": response,
            "sequence_number": seq
        });
        format!("event: response.in_progress\ndata: {}\n\n", event)
    }

    pub fn output_item_added(output_index: u32, item: &OutputItem, seq: u32) -> String {
        let event = serde_json::json!({
            "type": "response.output_item.added",
            "output_index": output_index,
            "item": item,
            "sequence_number": seq
        });
        format!("event: response.output_item.added\ndata: {}\n\n", event)
    }

    pub fn content_part_added(
        output_index: u32,
        content_index: u32,
        item_id: &str,
        part: &OutputContentPart,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.content_part.added",
            "output_index": output_index,
            "content_index": content_index,
            "item_id": item_id,
            "part": part,
            "sequence_number": seq
        });
        format!("event: response.content_part.added\ndata: {}\n\n", event)
    }

    pub fn output_text_delta(
        output_index: u32,
        content_index: u32,
        item_id: &str,
        delta: &str,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.output_text.delta",
            "output_index": output_index,
            "content_index": content_index,
            "item_id": item_id,
            "delta": delta,
            "logprobs": [],
            "sequence_number": seq
        });
        format!("event: response.output_text.delta\ndata: {}\n\n", event)
    }

    pub fn output_text_done(
        output_index: u32,
        content_index: u32,
        item_id: &str,
        text: &str,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.output_text.done",
            "output_index": output_index,
            "content_index": content_index,
            "item_id": item_id,
            "text": text,
            "logprobs": [],
            "sequence_number": seq
        });
        format!("event: response.output_text.done\ndata: {}\n\n", event)
    }

    pub fn content_part_done(
        output_index: u32,
        content_index: u32,
        item_id: &str,
        part: &OutputContentPart,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.content_part.done",
            "output_index": output_index,
            "content_index": content_index,
            "item_id": item_id,
            "part": part,
            "sequence_number": seq
        });
        format!("event: response.content_part.done\ndata: {}\n\n", event)
    }

    pub fn output_item_done(output_index: u32, item: &OutputItem, seq: u32) -> String {
        let event = serde_json::json!({
            "type": "response.output_item.done",
            "output_index": output_index,
            "item": item,
            "sequence_number": seq
        });
        format!("event: response.output_item.done\ndata: {}\n\n", event)
    }

    pub fn response_completed(response: ResponsesResponse, seq: u32) -> String {
        let event = serde_json::json!({
            "type": "response.completed",
            "response": response,
            "sequence_number": seq
        });
        format!("event: response.completed\ndata: {}\n\n", event)
    }

    pub fn reasoning_summary_part_added(
        output_index: u32,
        summary_index: u32,
        item_id: &str,
        part: &ReasoningSummary,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.reasoning_summary_part.added",
            "output_index": output_index,
            "summary_index": summary_index,
            "item_id": item_id,
            "part": part,
            "sequence_number": seq
        });
        format!(
            "event: response.reasoning_summary_part.added\ndata: {}\n\n",
            event
        )
    }

    pub fn reasoning_summary_text_delta(
        output_index: u32,
        summary_index: u32,
        item_id: &str,
        delta: &str,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.reasoning_summary_text.delta",
            "output_index": output_index,
            "summary_index": summary_index,
            "item_id": item_id,
            "delta": delta,
            "sequence_number": seq
        });
        format!(
            "event: response.reasoning_summary_text.delta\ndata: {}\n\n",
            event
        )
    }

    pub fn reasoning_summary_text_done(
        output_index: u32,
        summary_index: u32,
        item_id: &str,
        text: &str,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.reasoning_summary_text.done",
            "output_index": output_index,
            "summary_index": summary_index,
            "item_id": item_id,
            "text": text,
            "sequence_number": seq
        });
        format!(
            "event: response.reasoning_summary_text.done\ndata: {}\n\n",
            event
        )
    }

    pub fn reasoning_summary_part_done(
        output_index: u32,
        summary_index: u32,
        item_id: &str,
        part: &ReasoningSummary,
        seq: u32,
    ) -> String {
        let event = serde_json::json!({
            "type": "response.reasoning_summary_part.done",
            "output_index": output_index,
            "summary_index": summary_index,
            "item_id": item_id,
            "part": part,
            "sequence_number": seq
        });
        format!(
            "event: response.reasoning_summary_part.done\ndata: {}\n\n",
            event
        )
    }

    pub fn error(error: ResponsesError, seq: u32) -> String {
        let event = serde_json::json!({
            "type": "error",
            "code": error.code.as_deref().unwrap_or(&error.error_type),
            "message": error.message,
            "param": null,
            "sequence_number": seq
        });
        format!("event: error\ndata: {}\n\n", event)
    }
}

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

    #[test]
    fn test_responses_input_text() {
        let json = r#""What is the capital of France?""#;
        let input: ResponsesInput = serde_json::from_str(json).unwrap();
        match input {
            ResponsesInput::Text(s) => assert_eq!(s, "What is the capital of France?"),
            _ => panic!("Expected Text variant"),
        }
    }

    #[test]
    fn test_responses_input_items() {
        let json = r#"[
            {"type": "message", "role": "user", "content": "Hello!"}
        ]"#;
        let input: ResponsesInput = serde_json::from_str(json).unwrap();
        match input {
            ResponsesInput::Items(items) => {
                assert_eq!(items.len(), 1);
            }
            _ => panic!("Expected Items variant"),
        }
    }

    #[test]
    fn test_responses_input_items_shorthand() {
        // LangChain and other SDKs send items without "type" field
        let json = r#"[
            {"role": "user", "content": "Hello!"}
        ]"#;
        let input: ResponsesInput = serde_json::from_str(json).unwrap();
        match input {
            ResponsesInput::Items(items) => {
                assert_eq!(items.len(), 1);
                match &items[0] {
                    InputItem::Message { role, content } => {
                        assert_eq!(*role, InputRole::User);
                        match content {
                            MessageContent::Text(t) => assert_eq!(t, "Hello!"),
                            _ => panic!("Expected Text content"),
                        }
                    }
                    _ => panic!("Expected Message variant"),
                }
            }
            _ => panic!("Expected Items variant"),
        }
    }

    #[test]
    fn test_responses_input_items_shorthand_multi() {
        let json = r#"[
            {"role": "system", "content": "You are helpful."},
            {"role": "user", "content": "Hi!"}
        ]"#;
        let input: ResponsesInput = serde_json::from_str(json).unwrap();
        match input {
            ResponsesInput::Items(items) => assert_eq!(items.len(), 2),
            _ => panic!("Expected Items variant"),
        }
    }

    #[test]
    fn test_responses_request_simple() {
        let json = r#"{
            "model": "gpt-5",
            "input": "Tell me a story"
        }"#;
        let request: ResponsesRequest = serde_json::from_str(json).unwrap();
        assert_eq!(request.model, "gpt-5");
        assert!(!request.stream);
    }

    #[test]
    fn test_responses_request_with_messages() {
        let json = r#"{
            "model": "gpt-5",
            "input": [
                {"type": "message", "role": "user", "content": "Hello!"},
                {"type": "message", "role": "assistant", "content": "Hi there!"}
            ],
            "temperature": 0.7,
            "stream": true
        }"#;
        let request: ResponsesRequest = serde_json::from_str(json).unwrap();
        assert_eq!(request.model, "gpt-5");
        assert_eq!(request.temperature, Some(0.7));
        assert!(request.stream);
    }

    #[test]
    fn test_responses_response_new() {
        let usage = ResponsesUsage {
            input_tokens: 10,
            output_tokens: 20,
            total_tokens: 30,
            output_tokens_details: None,
        };
        let response = ResponsesResponse::new("gpt-5".to_string(), "Hello!".to_string(), usage);

        assert_eq!(response.object, "response");
        assert_eq!(response.model, "gpt-5");
        assert_eq!(response.status, ResponseStatus::Completed);
        assert_eq!(response.output.len(), 1);
        assert_eq!(response.output_text, Some("Hello!".to_string()));
    }

    #[test]
    fn test_responses_response_serialization() {
        let usage = ResponsesUsage {
            input_tokens: 10,
            output_tokens: 20,
            total_tokens: 30,
            output_tokens_details: Some(OutputTokensDetails {
                reasoning_tokens: 0,
            }),
        };
        let response =
            ResponsesResponse::new("gpt-5".to_string(), "Test response".to_string(), usage);

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"object\":\"response\""));
        assert!(json.contains("\"status\":\"completed\""));
        assert!(json.contains("\"output_text\":\"Test response\""));
    }

    #[test]
    fn test_content_part_types() {
        let json = r#"{"type": "input_text", "text": "Hello"}"#;
        let part: ContentPart = serde_json::from_str(json).unwrap();
        match part {
            ContentPart::InputText { text } => assert_eq!(text, "Hello"),
            _ => panic!("Expected InputText variant"),
        }
    }

    #[test]
    fn test_stream_event_creation() {
        let delta = ResponsesStreamEvent::output_text_delta(0, 0, "msg_123", "Hello", 5);
        assert!(delta.contains("event: response.output_text.delta"));
        assert!(delta.contains("\"delta\":\"Hello\""));
        assert!(delta.contains("\"sequence_number\":5"));
        assert!(delta.contains("\"item_id\":\"msg_123\""));
    }

    #[test]
    fn test_error_response() {
        let error = ResponsesError::rate_limit();
        let error_response = ResponsesErrorResponse { error };
        let json = serde_json::to_string(&error_response).unwrap();
        assert!(json.contains("\"type\":\"rate_limit_error\""));
    }

    #[test]
    fn test_responses_response_with_reasoning() {
        let usage = ResponsesUsage {
            input_tokens: 10,
            output_tokens: 20,
            total_tokens: 90,
            output_tokens_details: Some(OutputTokensDetails {
                reasoning_tokens: 60,
            }),
        };
        let response = ResponsesResponse::with_reasoning(
            "o3".to_string(),
            "The answer is 4.".to_string(),
            Some("The model considered the arithmetic.".to_string()),
            usage,
        );

        assert_eq!(response.output.len(), 2);

        // First item should be reasoning
        match &response.output[0] {
            OutputItem::Reasoning {
                id,
                status,
                summary,
                ..
            } => {
                assert!(id.starts_with("rs_"));
                assert_eq!(*status, ItemStatus::Completed);
                let summary = summary.as_ref().unwrap();
                assert_eq!(summary.len(), 1);
                assert_eq!(summary[0].summary_type, "summary_text");
                assert_eq!(summary[0].text, "The model considered the arithmetic.");
            }
            _ => panic!("Expected Reasoning variant"),
        }

        // Second item should be message
        match &response.output[1] {
            OutputItem::Message { id, role, .. } => {
                assert!(id.starts_with("msg_"));
                assert_eq!(*role, OutputRole::Assistant);
            }
            _ => panic!("Expected Message variant"),
        }
    }

    #[test]
    fn test_responses_response_with_reasoning_no_summary() {
        let usage = ResponsesUsage {
            input_tokens: 10,
            output_tokens: 20,
            total_tokens: 90,
            output_tokens_details: Some(OutputTokensDetails {
                reasoning_tokens: 60,
            }),
        };
        let response = ResponsesResponse::with_reasoning(
            "o3".to_string(),
            "The answer.".to_string(),
            None,
            usage,
        );

        assert_eq!(response.output.len(), 2);

        // First item: reasoning with no summary
        match &response.output[0] {
            OutputItem::Reasoning { summary, .. } => {
                assert!(summary.is_none());
            }
            _ => panic!("Expected Reasoning variant"),
        }
    }

    #[test]
    fn test_reasoning_output_item_serialization() {
        let item = OutputItem::Reasoning {
            id: "rs_test123".to_string(),
            status: ItemStatus::Completed,
            summary: Some(vec![ReasoningSummary {
                summary_type: "summary_text".to_string(),
                text: "Analyzing the problem.".to_string(),
            }]),
        };

        let json = serde_json::to_string(&item).unwrap();
        assert!(json.contains("\"type\":\"reasoning\""));
        assert!(json.contains("\"id\":\"rs_test123\""));
        assert!(json.contains("\"summary_text\""));
        assert!(json.contains("Analyzing the problem."));
    }

    #[test]
    fn test_reasoning_stream_event_helpers() {
        let summary = ReasoningSummary {
            summary_type: "summary_text".to_string(),
            text: String::new(),
        };

        let event = ResponsesStreamEvent::reasoning_summary_part_added(0, 0, "rs_123", &summary, 3);
        assert!(event.contains("event: response.reasoning_summary_part.added"));
        assert!(event.contains("\"output_index\":0"));
        assert!(event.contains("\"item_id\":\"rs_123\""));
        assert!(event.contains("\"sequence_number\":3"));

        let delta =
            ResponsesStreamEvent::reasoning_summary_text_delta(0, 0, "rs_123", "Thinking", 4);
        assert!(delta.contains("event: response.reasoning_summary_text.delta"));
        assert!(delta.contains("\"delta\":\"Thinking\""));
        assert!(delta.contains("\"sequence_number\":4"));

        let done =
            ResponsesStreamEvent::reasoning_summary_text_done(0, 0, "rs_123", "Full summary.", 5);
        assert!(done.contains("event: response.reasoning_summary_text.done"));
        assert!(done.contains("\"text\":\"Full summary.\""));
        assert!(done.contains("\"sequence_number\":5"));

        let part_done =
            ResponsesStreamEvent::reasoning_summary_part_done(0, 0, "rs_123", &summary, 6);
        assert!(part_done.contains("event: response.reasoning_summary_part.done"));
        assert!(part_done.contains("\"sequence_number\":6"));
    }

    #[test]
    fn test_reasoning_config_deserialization() {
        let json = r#"{
            "model": "o3",
            "input": "Hello",
            "reasoning": {
                "effort": "high",
                "summary": "auto"
            }
        }"#;
        let request: ResponsesRequest = serde_json::from_str(json).unwrap();
        let reasoning = request.reasoning.unwrap();
        assert_eq!(reasoning.effort, Some("high".to_string()));
        assert_eq!(reasoning.summary, Some("auto".to_string()));
    }
}