adk-gemini 3.0.0

Rust client for Google Gemini API
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
use reqwest::Url;
use serde::{Deserialize, Serialize, de};
use time::OffsetDateTime;

use crate::{
    Content, Modality, Part,
    safety::{SafetyRating, SafetySetting},
};

/// Reason why generation finished
///
/// The enum is `#[non_exhaustive]`: the API adds finish reasons, and a value this version does
/// not know deserializes as [`Other`](Self::Other).
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum FinishReason {
    /// Default value. This value is unused.
    FinishReasonUnspecified,
    /// Natural stop point of the model or provided stop sequence.
    Stop,
    /// The maximum number of tokens as specified in the request was reached.
    MaxTokens,
    /// The response candidate content was flagged for safety reasons.
    Safety,
    /// The response candidate content was flagged for recitation reasons.
    Recitation,
    /// The response candidate content was flagged for using an unsupported language.
    Language,
    /// Unknown reason.
    Other,
    /// Token generation stopped because the content contains forbidden terms.
    Blocklist,
    /// Token generation stopped for potentially containing prohibited content.
    ProhibitedContent,
    /// Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
    Spii,
    /// The function call generated by the model is invalid.
    MalformedFunctionCall,
    /// Token generation stopped because the response was blocked by Model Armor.
    ModelArmor,
    /// Token generation stopped because generated images contain safety violations.
    ImageSafety,
    /// Model generated a tool call but no tools were enabled in the request.
    UnexpectedToolCall,
    /// Model called too many tools consecutively, thus the system exited execution.
    TooManyToolCalls,
    /// The request is missing at least one thought signature.
    MissingThoughtSignature,
    /// Generation finished because the response was malformed.
    MalformedResponse,
    /// The response reached the per-request token limit before generation finished; a later
    /// request that carries the response's continuation token continues it (long decode).
    Continuation,
}

impl FinishReason {
    fn from_wire_str(value: &str) -> Self {
        match value {
            "FINISH_REASON_UNSPECIFIED" => Self::FinishReasonUnspecified,
            "STOP" => Self::Stop,
            "MAX_TOKENS" => Self::MaxTokens,
            "SAFETY" => Self::Safety,
            "RECITATION" => Self::Recitation,
            "LANGUAGE" => Self::Language,
            "OTHER" => Self::Other,
            "BLOCKLIST" => Self::Blocklist,
            "PROHIBITED_CONTENT" => Self::ProhibitedContent,
            "SPII" => Self::Spii,
            "MALFORMED_FUNCTION_CALL" => Self::MalformedFunctionCall,
            "MODEL_ARMOR" => Self::ModelArmor,
            "IMAGE_SAFETY" => Self::ImageSafety,
            "UNEXPECTED_TOOL_CALL" => Self::UnexpectedToolCall,
            "TOO_MANY_TOOL_CALLS" => Self::TooManyToolCalls,
            "MISSING_THOUGHT_SIGNATURE" => Self::MissingThoughtSignature,
            "MALFORMED_RESPONSE" => Self::MalformedResponse,
            "CONTINUATION" => Self::Continuation,
            _ => Self::Other,
        }
    }

    fn from_wire_number(value: i64) -> Self {
        match value {
            0 => Self::FinishReasonUnspecified,
            1 => Self::Stop,
            2 => Self::MaxTokens,
            3 => Self::Safety,
            4 => Self::Recitation,
            5 => Self::Other,
            6 => Self::Blocklist,
            7 => Self::ProhibitedContent,
            8 => Self::Spii,
            9 => Self::MalformedFunctionCall,
            10 => Self::ModelArmor,
            _ => Self::Other,
        }
    }
}

impl<'de> Deserialize<'de> for FinishReason {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(s) => Ok(Self::from_wire_str(&s)),
            serde_json::Value::Number(n) => {
                n.as_i64().map(Self::from_wire_number).ok_or_else(|| {
                    de::Error::custom("finishReason must be an integer-compatible number")
                })
            }
            _ => Err(de::Error::custom("finishReason must be a string or integer")),
        }
    }
}

/// Citation metadata for content
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CitationMetadata {
    /// The citation sources
    #[serde(default)]
    pub citation_sources: Vec<CitationSource>,
}

