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
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
// Gemini Interactions API types
// https://ai.google.dev/gemini-api/docs/interactions

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use validator::{Validate, ValidationError};

use super::{
    common::{default_true, deserialize_null_as_false, Function, GenerationRequest},
    sampling_params::validate_top_p_value,
    validated::Normalizable,
};

// ============================================================================
// Request Type
// ============================================================================

#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize, Validate)]
#[validate(schema(function = "validate_interactions_request"))]
pub struct InteractionsRequest {
    /// Model identifier (e.g., "gemini-2.5-flash")
    /// Required if agent is not provided
    pub model: Option<String>,

    /// Agent name (e.g., "deep-research-pro-preview-12-2025")
    /// Required if model is not provided
    pub agent: Option<String>,

    /// Input content - can be string or array of Content objects
    #[validate(custom(function = "validate_input"))]
    pub input: InteractionsInput,

    /// System instruction for the model
    pub system_instruction: Option<String>,

    /// Available tools
    #[validate(custom(function = "validate_tools"))]
    pub tools: Option<Vec<InteractionsTool>>,

    /// Response format for structured outputs
    pub response_format: Option<Value>,

    /// MIME type for the response (required if response_format is set)
    pub response_mime_type: Option<String>,

    /// Whether to stream the response
    #[serde(default, deserialize_with = "deserialize_null_as_false")]
    pub stream: bool,

    /// Whether to store the interaction (default: true)
    #[serde(default = "default_true")]
    pub store: bool,

    /// Run request in background (agents only)
    #[serde(default)]
    pub background: bool,

    /// Generation configuration
    #[validate(nested)]
    pub generation_config: Option<GenerationConfig>,

    /// Agent configuration (only applicable when agent is specified)
    pub agent_config: Option<AgentConfig>,

    /// Response modalities (text, image, audio)
    pub response_modalities: Option<Vec<ResponseModality>>,

    /// Link to prior interaction for stateful conversations
    pub previous_interaction_id: Option<String>,
}

impl Default for InteractionsRequest {
    fn default() -> Self {
        Self {
            model: None,
            agent: None,
            agent_config: None,
            input: InteractionsInput::Text(String::new()),
            system_instruction: None,
            previous_interaction_id: None,
            tools: None,
            generation_config: None,
            response_format: None,
            response_mime_type: None,
            response_modalities: None,
            stream: false,
            background: false,
            store: true,
        }
    }
}

impl Normalizable for InteractionsRequest {
    // Use default no-op implementation
}

impl GenerationRequest for InteractionsRequest {
    fn is_stream(&self) -> bool {
        self.stream
    }

    fn get_model(&self) -> Option<&str> {
        self.model.as_deref()
    }

    fn extract_text_for_routing(&self) -> String {
        fn extract_from_content(content: &Content) -> Option<String> {
            match content {
                Content::Text { text, .. } => text.clone(),
                _ => None,
            }
        }

        fn extract_from_turn(turn: &Turn) -> String {
            match &turn.content {
                Some(TurnContent::Text(text)) => text.clone(),
                Some(TurnContent::Contents(contents)) => contents
                    .iter()
                    .filter_map(extract_from_content)
                    .collect::<Vec<String>>()
                    .join(" "),
                None => String::new(),
            }
        }

        match &self.input {
            InteractionsInput::Text(text) => text.clone(),
            InteractionsInput::Content(content) => {
                extract_from_content(content).unwrap_or_default()
            }
            InteractionsInput::Contents(contents) => contents
                .iter()
                .filter_map(extract_from_content)
                .collect::<Vec<String>>()
                .join(" "),
            InteractionsInput::Turns(turns) => turns
                .iter()
                .map(extract_from_turn)
                .collect::<Vec<String>>()
                .join(" "),
        }
    }
}

// ============================================================================
// Response Type
// ============================================================================

#[skip_serializing_none]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Interaction {
    /// Object type, always "interaction"
    pub object: Option<String>,

    /// Model used
    pub model: Option<String>,

    /// Agent used
    pub agent: Option<String>,

    /// Interaction ID
    pub id: String,

    /// Interaction status
    pub status: InteractionsStatus,

    /// Creation timestamp (ISO 8601)
    pub created: Option<String>,

    /// Last update timestamp (ISO 8601)
    pub updated: Option<String>,

    /// Role of the interaction
    pub role: Option<String>,

    /// Output content
    pub outputs: Option<Vec<Content>>,

    /// Usage information
    pub usage: Option<InteractionsUsage>,

    /// Previous interaction ID for conversation threading
    pub previous_interaction_id: Option<String>,
}

impl Interaction {
    /// Check if the interaction is complete
    pub fn is_complete(&self) -> bool {
        matches!(self.status, InteractionsStatus::Completed)
    }

    /// Check if the interaction is in progress
    pub fn is_in_progress(&self) -> bool {
        matches!(self.status, InteractionsStatus::InProgress)
    }

    /// Check if the interaction failed
    pub fn is_failed(&self) -> bool {
        matches!(self.status, InteractionsStatus::Failed)
    }

    /// Check if the interaction requires action (tool execution)
    pub fn requires_action(&self) -> bool {
        matches!(self.status, InteractionsStatus::RequiresAction)
    }
}

// ============================================================================
// Streaming Event Types (SSE)
// ============================================================================

/// Server-Sent Event for Interactions API streaming
/// See: https://ai.google.dev/api/interactions-api#streaming
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "event_type")]
pub enum InteractionStreamEvent {
    /// Emitted when an interaction begins processing
    #[serde(rename = "interaction.start")]
    InteractionStart {
        /// The interaction object
        interaction: Option<Interaction>,
        /// Event ID for resuming streams
        event_id: Option<String>,
    },

    /// Emitted when an interaction completes
    #[serde(rename = "interaction.complete")]
    InteractionComplete {
        /// The interaction object
        interaction: Option<Interaction>,
        /// Event ID for resuming streams
        event_id: Option<String>,
    },

    /// Emitted when interaction status changes
    #[serde(rename = "interaction.status_update")]
    InteractionStatusUpdate {
        /// The interaction ID
        interaction_id: Option<String>,
        /// The new status
        status: Option<InteractionsStatus>,
        /// Event ID for resuming streams
        event_id: Option<String>,
    },

    /// Signals the beginning of a new content block
    #[serde(rename = "content.start")]
    ContentStart {
        /// Content block index in outputs array
        index: Option<u32>,
        /// The content object
        content: Option<Content>,
        /// Event ID for resuming streams
        event_id: Option<String>,
    },

    /// Streams incremental content updates
    #[serde(rename = "content.delta")]
    ContentDelta {
        /// Content block index in outputs array
        index: Option<u32>,
        /// Event ID for resuming streams
        event_id: Option<String>,
        /// The delta content
        delta: Option<Delta>,
    },

    /// Marks the end of a content block
    #[serde(rename = "content.stop")]
    ContentStop {
        /// Content block index in outputs array
        index: Option<u32>,
        /// Event ID for resuming streams
        event_id: Option<String>,
    },

    /// Error event
    #[serde(rename = "error")]
    Error {
        /// Error information
        error: Option<InteractionsError>,
        /// Event ID for resuming streams
        event_id: Option<String>,
    },
}

/// Delta content for streaming updates
/// See: https://ai.google.dev/api/interactions-api#ContentDelta
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Delta {
    /// Text delta
    Text {
        text: Option<String>,
        annotations: Option<Vec<Annotation>>,
    },
    /// Image delta
    Image {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<ImageMimeType>,
        resolution: Option<MediaResolution>,
    },
    /// Audio delta
    Audio {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<AudioMimeType>,
    },
    /// Document delta
    Document {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<DocumentMimeType>,
    },
    /// Video delta
    Video {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<VideoMimeType>,
        resolution: Option<MediaResolution>,
    },
    /// Thought summary delta
    ThoughtSummary {
        content: Option<ThoughtSummaryContent>,
    },
    /// Thought signature delta
    ThoughtSignature { signature: Option<String> },
    /// Function call delta
    FunctionCall {
        name: Option<String>,
        arguments: Option<String>,
        id: Option<String>,
    },
    /// Function result delta
    FunctionResult {
        name: Option<String>,
        is_error: Option<bool>,
        result: Option<Value>,
        call_id: Option<String>,
    },
    /// Code execution call delta
    CodeExecutionCall {
        arguments: Option<CodeExecutionArguments>,
        id: Option<String>,
    },
    /// Code execution result delta
    CodeExecutionResult {
        result: Option<String>,
        is_error: Option<bool>,
        signature: Option<String>,
        call_id: Option<String>,
    },
    /// URL context call delta
    UrlContextCall {
        arguments: Option<UrlContextArguments>,
        id: Option<String>,
    },
    /// URL context result delta
    UrlContextResult {
        signature: Option<String>,
        result: Option<Vec<UrlContextResultData>>,
        is_error: Option<bool>,
        call_id: Option<String>,
    },
    /// Google search call delta
    GoogleSearchCall {
        arguments: Option<GoogleSearchArguments>,
        id: Option<String>,
    },
    /// Google search result delta
    GoogleSearchResult {
        signature: Option<String>,
        result: Option<Vec<GoogleSearchResultData>>,
        is_error: Option<bool>,
        call_id: Option<String>,
    },
    /// File search call delta
    FileSearchCall { id: Option<String> },
    /// File search result delta
    FileSearchResult {
        result: Option<Vec<FileSearchResultData>>,
    },
    /// MCP server tool call delta
    McpServerToolCall {
        name: Option<String>,
        server_name: Option<String>,
        arguments: Option<Value>,
        id: Option<String>,
    },
    /// MCP server tool result delta
    McpServerToolResult {
        name: Option<String>,
        server_name: Option<String>,
        result: Option<Value>,
        call_id: Option<String>,
    },
}