/// Citation source
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CitationSource {
    /// The URI of the citation source
    pub uri: Option<String>,
    /// The title of the citation source
    pub title: Option<String>,
    /// The start index of the citation in the response
    pub start_index: Option<i32>,
    /// The end index of the citation in the response
    pub end_index: Option<i32>,
    /// The license of the citation source
    pub license: Option<String>,
    /// The publication date of the citation source
    #[serde(default, with = "time::serde::rfc3339::option")]
    pub publication_date: Option<OffsetDateTime>,
}

/// A candidate response
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Candidate {
    /// The content of the candidate
    #[serde(default)]
    pub content: Content,
    /// The safety ratings for the candidate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub safety_ratings: Option<Vec<SafetyRating>>,
    /// The citation metadata for the candidate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub citation_metadata: Option<CitationMetadata>,
    /// The grounding metadata for the candidate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grounding_metadata: Option<GroundingMetadata>,
    /// The finish reason for the candidate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_reason: Option<FinishReason>,
    /// The index of the candidate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<i32>,
    /// Log probabilities of the chosen and top tokens, when the request set
    /// [`GenerationConfig::response_logprobs`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logprobs_result: Option<LogprobsResult>,
    /// Average log probability of the candidate's tokens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub avg_logprobs: Option<f64>,
}

/// Log probabilities of a candidate's tokens.
///
/// # Example
///
/// ```
/// use adk_gemini::LogprobsResult;
///
/// let result: LogprobsResult = serde_json::from_value(serde_json::json!({
///     "topCandidates": [{"candidates": [{"token": "Hi", "tokenId": 17, "logProbability": -0.01}]}],
///     "chosenCandidates": [{"token": "Hi", "tokenId": 17, "logProbability": -0.01}],
///     "logProbabilitySum": -0.01
/// }))
/// .unwrap();
/// assert_eq!(result.chosen_candidates[0].token.as_deref(), Some("Hi"));
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LogprobsResult {
    /// The most likely tokens at each decoding step, most likely first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub top_candidates: Vec<TopLogprobsCandidates>,
    /// The token chosen at each decoding step; it may not be among `top_candidates`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub chosen_candidates: Vec<LogprobsCandidate>,
    /// Sum of the log probabilities of every chosen token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub log_probability_sum: Option<f64>,
}

/// The top candidate tokens at one decoding step.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TopLogprobsCandidates {
    /// Candidates sorted by log probability, most likely first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<LogprobsCandidate>,
}

/// One token and its log probability.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LogprobsCandidate {
    /// The token text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    /// The token id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_id: Option<i32>,
    /// The token's log probability.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub log_probability: Option<f64>,
}

/// Metadata about token usage.
///
/// A count the API reports as `null` or leaves out reads as `None` (zero inside the detail
/// lists) instead of failing the response, and [`raw`](Self::raw) keeps the object exactly as
/// it was sent, including fields this type does not model.
///
/// # Example
///
/// ```
/// use adk_gemini::UsageMetadata;
///
/// let usage: UsageMetadata = serde_json::from_value(serde_json::json!({
///     "promptTokenCount": 12,
///     "promptTokensDetails": [{"modality": "TEXT", "tokenCount": null}],
///     "toolUsePromptTokenCount": 30
/// }))
/// .unwrap();
/// assert_eq!(usage.prompt_tokens_details.as_ref().unwrap()[0].token_count, 0);
/// assert_eq!(usage.raw.as_ref().unwrap()["toolUsePromptTokenCount"], 30);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", try_from = "serde_json::Value")]
pub struct UsageMetadata {
    /// The number of prompt tokens (null if request processing failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_token_count: Option<i32>,
    /// The number of response tokens (null if generation failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub candidates_token_count: Option<i32>,
    /// The total number of tokens (null if individual counts unavailable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_token_count: Option<i32>,
    /// The number of thinking tokens (Gemini 2.5 series only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thoughts_token_count: Option<i32>,
    /// Detailed prompt token information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_tokens_details: Option<Vec<PromptTokenDetails>>,
    /// The number of cached content tokens (batch API)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cached_content_token_count: Option<i32>,
    /// Detailed cache token information (batch API)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_tokens_details: Option<Vec<PromptTokenDetails>>,
    /// The `usageMetadata` object exactly as the API sent it, including fields this type
    /// does not model, such as `toolUsePromptTokenCount` or `trafficType`.
    ///
    /// `None` for a value built in code.
    #[serde(skip)]
    pub raw: Option<serde_json::Value>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct UsageMetadataWire {
    #[serde(default)]
    prompt_token_count: Option<i32>,
    #[serde(default)]
    candidates_token_count: Option<i32>,
    #[serde(default)]
    total_token_count: Option<i32>,
    #[serde(default)]
    thoughts_token_count: Option<i32>,
    #[serde(default)]
    prompt_tokens_details: Option<Vec<PromptTokenDetails>>,
    #[serde(default)]
    cached_content_token_count: Option<i32>,
    #[serde(default)]
    cache_tokens_details: Option<Vec<PromptTokenDetails>>,
}

impl TryFrom<serde_json::Value> for UsageMetadata {
    type Error = serde_json::Error;