/// Error information in streaming events
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InteractionsError {
    /// Error code
    pub code: Option<String>,
    /// Error message
    pub message: Option<String>,
}

// ============================================================================
// Query Parameters
// ============================================================================

/// Query parameters for GET /interactions/{id}
#[skip_serializing_none]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct InteractionsGetParams {
    /// Whether to stream the response
    pub stream: Option<bool>,
    /// Last event ID for resuming a stream
    pub last_event_id: Option<String>,
    /// API version
    pub api_version: Option<String>,
}

/// Query parameters for DELETE /interactions/{id}
#[skip_serializing_none]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct InteractionsDeleteParams {
    /// API version
    pub api_version: Option<String>,
}

/// Query parameters for POST /interactions/{id}/cancel
#[skip_serializing_none]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct InteractionsCancelParams {
    /// API version
    pub api_version: Option<String>,
}

// ============================================================================
// Interaction Tools
// ============================================================================

/// Interaction tool types
/// See: https://ai.google.dev/api/interactions-api#Resource:Tool
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InteractionsTool {
    /// Function tool with function declaration
    Function(Function),
    /// Google Search built-in tool
    GoogleSearch {},
    /// Code Execution built-in tool
    CodeExecution {},
    /// URL Context built-in tool
    UrlContext {},
    /// MCP Server tool
    McpServer {
        name: Option<String>,
        url: Option<String>,
        headers: Option<HashMap<String, String>>,
        allowed_tools: Option<AllowedTools>,
    },
    /// File Search built-in tool
    FileSearch {
        /// Names of file search stores to search
        file_search_store_names: Option<Vec<String>>,
        /// Maximum number of results to return
        top_k: Option<u32>,
        /// Metadata filter for search
        metadata_filter: Option<String>,
    },
}

/// Allowed tools configuration for MCP server
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct AllowedTools {
    /// Tool choice mode: auto, any, none, or validated
    pub mode: Option<ToolChoiceType>,
    /// List of allowed tool names
    pub tools: Option<Vec<String>>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ToolChoiceType {
    Auto,
    Any,
    None,
    Validated,
}

// ============================================================================
// Generation Config (Gemini-specific)
// ============================================================================

#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize, Validate)]
pub struct GenerationConfig {
    #[validate(range(min = 0.0, max = 2.0))]
    pub temperature: Option<f32>,

    #[validate(custom(function = "validate_top_p_value"))]
    pub top_p: Option<f32>,

    pub seed: Option<i64>,

    #[validate(custom(function = "validate_stop_sequences"))]
    pub stop_sequences: Option<Vec<String>>,

    pub tool_choice: Option<ToolChoice>,

    pub thinking_level: Option<ThinkingLevel>,

    pub thinking_summaries: Option<ThinkingSummaries>,

    #[validate(range(min = 1))]
    pub max_output_tokens: Option<u32>,

    pub speech_config: Option<Vec<SpeechConfig>>,

    pub image_config: Option<ImageConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingLevel {
    Minimal,
    Low,
    Medium,
    High,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingSummaries {
    Auto,
    None,
}

/// Tool choice can be a simple mode or a detailed config
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ToolChoice {
    Type(ToolChoiceType),
    Config(ToolChoiceConfig),
}

#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ToolChoiceConfig {
    pub allowed_tools: Option<AllowedTools>,
}

#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SpeechConfig {
    pub voice: Option<String>,
    pub language: Option<String>,
    pub speaker: Option<String>,
}

#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ImageConfig {
    pub aspect_ratio: Option<AspectRatio>,
    pub image_size: Option<ImageSize>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum AspectRatio {
    #[serde(rename = "1:1")]
    Square,
    #[serde(rename = "2:3")]
    Portrait2x3,
    #[serde(rename = "3:2")]
    Landscape3x2,
    #[serde(rename = "3:4")]
    Portrait3x4,
    #[serde(rename = "4:3")]
    Landscape4x3,
    #[serde(rename = "4:5")]
    Portrait4x5,
    #[serde(rename = "5:4")]
    Landscape5x4,
    #[serde(rename = "9:16")]
    Portrait9x16,
    #[serde(rename = "16:9")]
    Landscape16x9,
    #[serde(rename = "21:9")]
    UltraWide,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum ImageSize {
    #[serde(rename = "1K")]
    OneK,
    #[serde(rename = "2K")]
    TwoK,
    #[serde(rename = "4K")]
    FourK,
}

/// Agent configuration
/// See: https://ai.google.dev/api/interactions-api#CreateInteraction-deep_research
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentConfig {
    /// Dynamic agent configuration
    Dynamic {},
    /// Deep Research agent configuration
    #[serde(rename = "deep-research")]
    DeepResearch {
        /// Whether to include thought summaries ("auto" or "none")
        #[serde(skip_serializing_if = "Option::is_none")]
        thinking_summaries: Option<ThinkingSummaries>,
    },
}

// ============================================================================
// Input/Output Types
// ============================================================================

/// Input can be Content, array of Content, array of Turn, or string
/// See: https://ai.google.dev/api/interactions-api#request-body
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InteractionsInput {
    /// Simple text input
    Text(String),
    /// Single content block
    Content(Content),
    /// Array of content blocks
    Contents(Vec<Content>),
    /// Array of turns (conversation history)
    Turns(Vec<Turn>),
}

/// A turn in a conversation with role and content
/// See: https://ai.google.dev/api/interactions-api#Resource:Turn
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Turn {
    /// Role: "user" or "model"
    pub role: Option<String>,
    /// Content can be array of Content or string
    pub content: Option<TurnContent>,
}

/// Turn content can be array of Content or a simple string
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TurnContent {
    Contents(Vec<Content>),
    Text(String),
}

/// Content is a polymorphic type representing different content types
/// See: https://ai.google.dev/api/interactions-api#Resource:Content
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Content {
    /// Text content
    Text {
        text: Option<String>,
        annotations: Option<Vec<Annotation>>,
    },

    /// Image content
    Image {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<ImageMimeType>,
        resolution: Option<MediaResolution>,
    },

    /// Audio content
    Audio {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<AudioMimeType>,
    },

    /// Document content (PDF)
    Document {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<DocumentMimeType>,
    },

    /// Video content
    Video {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<VideoMimeType>,
        resolution: Option<MediaResolution>,
    },

    /// Thought content
    Thought {
        signature: Option<String>,
        summary: Option<Vec<ThoughtSummaryContent>>,
    },

    /// Function call content
    FunctionCall {
        name: String,
        arguments: Value,
        id: String,
    },

    /// Function result content
    FunctionResult {
        name: Option<String>,
        is_error: Option<bool>,
        result: Value,
        call_id: String,
    },

    /// Code execution call content
    CodeExecutionCall {
        arguments: Option<CodeExecutionArguments>,
        id: Option<String>,
    },

    /// Code execution result content
    CodeExecutionResult {
        result: Option<String>,
        is_error: Option<bool>,
        signature: Option<String>,
        call_id: Option<String>,
    },

    /// URL context call content
    UrlContextCall {
        arguments: Option<UrlContextArguments>,
        id: Option<String>,
    },

    /// URL context result content
    UrlContextResult {
        signature: Option<String>,
        result: Option<Vec<UrlContextResultData>>,
        is_error: Option<bool>,
        call_id: Option<String>,
    },

    /// Google search call content
    GoogleSearchCall {
        arguments: Option<GoogleSearchArguments>,
        id: Option<String>,
    },

    /// Google search result content
    GoogleSearchResult {
        signature: Option<String>,
        result: Option<Vec<GoogleSearchResultData>>,
        is_error: Option<bool>,
        call_id: Option<String>,
    },

    /// File search call content
    FileSearchCall { id: Option<String> },

    /// File search result content
    FileSearchResult {
        result: Option<Vec<FileSearchResultData>>,
    },

    /// MCP server tool call content
    McpServerToolCall {
        name: String,
        server_name: String,
        arguments: Value,
        id: String,
    },

    /// MCP server tool result content
    McpServerToolResult {
        name: Option<String>,
        server_name: Option<String>,
        result: Value,
        call_id: String,
    },
}

/// Content types allowed in thought summary (text or image only)
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ThoughtSummaryContent {
    /// Text content in thought summary
    Text {
        text: Option<String>,
        annotations: Option<Vec<Annotation>>,
    },
    /// Image content in thought summary
    Image {
        data: Option<String>,
        uri: Option<String>,
        mime_type: Option<ImageMimeType>,
        resolution: Option<MediaResolution>,
    },
}

/// Annotation for text content (citations)
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Annotation {
    /// Start of the attributed segment, measured in bytes
    pub start_index: Option<u32>,
    /// End of the attributed segment, exclusive
    pub end_index: Option<u32>,
    /// Source attributed for a portion of the text (URL, title, or other identifier)
    pub source: Option<String>,
}

/// Arguments for URL context call
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct UrlContextArguments {
    /// The URLs to fetch
    pub urls: Option<Vec<String>>,
}

/// Result data for URL context result
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct UrlContextResultData {
    /// The URL that was fetched
    pub url: Option<String>,
    /// The status of the URL retrieval
    pub status: Option<UrlContextStatus>,
}

/// Status of URL context retrieval
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum UrlContextStatus {
    Success,
    Error,
    Paywall,
    Unsafe,
}

/// Arguments for Google search call
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GoogleSearchArguments {
    /// Web search queries
    pub queries: Option<Vec<String>>,
}

/// Result data for Google search result
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GoogleSearchResultData {
    /// URI reference of the search result
    pub url: Option<String>,
    /// Title of the search result
    pub title: Option<String>,
    /// Web content snippet
    pub rendered_content: Option<String>,
}

/// Result data for file search result
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FileSearchResultData {
    /// Search result title
    pub title: Option<String>,
    /// Search result text
    pub text: Option<String>,
    /// Name of the file search store
    pub file_search_store: Option<String>,
}

/// Arguments for code execution call
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CodeExecutionArguments {
    /// Programming language (currently only Python is supported)
    pub language: Option<CodeExecutionLanguage>,
    /// The code to be executed
    pub code: Option<String>,
}

/// Supported languages for code execution
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CodeExecutionLanguage {
    Python,
}

/// Image/video resolution options
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MediaResolution {
    Low,
    Medium,
    High,
    UltraHigh,
}

/// Supported image MIME types
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum ImageMimeType {
    #[serde(rename = "image/png")]
    Png,
    #[serde(rename = "image/jpeg")]
    Jpeg,
    #[serde(rename = "image/webp")]
    Webp,
    #[serde(rename = "image/heic")]
    Heic,
    #[serde(rename = "image/heif")]
    Heif,
}

impl ImageMimeType {
    pub fn as_str(&self) -> &'static str {
        match self {
            ImageMimeType::Png => "image/png",
            ImageMimeType::Jpeg => "image/jpeg",
            ImageMimeType::Webp => "image/webp",
            ImageMimeType::Heic => "image/heic",
            ImageMimeType::Heif => "image/heif",
        }
    }
}

/// Supported audio MIME types
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum AudioMimeType {
    #[serde(rename = "audio/wav")]
    Wav,
    #[serde(rename = "audio/mp3")]
    Mp3,
    #[serde(rename = "audio/aiff")]
    Aiff,
    #[serde(rename = "audio/aac")]
    Aac,
    #[serde(rename = "audio/ogg")]
    Ogg,
    #[serde(rename = "audio/flac")]
    Flac,
}

impl AudioMimeType {
    pub fn as_str(&self) -> &'static str {
        match self {
            AudioMimeType::Wav => "audio/wav",
            AudioMimeType::Mp3 => "audio/mp3",
            AudioMimeType::Aiff => "audio/aiff",
            AudioMimeType::Aac => "audio/aac",
            AudioMimeType::Ogg => "audio/ogg",
            AudioMimeType::Flac => "audio/flac",
        }
    }
}