    fn try_from(raw: serde_json::Value) -> Result<Self, Self::Error> {
        let wire = UsageMetadataWire::deserialize(&raw)?;
        Ok(Self {
            prompt_token_count: wire.prompt_token_count,
            candidates_token_count: wire.candidates_token_count,
            total_token_count: wire.total_token_count,
            thoughts_token_count: wire.thoughts_token_count,
            prompt_tokens_details: wire.prompt_tokens_details,
            cached_content_token_count: wire.cached_content_token_count,
            cache_tokens_details: wire.cache_tokens_details,
            raw: Some(raw),
        })
    }
}

/// Details about prompt tokens by modality
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PromptTokenDetails {
    /// The modality (e.g., "TEXT"); `MODALITY_UNSPECIFIED` when the API leaves it out
    #[serde(default = "unspecified_modality")]
    pub modality: Modality,
    /// Token count for this modality; zero when the API reports `null` or leaves it out
    #[serde(default, deserialize_with = "adk_core::nullable_count")]
    pub token_count: i32,
}

fn unspecified_modality() -> Modality {
    Modality::ModalityUnspecified
}

/// Grounding metadata for responses that use grounding tools
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct GroundingMetadata {
    /// Grounding chunks containing source information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grounding_chunks: Option<Vec<GroundingChunk>>,
    /// Grounding supports connecting response text to sources
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grounding_supports: Option<Vec<GroundingSupport>>,
    /// Web search queries used for grounding
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web_search_queries: Option<Vec<String>>,
    /// Provider-rendered Google Search suggestions and SDK data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_entry_point: Option<SearchEntryPoint>,
    /// Google Maps widget context token
    #[serde(skip_serializing_if = "Option::is_none")]
    pub google_maps_widget_context_token: Option<String>,
}

/// Google Search suggestions returned alongside a grounded answer.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct SearchEntryPoint {
    /// HTML and CSS to display the provider's search suggestions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rendered_content: Option<String>,
    /// Base64-encoded search term and URL tuples for native SDKs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sdk_blob: Option<String>,
}

/// A chunk of grounding information from a source
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GroundingChunk {
    /// Maps-specific grounding information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maps: Option<MapsGroundingChunk>,
    /// Web-specific grounding information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web: Option<WebGroundingChunk>,
}

/// Maps-specific grounding chunk information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MapsGroundingChunk {
    /// The URI of the Maps source
    #[serde(default)]
    pub uri: Option<Url>,
    /// The title of the Maps source
    #[serde(default)]
    pub title: Option<String>,
    /// The place ID from Google Maps
    #[serde(skip_serializing_if = "Option::is_none")]
    pub place_id: Option<String>,
}

/// Web-specific grounding chunk information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WebGroundingChunk {
    /// The URI of the web source
    #[serde(default)]
    pub uri: Option<Url>,
    /// The title of the web source
    #[serde(default)]
    pub title: Option<String>,
}

/// Support information connecting response text to grounding sources
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GroundingSupport {
    /// Segment of the response text
    pub segment: GroundingSegment,
    /// Indices of grounding chunks that support this segment
    pub grounding_chunk_indices: Vec<u32>,
}

/// A segment of response text
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct GroundingSegment {
    /// Index of the Part within the candidate's Content.
    ///
    /// The API omits zero values, so the field is absent when the segment is in the
    /// first part; treat `None` as part `0`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub part_index: Option<u32>,
    /// Start index of the segment in the response text
    #[serde(default)]
    pub start_index: Option<u32>,
    /// End index of the segment in the response text
    #[serde(default)]
    pub end_index: Option<u32>,
    /// The text content of the segment
    #[serde(default)]
    pub text: Option<String>,
}