/// Supported document MIME types
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum DocumentMimeType {
    #[serde(rename = "application/pdf")]
    Pdf,
}

impl DocumentMimeType {
    pub fn as_str(&self) -> &'static str {
        match self {
            DocumentMimeType::Pdf => "application/pdf",
        }
    }
}

/// Supported video MIME types
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum VideoMimeType {
    #[serde(rename = "video/mp4")]
    Mp4,
    #[serde(rename = "video/mpeg")]
    Mpeg,
    #[serde(rename = "video/mov")]
    Mov,
    #[serde(rename = "video/avi")]
    Avi,
    #[serde(rename = "video/x-flv")]
    Flv,
    #[serde(rename = "video/mpg")]
    Mpg,
    #[serde(rename = "video/webm")]
    Webm,
    #[serde(rename = "video/wmv")]
    Wmv,
    #[serde(rename = "video/3gpp")]
    ThreeGpp,
}

impl VideoMimeType {
    pub fn as_str(&self) -> &'static str {
        match self {
            VideoMimeType::Mp4 => "video/mp4",
            VideoMimeType::Mpeg => "video/mpeg",
            VideoMimeType::Mov => "video/mov",
            VideoMimeType::Avi => "video/avi",
            VideoMimeType::Flv => "video/x-flv",
            VideoMimeType::Mpg => "video/mpg",
            VideoMimeType::Webm => "video/webm",
            VideoMimeType::Wmv => "video/wmv",
            VideoMimeType::ThreeGpp => "video/3gpp",
        }
    }
}

// ============================================================================
// Status Types
// ============================================================================

#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InteractionsStatus {
    #[default]
    InProgress,
    RequiresAction,
    Completed,
    Failed,
    Cancelled,
}

// ============================================================================
// Usage Types
// ============================================================================

/// Token count by modality
#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ModalityTokens {
    pub modality: Option<ResponseModality>,
    pub tokens: Option<u32>,
}

#[skip_serializing_none]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InteractionsUsage {
    pub total_input_tokens: Option<u32>,
    pub input_tokens_by_modality: Option<Vec<ModalityTokens>>,
    pub total_cached_tokens: Option<u32>,
    pub cached_tokens_by_modality: Option<Vec<ModalityTokens>>,
    pub total_output_tokens: Option<u32>,
    pub output_tokens_by_modality: Option<Vec<ModalityTokens>>,
    pub total_tool_use_tokens: Option<u32>,
    pub tool_use_tokens_by_modality: Option<Vec<ModalityTokens>>,
    pub total_thought_tokens: Option<u32>,
    pub total_tokens: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ResponseModality {
    Text,
    Image,
    Audio,
}

fn is_option_blank(v: Option<&String>) -> bool {
    v.map(|s| s.trim().is_empty()).unwrap_or(true)
}

fn validate_interactions_request(req: &InteractionsRequest) -> Result<(), ValidationError> {
    // Exactly one of model or agent must be provided
    if is_option_blank(req.model.as_ref()) && is_option_blank(req.agent.as_ref()) {
        return Err(ValidationError::new("model_or_agent_required"));
    }
    if !is_option_blank(req.model.as_ref()) && !is_option_blank(req.agent.as_ref()) {
        let mut e = ValidationError::new("model_and_agent_mutually_exclusive");
        e.message = Some("Cannot set both model and agent. Provide exactly one.".into());
        return Err(e);
    }

    // response_mime_type is required when response_format is set
    if req.response_format.is_some() && is_option_blank(req.response_mime_type.as_ref()) {
        return Err(ValidationError::new("response_mime_type_required"));
    }

    // background mode is required for agent interactions, and only for agents
    if !is_option_blank(req.agent.as_ref()) && !req.background {
        let mut e = ValidationError::new("agent_requires_background");
        e.message = Some("Agent interactions require background mode to be enabled.".into());
        return Err(e);
    }
    if !is_option_blank(req.model.as_ref()) && req.background {
        let mut e = ValidationError::new("background_requires_agent");
        e.message = Some("Background mode is only supported for agent interactions.".into());
        return Err(e);
    }

    // background and stream are mutually exclusive
    if req.background && req.stream {
        let mut e = ValidationError::new("background_conflicts_with_stream");
        e.message = Some("Cannot set both background and stream to true.".into());
        return Err(e);
    }
    Ok(())
}