/// Response from the Gemini API for content generation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GenerationResponse {
    /// The candidates generated
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<Candidate>,
    /// The prompt feedback
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt_feedback: Option<PromptFeedback>,
    /// Usage metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_metadata: Option<UsageMetadata>,
    /// Model version used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_version: Option<String>,
    /// Response ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_id: Option<String>,
}

/// Reason why content was blocked
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BlockReason {
    /// Default value. This value is unused.
    BlockReasonUnspecified,
    /// Prompt was blocked due to safety reasons. Inspect safetyRatings to understand which safety category blocked it.
    Safety,
    /// Prompt was blocked due to unknown reasons.
    Other,
    /// Prompt was blocked due to the terms which are included from the terminology blocklist.
    Blocklist,
    /// Prompt was blocked due to prohibited content.
    ProhibitedContent,
    /// Prompt was blocked by Model Armor.
    ModelArmor,
    /// Prompt was blocked due to jailbreak detection.
    Jailbreak,
    /// Candidates blocked due to unsafe image generation content.
    ImageSafety,
}

impl BlockReason {
    fn from_wire_str(value: &str) -> Self {
        match value {
            "BLOCK_REASON_UNSPECIFIED" | "BLOCKED_REASON_UNSPECIFIED" => {
                Self::BlockReasonUnspecified
            }
            "SAFETY" => Self::Safety,
            "OTHER" => Self::Other,
            "BLOCKLIST" => Self::Blocklist,
            "PROHIBITED_CONTENT" => Self::ProhibitedContent,
            "MODEL_ARMOR" => Self::ModelArmor,
            "JAILBREAK" => Self::Jailbreak,
            "IMAGE_SAFETY" => Self::ImageSafety,
            _ => Self::Other,
        }
    }

    fn from_wire_number(value: i64) -> Self {
        match value {
            0 => Self::BlockReasonUnspecified,
            1 => Self::Safety,
            2 => Self::Other,
            3 => Self::Blocklist,
            4 => Self::ProhibitedContent,
            5 => Self::ModelArmor,
            6 => Self::Jailbreak,
            7 => Self::ImageSafety,
            _ => Self::Other,
        }
    }
}

impl<'de> Deserialize<'de> for BlockReason {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(s) => Ok(Self::from_wire_str(&s)),
            serde_json::Value::Number(n) => {
                n.as_i64().map(Self::from_wire_number).ok_or_else(|| {
                    de::Error::custom("blockReason must be an integer-compatible number")
                })
            }
            _ => Err(de::Error::custom("blockReason must be a string or integer")),
        }
    }
}

/// Feedback about the prompt
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PromptFeedback {
    /// The safety ratings for the prompt
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub safety_ratings: Vec<SafetyRating>,
    /// The block reason if the prompt was blocked
    #[serde(skip_serializing_if = "Option::is_none")]
    pub block_reason: Option<BlockReason>,
}

impl GenerationResponse {
    /// Get the visible answer text of the first candidate.
    ///
    /// Concatenates every non-thought text part, in order. This is deliberately
    /// not "the first part": responses that use thinking or built-in tools
    /// (Google Search, URL context, code execution) commonly lead with thought
    /// or tool parts and place the answer text in a later part — so reading only
    /// the first part would return an empty string. Thought parts are excluded;
    /// use [`text_with_thoughts`](Self::text_with_thoughts) to inspect them.
    pub fn text(&self) -> String {
        self.candidates
            .first()
            .and_then(|c| c.content.parts.as_ref())
            .map(|parts| {
                parts
                    .iter()
                    .filter_map(|p| match p {
                        Part::Text { text, thought, thought_signature: _ }
                            if !thought.unwrap_or(false) =>
                        {
                            Some(text.as_str())
                        }
                        _ => None,
                    })
                    .collect::<String>()
            })
            .unwrap_or_default()
    }