fn validate_tools(tools: &[InteractionsTool]) -> Result<(), ValidationError> {
    // FileSearch tool is not supported yet
    if tools
        .iter()
        .any(|t| matches!(t, InteractionsTool::FileSearch { .. }))
    {
        return Err(ValidationError::new("file_search_tool_not_supported"));
    }
    Ok(())
}

fn validate_input(input: &InteractionsInput) -> Result<(), ValidationError> {
    // Reject empty input
    let empty_msg = match input {
        InteractionsInput::Text(s) if s.trim().is_empty() => Some("Input text cannot be empty"),
        InteractionsInput::Content(content) if is_content_empty(content) => {
            Some("Input content cannot be empty")
        }
        InteractionsInput::Contents(contents) if contents.is_empty() => {
            Some("Input content array cannot be empty")
        }
        InteractionsInput::Contents(contents) if contents.iter().any(is_content_empty) => {
            Some("Input content array contains empty content items")
        }
        InteractionsInput::Turns(turns) if turns.is_empty() => {
            Some("Input turns array cannot be empty")
        }
        InteractionsInput::Turns(turns) if turns.iter().any(is_turn_empty) => {
            Some("Input turns array contains empty turn items")
        }
        _ => None,
    };
    if let Some(msg) = empty_msg {
        let mut e = ValidationError::new("input_cannot_be_empty");
        e.message = Some(msg.into());
        return Err(e);
    }

    // Reject unsupported file search content
    fn has_file_search_content(content: &Content) -> bool {
        matches!(
            content,
            Content::FileSearchCall { .. } | Content::FileSearchResult { .. }
        )
    }

    fn check_turn(turn: &Turn) -> bool {
        if let Some(content) = &turn.content {
            match content {
                TurnContent::Contents(contents) => contents.iter().any(has_file_search_content),
                TurnContent::Text(_) => false,
            }
        } else {
            false
        }
    }

    let has_file_search = match input {
        InteractionsInput::Text(_) => false,
        InteractionsInput::Content(content) => has_file_search_content(content),
        InteractionsInput::Contents(contents) => contents.iter().any(has_file_search_content),
        InteractionsInput::Turns(turns) => turns.iter().any(check_turn),
    };

    if has_file_search {
        return Err(ValidationError::new("file_search_content_not_supported"));
    }
    Ok(())
}

fn is_content_empty(content: &Content) -> bool {
    match content {
        Content::Text { text, .. } => is_option_blank(text.as_ref()),
        Content::Image { data, uri, .. }
        | Content::Audio { data, uri, .. }
        | Content::Document { data, uri, .. }
        | Content::Video { data, uri, .. } => {
            is_option_blank(data.as_ref()) && is_option_blank(uri.as_ref())
        }
        Content::CodeExecutionCall { id, .. }
        | Content::UrlContextCall { id, .. }
        | Content::GoogleSearchCall { id, .. } => is_option_blank(id.as_ref()),
        Content::CodeExecutionResult { call_id, .. }
        | Content::UrlContextResult { call_id, .. }
        | Content::GoogleSearchResult { call_id, .. } => is_option_blank(call_id.as_ref()),
        _ => false,
    }
}

fn is_turn_empty(turn: &Turn) -> bool {
    match &turn.content {
        None => true,
        Some(TurnContent::Text(s)) => s.trim().is_empty(),
        Some(TurnContent::Contents(contents)) => {
            contents.is_empty() || contents.iter().any(is_content_empty)
        }
    }
}

fn validate_stop_sequences(seqs: &[String]) -> Result<(), ValidationError> {
    if seqs.len() > 5 {
        let mut e = ValidationError::new("too_many_stop_sequences");
        e.message = Some("Maximum 5 stop sequences allowed".into());
        return Err(e);
    }
    if seqs.iter().any(|s| s.trim().is_empty()) {
        let mut e = ValidationError::new("stop_sequences_cannot_be_empty");
        e.message = Some("Stop sequences cannot contain empty strings".into());
        return Err(e);
    }
    Ok(())
}