    /// Get function calls from the response
    pub fn function_calls(&self) -> Vec<&crate::tools::FunctionCall> {
        self.candidates
            .iter()
            .flat_map(|c| {
                c.content
                    .parts
                    .as_ref()
                    .map(|parts| {
                        parts
                            .iter()
                            .filter_map(|p| match p {
                                Part::FunctionCall { function_call, thought_signature: _ } => {
                                    Some(function_call)
                                }
                                _ => None,
                            })
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect()
    }

    /// Get function calls with their thought signatures from the response
    pub fn function_calls_with_thoughts(
        &self,
    ) -> Vec<(&crate::tools::FunctionCall, Option<&String>)> {
        self.candidates
            .iter()
            .flat_map(|c| {
                c.content
                    .parts
                    .as_ref()
                    .map(|parts| {
                        parts
                            .iter()
                            .filter_map(|p| match p {
                                Part::FunctionCall { function_call, thought_signature } => {
                                    Some((function_call, thought_signature.as_ref()))
                                }
                                _ => None,
                            })
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect()
    }

    /// Get thought summaries from the response
    pub fn thoughts(&self) -> Vec<String> {
        self.candidates
            .iter()
            .flat_map(|c| {
                c.content
                    .parts
                    .as_ref()
                    .map(|parts| {
                        parts
                            .iter()
                            .filter_map(|p| match p {
                                Part::Text { text, thought: Some(true), thought_signature: _ } => {
                                    Some(text.clone())
                                }
                                _ => None,
                            })
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect()
    }

    /// Get all text parts (both regular text and thoughts)
    pub fn all_text(&self) -> Vec<(String, bool)> {
        self.candidates
            .iter()
            .flat_map(|c| {
                c.content
                    .parts
                    .as_ref()
                    .map(|parts| {
                        parts
                            .iter()
                            .filter_map(|p| match p {
                                Part::Text { text, thought, thought_signature: _ } => {
                                    Some((text.clone(), thought.unwrap_or(false)))
                                }
                                _ => None,
                            })
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect()
    }

    /// Get text parts with their thought signatures from the response
    pub fn text_with_thoughts(&self) -> Vec<(String, bool, Option<&String>)> {
        self.candidates
            .iter()
            .flat_map(|c| {
                c.content
                    .parts
                    .as_ref()
                    .map(|parts| {
                        parts
                            .iter()
                            .filter_map(|p| match p {
                                Part::Text { text, thought, thought_signature } => Some((
                                    text.clone(),
                                    thought.unwrap_or(false),
                                    thought_signature.as_ref(),
                                )),
                                _ => None,
                            })
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            })
            .collect()
    }
}

/// Request to generate content
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateContentRequest {
    /// The contents to generate content from
    pub contents: Vec<Content>,
    /// The generation config
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generation_config: Option<GenerationConfig>,
    /// The safety settings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub safety_settings: Option<Vec<SafetySetting>>,
    /// The tools that the model can use
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<crate::tools::Tool>>,
    /// The tool config
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_config: Option<crate::tools::ToolConfig>,
    /// The system instruction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_instruction: Option<Content>,
    /// The cached content to use
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cached_content: Option<String>,
}

impl GenerateContentRequest {
    /// Strips fields that Vertex AI does not support.
    ///
    /// The Vertex AI surface (`aiplatform.googleapis.com`) rejects
    /// `includeServerSideToolInvocations` with a 400 error. Vertex AI handles
    /// built-in tools (Google Search, URL Context, etc.) natively without
    /// needing this flag. This method clears the flag so the request can be
    /// sent to Vertex AI without modification.
    ///
    /// AI Studio (`generativelanguage.googleapis.com`) requires the flag for
    /// Gemini 3 models to return `toolCall`/`toolResponse` parts instead of
    /// silently truncating the response.
    pub fn strip_vertex_unsupported_fields(&mut self) {
        if let Some(tc) = &mut self.tool_config {
            tc.include_server_side_tool_invocations = None;
        }
    }
}

/// Native thinking level for Gemini 4 and Gemini 3 models.
///
/// Controls the amount of reasoning effort the model applies. This is the
/// Gemini 3 native thinking control — for Gemini 2.5 budget-based thinking,
/// use [`ThinkingConfig::with_thinking_budget`] instead.
///
/// Serializes as lowercase per the Gemini API contract
/// (e.g., `"low"`, `"xhigh"`).
///
/// Available levels (model support and defaults vary by model, see
/// <https://aistudio.google.com/docs/thinking#thinking-levels>):
/// - `Minimal` — matches "no thinking" for most queries; model may still
///   think minimally for complex coding tasks. Not supported on Gemini 4 models,
///   Gemini 3.8 Flash or Gemini 3.1 Pro.
/// - `Low` — minimizes latency and cost; improved for code and agentic tasks
///   that require fewer steps.
/// - `Medium` — balanced thinking for most tasks. Default for Gemini 4 Carbon,
///   Gemini 4 Argon and Gemini 3.8 Flash.
/// - `High` — maximizes reasoning depth. Default for Gemini 4 Neon, Gemini 4
///   Hydrogen and Gemini 3.1 Pro.
/// - `XHigh` — the deepest reasoning, for hard multi-step problems. Supported on
///   Gemini 4 Neon and Gemini 4 Hydrogen only.
///
/// The enum is `#[non_exhaustive]`: Google adds levels.
///
/// Note: `temperature`, `top_p`, and `top_k` are no longer recommended for
/// Gemini 3.x models — their reasoning is tuned for the default sampling
/// settings. Use `thinking_level` to control reasoning effort instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ThinkingLevel {
    /// Minimal reasoning effort. Matches "no thinking" for most queries.
    /// Not supported on Gemini 4 models, Gemini 3.8 Flash or Gemini 3.1 Pro.
    Minimal,
    /// Low reasoning effort. Best for simple instruction following and chat.
    Low,
    /// Medium reasoning effort. Balanced thinking for most tasks.
    /// Default for Gemini 4 Carbon, Gemini 4 Argon and Gemini 3.8 Flash.
    Medium,
    /// High reasoning effort — maximizes reasoning depth. Default for
    /// Gemini 4 Neon, Gemini 4 Hydrogen and Gemini 3.1 Pro.
    High,
    /// Extra-high reasoning effort: the most tokens and the deepest reasoning.
    /// Supported on Gemini 4 Neon and Gemini 4 Hydrogen only.
    XHigh,
}

/// The harness effort levels (spec 3.1 §7.23): `Low`, `Medium` and `High` map to the
/// thinking level of the same name; `Minimal` and `XHigh` stay reachable only through
/// [`ThinkingConfig::with_thinking_level`], since [`adk_core::Effort`] has no level below
/// `Low` or above `High`.
///
/// # Example
///
/// ```rust
/// use adk_gemini::ThinkingLevel;
///
/// assert_eq!(ThinkingLevel::from(adk_core::Effort::Medium), ThinkingLevel::Medium);
/// ```
impl From<adk_core::Effort> for ThinkingLevel {
    fn from(effort: adk_core::Effort) -> Self {
        match effort {
            adk_core::Effort::Low => Self::Low,
            adk_core::Effort::Medium => Self::Medium,
            adk_core::Effort::High => Self::High,
        }
    }
}

/// Configuration for thinking (Gemini 2.5 and 3 series)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThinkingConfig {
    /// The thinking budget (number of thinking tokens)
    ///
    /// This is the Gemini 2.5 budget-based thinking control.
    ///
    /// - Set to 0 to disable thinking
    /// - Set to -1 for dynamic thinking (model decides)
    /// - Set to a positive number for a specific token budget
    ///
    /// Model-specific ranges:
    /// - 2.5 Pro: 128 to 32768 (cannot disable thinking)
    /// - 2.5 Flash: 0 to 24576
    /// - 2.5 Flash Lite: 512 to 24576
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_budget: Option<i32>,

    /// Whether to include thought summaries in the response
    ///
    /// When enabled, the response will include synthesized versions of the model's
    /// raw thoughts, providing insights into the reasoning process.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_thoughts: Option<bool>,

    /// Native thinking level for Gemini 3 models.
    ///
    /// When set, the model uses level-based reasoning instead of a token budget.
    /// Do not combine with `thinking_budget` — use one or the other.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_level: Option<ThinkingLevel>,
}

impl ThinkingConfig {
    /// Validate the thinking configuration.
    ///
    /// Returns an error if both `thinking_budget` and `thinking_level` are set,
    /// since they are mutually exclusive controls (budget for Gemini 2.5, level for Gemini 3).
    pub fn validate(&self) -> Result<(), String> {
        if self.thinking_budget.is_some() && self.thinking_level.is_some() {
            return Err(
                "thinking_budget and thinking_level are mutually exclusive; use one or the other"
                    .to_string(),
            );
        }
        Ok(())
    }

    /// Create a new thinking config with default settings
    pub fn new() -> Self {
        Self { thinking_budget: None, include_thoughts: None, thinking_level: None }
    }

    /// Set the thinking budget (Gemini 2.5 budget-based control)
    pub fn with_thinking_budget(mut self, budget: i32) -> Self {
        self.thinking_budget = Some(budget);
        self
    }

    /// Enable dynamic thinking (model decides the budget)
    pub fn with_dynamic_thinking(mut self) -> Self {
        self.thinking_budget = Some(-1);
        self
    }

    /// Include thought summaries in the response
    pub fn with_thoughts_included(mut self, include: bool) -> Self {
        self.include_thoughts = Some(include);
        self
    }

    /// Set the thinking level (Gemini 3 native level-based control).
    ///
    /// This is the preferred control for Gemini 3 models. Do not combine
    /// with `with_thinking_budget` — use one or the other.
    pub fn with_thinking_level(mut self, level: ThinkingLevel) -> Self {
        self.thinking_level = Some(level);
        self
    }

    /// Create a thinking config that enables dynamic thinking with thoughts included
    pub fn dynamic_thinking() -> Self {
        Self { thinking_budget: Some(-1), include_thoughts: Some(true), thinking_level: None }
    }
}

impl Default for ThinkingConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for generation
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerationConfig {
    /// The temperature for the model (0.0 to 1.0)
    ///
    /// Controls the randomness of the output. Higher values (e.g., 0.9) make output
    /// more random, lower values (e.g., 0.1) make output more deterministic.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// The top-p value for the model (0.0 to 1.0)
    ///
    /// For each token generation step, the model considers the top_p percentage of
    /// probability mass for potential token choices. Lower values are more selective,
    /// higher values allow more variety.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,

    /// The top-k value for the model
    ///
    /// For each token generation step, the model considers the top_k most likely tokens.
    /// Lower values are more selective, higher values allow more variety.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<i32>,

    /// The maximum number of tokens to generate
    ///
    /// Limits the length of the generated content. One token is roughly 4 characters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_output_tokens: Option<i32>,

    /// The candidate count
    ///
    /// Number of alternative responses to generate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub candidate_count: Option<i32>,

    /// Whether to stop on specific sequences
    ///
    /// The model will stop generating content when it encounters any of these sequences.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,

    /// Seed used in decoding, so repeated requests with the same seed return the same output.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed: Option<i64>,

    /// Penalty applied to tokens that already appear in the response, encouraging new topics.
    ///
    /// The API rejects it with `INVALID_ARGUMENT` for models that do not enable penalties.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,

    /// Penalty scaled by how often a token already appears in the response.
    ///
    /// The API rejects it with `INVALID_ARGUMENT` for models that do not enable penalties.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,

    /// Whether to return the log probabilities of the chosen tokens in
    /// [`Candidate::logprobs_result`].
    ///
    /// The API rejects it with `INVALID_ARGUMENT` for models that do not enable log
    /// probabilities.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response_logprobs: Option<bool>,

    /// Number of top candidate tokens, with their log probabilities, to return at each
    /// decoding step. Requires `response_logprobs`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<i32>,

    /// The response mime type
    ///
    /// Specifies the format of the model's response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_mime_type: Option<String>,
    /// The response schema
    ///
    /// Specifies the JSON schema for structured responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_schema: Option<serde_json::Value>,

    /// Response modalities (for TTS and other multimodal outputs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_modalities: Option<Vec<String>>,

    /// Speech configuration for text-to-speech generation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speech_config: Option<SpeechConfig>,

    /// The thinking configuration
    ///
    /// Configuration for the model's thinking process (Gemini 2.5 series only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_config: Option<ThinkingConfig>,

    /// The resolution images and video frames are tokenised at, which their token count
    /// and cost depend on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub media_resolution: Option<MediaResolution>,
}

/// The resolution Gemini tokenises images and video frames at: `generationConfig.mediaResolution`.
///
/// A video frame costs about 66 tokens at `Low` and about 258 at `Medium` and `High`; with
/// 32 tokens a second of audio, a second of video at 1 fps is about 100 or about 300 tokens.
///
/// # Example
///
/// ```rust
/// use adk_gemini::{GenerationConfig, MediaResolution};
///
/// let config = GenerationConfig { media_resolution: Some(MediaResolution::Low), ..Default::default() };
/// let json = serde_json::to_value(&config).unwrap();
/// assert_eq!(json["mediaResolution"], "MEDIA_RESOLUTION_LOW");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum MediaResolution {
    /// The model's default.
    #[serde(rename = "MEDIA_RESOLUTION_UNSPECIFIED")]
    Unspecified,
    /// 64 tokens a frame (about 66 with overhead).
    #[serde(rename = "MEDIA_RESOLUTION_LOW")]
    Low,
    /// 256 tokens a frame.
    #[serde(rename = "MEDIA_RESOLUTION_MEDIUM")]
    Medium,
    /// Up to 256 tokens a frame, with zoomed reframing for images.
    #[serde(rename = "MEDIA_RESOLUTION_HIGH")]
    High,
}

impl GenerationConfig {
    /// Validate the generation configuration.
    ///
    /// Returns an error if any parameter is outside its valid range:
    /// - `temperature`: must be between 0.0 and 2.0
    /// - `top_p`: must be between 0.0 and 1.0
    /// - `top_k`: must be positive
    /// - `max_output_tokens`: must be positive
    ///
    /// If `thinking_config` is present, delegates to [`ThinkingConfig::validate`] as well.
    /// All `None` fields are accepted without error.
    pub fn validate(&self) -> Result<(), String> {
        if let Some(t) = self.temperature
            && !(0.0..=2.0).contains(&t)
        {
            return Err("temperature must be between 0.0 and 2.0".to_string());
        }
        if let Some(p) = self.top_p
            && !(0.0..=1.0).contains(&p)
        {
            return Err("top_p must be between 0.0 and 1.0".to_string());
        }
        if let Some(k) = self.top_k
            && k <= 0
        {
            return Err("top_k must be positive".to_string());
        }
        if let Some(m) = self.max_output_tokens
            && m <= 0
        {
            return Err("max_output_tokens must be positive".to_string());
        }
        if let Some(ref tc) = self.thinking_config {
            tc.validate()?;
        }
        Ok(())
    }
}

/// Configuration for speech generation (text-to-speech)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SpeechConfig {
    /// Single voice configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub voice_config: Option<VoiceConfig>,
    /// Multi-speaker voice configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub multi_speaker_voice_config: Option<MultiSpeakerVoiceConfig>,
}

/// Voice configuration for text-to-speech
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VoiceConfig {
    /// Prebuilt voice configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prebuilt_voice_config: Option<PrebuiltVoiceConfig>,
}

/// Prebuilt voice configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PrebuiltVoiceConfig {
    /// The name of the voice to use
    pub voice_name: String,
}

/// Multi-speaker voice configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MultiSpeakerVoiceConfig {
    /// Configuration for each speaker
    pub speaker_voice_configs: Vec<SpeakerVoiceConfig>,
}

/// Configuration for a specific speaker in multi-speaker TTS
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SpeakerVoiceConfig {
    /// The name of the speaker (must match the name used in the prompt)
    pub speaker: String,
    /// Voice configuration for this speaker
    pub voice_config: VoiceConfig,
}

impl SpeechConfig {
    /// Create a new speech config with a single voice
    pub fn single_voice(voice_name: impl Into<String>) -> Self {
        Self {
            voice_config: Some(VoiceConfig {
                prebuilt_voice_config: Some(PrebuiltVoiceConfig { voice_name: voice_name.into() }),
            }),
            multi_speaker_voice_config: None,
        }
    }

    /// Create a new speech config with multiple speakers
    pub fn multi_speaker(speakers: Vec<SpeakerVoiceConfig>) -> Self {
        Self {
            voice_config: None,
            multi_speaker_voice_config: Some(MultiSpeakerVoiceConfig {
                speaker_voice_configs: speakers,
            }),
        }
    }
}

impl SpeakerVoiceConfig {
    /// Create a new speaker voice configuration
    pub fn new(speaker: impl Into<String>, voice_name: impl Into<String>) -> Self {
        Self {
            speaker: speaker.into(),
            voice_config: VoiceConfig {
                prebuilt_voice_config: Some(PrebuiltVoiceConfig { voice_name: voice_name.into() }),
            },
        }
    }
}

#[cfg(test)]
mod effort_tests {
    use super::ThinkingLevel;

    /// The harness levels map to their namesakes; `Minimal` is never produced.
    #[test]
    fn every_harness_effort_maps_to_its_namesake() {
        for (core, level) in [
            (adk_core::Effort::Low, ThinkingLevel::Low),
            (adk_core::Effort::Medium, ThinkingLevel::Medium),
            (adk_core::Effort::High, ThinkingLevel::High),
        ] {
            assert_eq!(ThinkingLevel::from(core), level);
        }
    }
}