reson-agentic 0.5.1

Agents are just functions - production-grade LLM agent framework
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
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
//! Core types for Reson
//!
//! This module contains the fundamental data structures used throughout
//! the framework: messages, tool calls, tool results, and reasoning segments.

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::error::{Error, Result};

/// Format JSON to match Python's json.dumps default style (space after colon and comma)
fn format_json_python_style(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Object(map) => {
            let pairs: Vec<String> = map
                .iter()
                .map(|(k, v)| format!("\"{}\": {}", k, format_json_python_style(v)))
                .collect();
            format!("{{{}}}", pairs.join(", "))
        }
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(format_json_python_style).collect();
            format!("[{}]", items.join(", "))
        }
        serde_json::Value::String(_) => {
            serde_json::to_string(value).unwrap_or_else(|_| "\"\"".to_string())
        }
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Null => "null".to_string(),
    }
}

/// LLM Provider enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Provider {
    /// Anthropic Claude (direct API)
    Anthropic,
    /// OpenAI GPT models (direct API)
    OpenAI,
    /// OpenAI Responses API
    OpenAIResponses,
    /// AWS Bedrock (Claude and others)
    Bedrock,
    /// Google Gemini via GenAI SDK
    GoogleGenAI,
    /// Anthropic Claude via Google Vertex AI
    GoogleAnthropic,
    /// OpenRouter proxy service
    OpenRouter,
    /// OpenRouter Responses API
    OpenRouterResponses,
}

impl Provider {
    /// Parse provider from model string (e.g., "anthropic:claude-3-opus")
    pub fn from_model_string(model: &str) -> Result<(Self, String)> {
        let parts: Vec<&str> = model.split(':').collect();
        if parts.len() < 2 {
            return Err(Error::InvalidProvider(format!(
                "Invalid model string format: {}. Expected 'provider:model'",
                model
            )));
        }

        let (provider_str, model_name) = if parts.len() >= 3 && parts[1] == "resp" {
            let provider = match parts[0] {
                "openai" => Provider::OpenAIResponses,
                "openrouter" => Provider::OpenRouterResponses,
                _ => return Err(Error::InvalidProvider(parts[0].to_string())),
            };
            return Ok((provider, parts[2..].join(":")));
        } else {
            (parts[0], parts[1..].join(":"))
        };

        let provider = match provider_str {
            "anthropic" => Provider::Anthropic,
            "openai" => Provider::OpenAI,
            "bedrock" => Provider::Bedrock,
            "google-genai" | "gemini" | "google-gemini" => Provider::GoogleGenAI,
            "google-anthropic" | "vertexai" => Provider::GoogleAnthropic,
            "openrouter" => Provider::OpenRouter,
            _ => return Err(Error::InvalidProvider(provider_str.to_string())),
        };
        Ok((provider, model_name))
    }

    /// Check if this provider supports native tool calling
    pub fn supports_native_tools(&self) -> bool {
        matches!(
            self,
            Provider::Anthropic
                | Provider::OpenAI
                | Provider::OpenAIResponses
                | Provider::Bedrock
                | Provider::GoogleGenAI
                | Provider::GoogleAnthropic
                | Provider::OpenRouter
                | Provider::OpenRouterResponses
        )
    }
}

/// Chat message role
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChatRole {
    /// System message (instructions)
    System,
    /// User message
    User,
    /// Assistant message
    Assistant,
    /// Tool result message
    #[serde(rename = "tool")]
    Tool,
}

/// Cache marker for Anthropic prompt caching
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CacheMarker {
    /// Ephemeral cache point
    Ephemeral,
}

/// A chat message in the conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    /// Message role
    pub role: ChatRole,

    /// Message content (text)
    pub content: String,

    /// Optional cache marker (for Anthropic caching)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_marker: Option<CacheMarker>,

    /// Optional model family filtering
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_families: Option<Vec<String>>,

    /// Provider-specific signature for reasoning preservation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

impl ChatMessage {
    /// Create a new system message
    pub fn system(content: impl Into<String>) -> Self {
        Self {
            role: ChatRole::System,
            content: content.into(),
            cache_marker: None,
            model_families: None,
            signature: None,
        }
    }

    /// Create a new user message
    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: ChatRole::User,
            content: content.into(),
            cache_marker: None,
            model_families: None,
            signature: None,
        }
    }

    /// Create a new assistant message
    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: ChatRole::Assistant,
            content: content.into(),
            cache_marker: None,
            model_families: None,
            signature: None,
        }
    }

    /// Add a cache marker to this message
    pub fn with_cache_marker(mut self, marker: CacheMarker) -> Self {
        self.cache_marker = Some(marker);
        self
    }
}

/// Token usage statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TokenUsage {
    /// Input tokens consumed
    pub input_tokens: u64,

    /// Output tokens generated
    pub output_tokens: u64,

    /// Cached tokens (for Anthropic caching)
    pub cached_tokens: u64,
}

impl TokenUsage {
    /// Create new token usage stats
    pub fn new(input_tokens: u64, output_tokens: u64, cached_tokens: u64) -> Self {
        Self {
            input_tokens,
            output_tokens,
            cached_tokens,
        }
    }

    /// Total tokens (input + output)
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens + self.output_tokens
    }
}

/// Cost information for inference requests
///
/// Stores costs in microdollars ($1 = 1,000,000 microdollars) for billing-level precision.
/// This avoids floating-point rounding errors when accumulating many small costs.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CostInfo {
    /// Input tokens consumed
    pub input_tokens: u64,

    /// Output tokens generated
    pub output_tokens: u64,

    /// Cache read tokens (prompt caching hits)
    pub cache_read_input_tokens: u64,

    /// Cache write tokens (prompt caching misses that were cached)
    pub cache_write_input_tokens: u64,

    /// Cost in microdollars ($1 = 1,000,000) - calculated from pricing tables
    pub microdollar_cost: u64,

    /// Provider-reported cost in microdollars (e.g., from OpenRouter)
    /// When present, this takes precedence over calculated cost
    pub provider_cost_microdollars: Option<u64>,

    /// Manual adjustment in microdollars (can be negative via wrapping)
    pub microdollar_adjust: u64,
}

impl CostInfo {
    /// Create CostInfo from TokenUsage and model name
    ///
    /// Calculates cost based on per-model pricing. Uses microdollars for precision.
    pub fn from_usage(usage: &TokenUsage, model: &str) -> Self {
        let mut info = Self {
            input_tokens: usage.input_tokens,
            output_tokens: usage.output_tokens,
            cache_read_input_tokens: usage.cached_tokens,
            cache_write_input_tokens: 0, // Not tracked in TokenUsage currently
            microdollar_cost: 0,
            provider_cost_microdollars: None,
            microdollar_adjust: 0,
        };

        info.microdollar_cost = info.calculate_microdollar_cost(model);
        info
    }

    /// Create CostInfo with provider-reported cost (e.g., from OpenRouter)
    ///
    /// When the provider returns cost directly, we use that instead of calculating.
    /// The provider cost takes precedence in `total_microdollars()`.
    pub fn from_usage_with_provider_cost(
        usage: &TokenUsage,
        model: &str,
        provider_cost_dollars: f64,
    ) -> Self {
        let mut info = Self::from_usage(usage, model);
        // Convert dollars to microdollars
        info.provider_cost_microdollars = Some((provider_cost_dollars * 1_000_000.0) as u64);
        info
    }

    /// Set provider-reported cost in dollars
    pub fn with_provider_cost(mut self, cost_dollars: f64) -> Self {
        self.provider_cost_microdollars = Some((cost_dollars * 1_000_000.0) as u64);
        self
    }

    /// Calculate cost in microdollars based on model pricing
    ///
    /// Pricing per million tokens, converted to microdollars per token:
    /// - $X per 1M tokens = X microdollars per token
    fn calculate_microdollar_cost(&self, model: &str) -> u64 {
        let model_lower = model.to_lowercase();

        // Anthropic models
        if model_lower.contains("claude") || model_lower.contains("anthropic") {
            if model_lower.contains("haiku") {
                // Haiku: $0.80/1M input, $4/1M output, $0.08/1M cache read
                // In microdollars: 0.80 input, 4.0 output, 0.08 cache read
                let input_cost = (self.input_tokens as f64) * 0.80;
                let output_cost = (self.output_tokens as f64) * 4.0;
                let cache_cost = (self.cache_read_input_tokens as f64) * 0.08;
                (input_cost + output_cost + cache_cost).ceil() as u64
            } else if model_lower.contains("opus") {
                // Opus: $15/1M input, $75/1M output, $1.50/1M cache read
                let input_cost = (self.input_tokens as f64) * 15.0;
                let output_cost = (self.output_tokens as f64) * 75.0;
                let cache_cost = (self.cache_read_input_tokens as f64) * 1.50;
                (input_cost + output_cost + cache_cost).ceil() as u64
            } else {
                // Sonnet (default): $3/1M input, $15/1M output, $0.30/1M cache read
                let input_cost = (self.input_tokens as f64) * 3.0;
                let output_cost = (self.output_tokens as f64) * 15.0;
                let cache_cost = (self.cache_read_input_tokens as f64) * 0.30;
                (input_cost + output_cost + cache_cost).ceil() as u64
            }
        }
        // OpenAI models
        else if model_lower.contains("gpt-4o") || model_lower.contains("o4-mini") {
            if model_lower.contains("mini") {
                // GPT-4o-mini / o4-mini: $1.10/1M input, $4.40/1M output
                let input_cost = (self.input_tokens as f64) * 1.10;
                let output_cost = (self.output_tokens as f64) * 4.40;
                let cache_cost = (self.cache_read_input_tokens as f64) * 0.275;
                (input_cost + output_cost + cache_cost).ceil() as u64
            } else {
                // GPT-4o: $5/1M input, $15/1M output
                let input_cost = (self.input_tokens as f64) * 5.0;
                let output_cost = (self.output_tokens as f64) * 15.0;
                let cache_cost = (self.cache_read_input_tokens as f64) * 1.25;
                (input_cost + output_cost + cache_cost).ceil() as u64
            }
        } else if model_lower.contains("o3") {
            // o3: $10/1M input, $40/1M output
            let input_cost = (self.input_tokens as f64) * 10.0;
            let output_cost = (self.output_tokens as f64) * 40.0;
            let cache_cost = (self.cache_read_input_tokens as f64) * 2.5;
            (input_cost + output_cost + cache_cost).ceil() as u64
        } else if model_lower.contains("o1") {
            // o1: $15/1M input, $60/1M output
            let input_cost = (self.input_tokens as f64) * 15.0;
            let output_cost = (self.output_tokens as f64) * 60.0;
            (input_cost + output_cost).ceil() as u64
        }
        // Google models
        else if model_lower.contains("gemini") {
            if model_lower.contains("flash") {
                // Gemini Flash: $0.075/1M input, $0.30/1M output
                let input_cost = (self.input_tokens as f64) * 0.075;
                let output_cost = (self.output_tokens as f64) * 0.30;
                (input_cost + output_cost).ceil() as u64
            } else if model_lower.contains("pro") {
                // Gemini Pro: $1.25/1M input, $5/1M output
                let input_cost = (self.input_tokens as f64) * 1.25;
                let output_cost = (self.output_tokens as f64) * 5.0;
                (input_cost + output_cost).ceil() as u64
            } else {
                0
            }
        } else {
            // Unknown model - return 0 cost
            0
        }
    }

    /// Total cost in microdollars (including adjustments)
    ///
    /// Prefers provider-reported cost when available (e.g., from OpenRouter),
    /// falls back to calculated cost from pricing tables.
    pub fn total_microdollars(&self) -> u64 {
        let base_cost = self
            .provider_cost_microdollars
            .unwrap_or(self.microdollar_cost);
        base_cost.wrapping_add(self.microdollar_adjust)
    }

    /// Get the calculated cost (from pricing tables), ignoring provider cost
    pub fn calculated_microdollars(&self) -> u64 {
        self.microdollar_cost.wrapping_add(self.microdollar_adjust)
    }

    /// Check if provider reported cost directly
    pub fn has_provider_cost(&self) -> bool {
        self.provider_cost_microdollars.is_some()
    }

    /// Convert to dollars (for display)
    pub fn total_dollars(&self) -> f64 {
        (self.total_microdollars() as f64) / 1_000_000.0
    }

    /// Convert to cents (for legacy compatibility)
    pub fn total_cents(&self) -> u64 {
        self.total_microdollars() / 10_000
    }
}

// ============================================================================
// Media Types - for multimodal content (images, audio, video)
// ============================================================================

/// Source of media content - where the data comes from
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MediaSource {
    /// Base64-encoded data with MIME type
    Base64 { data: String, mime_type: String },
    /// URL to the media (public URL)
    Url { url: String },
    /// Provider file ID (uploaded via provider's File API)
    FileId { file_id: String },
    /// Provider file URI (Google-style, includes YouTube URLs)
    FileUri {
        uri: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
    },
}

impl MediaSource {
    /// Create from base64 data
    pub fn base64(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self::Base64 {
            data: data.into(),
            mime_type: mime_type.into(),
        }
    }

    /// Create from URL
    pub fn url(url: impl Into<String>) -> Self {
        Self::Url { url: url.into() }
    }

    /// Create from provider file ID
    pub fn file_id(file_id: impl Into<String>) -> Self {
        Self::FileId {
            file_id: file_id.into(),
        }
    }

    /// Create from provider file URI (Google)
    pub fn file_uri(uri: impl Into<String>) -> Self {
        Self::FileUri {
            uri: uri.into(),
            mime_type: None,
        }
    }

    /// Create from YouTube URL (Google)
    pub fn youtube(url: impl Into<String>) -> Self {
        Self::FileUri {
            uri: url.into(),
            mime_type: Some("video/*".to_string()),
        }
    }
}

/// Video-specific metadata for processing options
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VideoMetadata {
    /// Start offset for clipping (e.g., "1250s" or "00:30")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_offset: Option<String>,

    /// End offset for clipping
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_offset: Option<String>,

    /// Frames per second for sampling (default 1 FPS)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fps: Option<f32>,
}

impl VideoMetadata {
    /// Create new video metadata
    pub fn new() -> Self {
        Self::default()
    }

    /// Set start offset
    pub fn with_start(mut self, offset: impl Into<String>) -> Self {
        self.start_offset = Some(offset.into());
        self
    }

    /// Set end offset
    pub fn with_end(mut self, offset: impl Into<String>) -> Self {
        self.end_offset = Some(offset.into());
        self
    }

    /// Set FPS for video sampling
    pub fn with_fps(mut self, fps: f32) -> Self {
        self.fps = Some(fps);
        self
    }

    /// Set clipping range
    pub fn with_clip(mut self, start: impl Into<String>, end: impl Into<String>) -> Self {
        self.start_offset = Some(start.into());
        self.end_offset = Some(end.into());
        self
    }
}

/// A media content part that can be attached to messages
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MediaPart {
    /// Text content
    Text { text: String },

    /// Image content
    Image {
        source: MediaSource,
        /// Detail level for processing (OpenAI: "high", "low", "auto")
        #[serde(skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
    },

    /// Audio content
    Audio {
        source: MediaSource,
        /// Audio format hint (e.g., "wav", "mp3")
        #[serde(skip_serializing_if = "Option::is_none")]
        format: Option<String>,
    },

    /// Video content
    Video {
        source: MediaSource,
        /// Video processing metadata (clipping, FPS)
        #[serde(skip_serializing_if = "Option::is_none")]
        metadata: Option<VideoMetadata>,
    },

    /// PDF document (Anthropic, Google)
    Document { source: MediaSource },
}

impl MediaPart {
    /// Create a text part
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Create an image part from a source
    pub fn image(source: MediaSource) -> Self {
        Self::Image {
            source,
            detail: None,
        }
    }

    /// Create an image part with detail level
    pub fn image_with_detail(source: MediaSource, detail: impl Into<String>) -> Self {
        Self::Image {
            source,
            detail: Some(detail.into()),
        }
    }

    /// Create an audio part
    pub fn audio(source: MediaSource) -> Self {
        Self::Audio {
            source,
            format: None,
        }
    }

    /// Create an audio part with format hint
    pub fn audio_with_format(source: MediaSource, format: impl Into<String>) -> Self {
        Self::Audio {
            source,
            format: Some(format.into()),
        }
    }

    /// Create a video part
    pub fn video(source: MediaSource) -> Self {
        Self::Video {
            source,
            metadata: None,
        }
    }

    /// Create a video part with metadata
    pub fn video_with_metadata(source: MediaSource, metadata: VideoMetadata) -> Self {
        Self::Video {
            source,
            metadata: Some(metadata),
        }
    }

    /// Create a video from YouTube URL
    pub fn youtube(url: impl Into<String>) -> Self {
        Self::Video {
            source: MediaSource::youtube(url),
            metadata: None,
        }
    }

    /// Create a video from YouTube URL with clipping
    pub fn youtube_clip(
        url: impl Into<String>,
        start: impl Into<String>,
        end: impl Into<String>,
    ) -> Self {
        Self::Video {
            source: MediaSource::youtube(url),
            metadata: Some(VideoMetadata::new().with_clip(start, end)),
        }
    }

    /// Create a document part
    pub fn document(source: MediaSource) -> Self {
        Self::Document { source }
    }
}

/// A multimodal message containing multiple parts (text, images, video, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultimodalMessage {
    /// Message role
    pub role: ChatRole,

    /// Content parts (text, images, video, audio, documents)
    pub parts: Vec<MediaPart>,

    /// Optional cache marker (for Anthropic caching)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_marker: Option<CacheMarker>,
}

impl MultimodalMessage {
    /// Create a new multimodal user message
    pub fn user(parts: Vec<MediaPart>) -> Self {
        Self {
            role: ChatRole::User,
            parts,
            cache_marker: None,
        }
    }

    /// Create a user message with text and media
    pub fn user_with_media(text: impl Into<String>, media: MediaPart) -> Self {
        Self {
            role: ChatRole::User,
            parts: vec![media, MediaPart::text(text)],
            cache_marker: None,
        }
    }

    /// Create a user message with text and video
    pub fn user_with_video(text: impl Into<String>, source: MediaSource) -> Self {
        Self::user_with_media(text, MediaPart::video(source))
    }

    /// Create a user message with text and image
    pub fn user_with_image(text: impl Into<String>, source: MediaSource) -> Self {
        Self::user_with_media(text, MediaPart::image(source))
    }

    /// Create a user message with text and YouTube video
    pub fn user_with_youtube(text: impl Into<String>, url: impl Into<String>) -> Self {
        Self::user_with_media(text, MediaPart::youtube(url))
    }

    /// Add a cache marker
    pub fn with_cache_marker(mut self, marker: CacheMarker) -> Self {
        self.cache_marker = Some(marker);
        self
    }
}

// ============================================================================
// Tool Types
// ============================================================================

/// Result of ToolCall::create() - handles single, multiple, or empty results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CreateResult {
    /// Single tool call
    Single(ToolCall),
    /// Multiple tool calls
    Multiple(Vec<ToolCall>),
    /// Empty input (no tool calls)
    Empty,
}

/// A tool call from the LLM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// Unique ID for this tool use
    pub tool_use_id: String,

    /// Name of the tool to call
    pub tool_name: String,

    /// Tool arguments (parsed JSON)
    pub args: serde_json::Value,

    /// Raw argument string (for debugging)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_arguments: Option<String>,

    /// Provider signature for reasoning preservation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,

    /// Original tool call object (for preserving provider format)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_obj: Option<serde_json::Value>,
}

impl ToolCall {
    /// Create a new tool call
    pub fn new(tool_name: impl Into<String>, args: serde_json::Value) -> Self {
        Self {
            tool_use_id: Uuid::new_v4().to_string(),
            tool_name: tool_name.into(),
            args,
            raw_arguments: None,
            signature: None,
            tool_obj: None,
        }
    }

    /// Create from provider-specific format with auto-detection
    ///
    /// Detects the provider format automatically based on the structure:
    /// - OpenAI: has "function" key with "name" and "arguments"
    /// - Anthropic: has "name" and "input" keys (no "function")
    /// - Google: has "functionCall" key
    /// - Deserializable object: has "_tool_name" attribute
    /// - List: returns Vec of ToolCalls
    pub fn create(data: serde_json::Value) -> Result<CreateResult> {
        // Handle list input
        if let Some(arr) = data.as_array() {
            if arr.is_empty() {
                return Ok(CreateResult::Empty);
            }
            let mut results = Vec::new();
            for item in arr {
                match Self::create(item.clone())? {
                    CreateResult::Single(tc) => results.push(tc),
                    CreateResult::Multiple(tcs) => results.extend(tcs),
                    CreateResult::Empty => {}
                }
            }
            return Ok(CreateResult::Multiple(results));
        }

        // Detect format and parse
        if data.get("function").is_some() {
            // OpenAI format
            Self::from_provider_format(data, Provider::OpenAI).map(CreateResult::Single)
        } else if data
            .get("type")
            .and_then(|v| v.as_str())
            .map(|t| t == "function_call")
            .unwrap_or(false)
            && data.get("name").is_some()
        {
            // OpenAI/OpenRouter Responses format
            Self::from_provider_format(data, Provider::OpenAIResponses).map(CreateResult::Single)
        } else if data.get("functionCall").is_some() {
            // Google format
            Self::from_provider_format(data, Provider::GoogleGenAI).map(CreateResult::Single)
        } else if data.get("name").is_some() && data.get("input").is_some() {
            // Anthropic format
            Self::from_provider_format(data, Provider::Anthropic).map(CreateResult::Single)
        } else if data.get("_tool_name").is_some() {
            // Deserializable object format
            let tool_name = data["_tool_name"]
                .as_str()
                .ok_or_else(|| Error::Parse("_tool_name must be a string".to_string()))?
                .to_string();
            let tool_use_id = data
                .get("_tool_use_id")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| Uuid::new_v4().to_string());
            let signature = data
                .get("signature")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .or_else(|| {
                    data.get("thought_signature")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                });

            // Extract args by filtering out internal fields
            let mut args = serde_json::Map::new();
            if let Some(obj) = data.as_object() {
                for (k, v) in obj {
                    if !k.starts_with('_') && k != "signature" && k != "thought_signature" {
                        args.insert(k.clone(), v.clone());
                    }
                }
            }

            Ok(CreateResult::Single(Self {
                tool_use_id,
                tool_name,
                args: serde_json::Value::Object(args),
                raw_arguments: None,
                signature,
                tool_obj: Some(data),
            }))
        } else {
            Err(Error::Parse("Unknown tool call format".to_string()))
        }
    }

    /// Create from provider-specific format
    pub fn from_provider_format(
        provider_format: serde_json::Value,
        provider: Provider,
    ) -> Result<Self> {
        match provider {
            Provider::Anthropic | Provider::Bedrock => Ok(Self {
                tool_use_id: provider_format["id"]
                    .as_str()
                    .ok_or_else(|| Error::Parse("Missing 'id' in tool call".to_string()))?
                    .to_string(),
                tool_name: provider_format["name"]
                    .as_str()
                    .ok_or_else(|| Error::Parse("Missing 'name' in tool call".to_string()))?
                    .to_string(),
                args: provider_format["input"].clone(),
                raw_arguments: None,
                signature: None,
                tool_obj: Some(provider_format),
            }),
            Provider::OpenAI | Provider::OpenRouter => {
                let function = &provider_format["function"];
                let arguments = &function["arguments"];

                // Handle both string (real API) and object (streaming accumulator) arguments
                let (args, raw_arguments) = if let Some(args_str) = arguments.as_str() {
                    let parsed: serde_json::Value = serde_json::from_str(args_str)?;
                    (parsed, Some(args_str.to_string()))
                } else if arguments.is_object() {
                    let raw = serde_json::to_string(arguments)?;
                    (arguments.clone(), Some(raw))
                } else {
                    return Err(Error::Parse("Missing 'arguments' in tool call".to_string()));
                };

                Ok(Self {
                    tool_use_id: provider_format["id"]
                        .as_str()
                        .ok_or_else(|| Error::Parse("Missing 'id' in tool call".to_string()))?
                        .to_string(),
                    tool_name: function["name"]
                        .as_str()
                        .ok_or_else(|| Error::Parse("Missing 'name' in function".to_string()))?
                        .to_string(),
                    args,
                    raw_arguments,
                    signature: None,
                    tool_obj: Some(provider_format),
                })
            }
            Provider::OpenAIResponses | Provider::OpenRouterResponses => {
                let args_str = provider_format["arguments"].as_str().unwrap_or("");
                let call_id = provider_format
                    .get("call_id")
                    .and_then(|v| v.as_str())
                    .or_else(|| provider_format.get("id").and_then(|v| v.as_str()))
                    .ok_or_else(|| Error::Parse("Missing 'call_id' in tool call".to_string()))?;
                Ok(Self {
                    tool_use_id: call_id.to_string(),
                    tool_name: provider_format["name"]
                        .as_str()
                        .ok_or_else(|| Error::Parse("Missing 'name' in tool call".to_string()))?
                        .to_string(),
                    args: serde_json::from_str(args_str).unwrap_or_else(|_| serde_json::json!({})),
                    raw_arguments: Some(args_str.to_string()),
                    signature: None,
                    tool_obj: Some(provider_format),
                })
            }
            Provider::GoogleGenAI | Provider::GoogleAnthropic => {
                // Google format generates tool_use_id based on name + args hash (matches Python)
                let func_call = &provider_format["functionCall"];
                let name = func_call["name"]
                    .as_str()
                    .ok_or_else(|| Error::Parse("Missing 'name' in functionCall".to_string()))?;
                let args = func_call
                    .get("args")
                    .cloned()
                    .unwrap_or(serde_json::json!({}));

                // Generate ID matching Python: google_{name}_{hash}
                use std::collections::hash_map::DefaultHasher;
                use std::hash::{Hash, Hasher};
                let mut hasher = DefaultHasher::new();
                args.to_string().hash(&mut hasher);
                let hash = hasher.finish();
                let tool_use_id = format!("google_{}_{}", name, hash);

                Ok(Self {
                    tool_use_id,
                    tool_name: name.to_string(),
                    args,
                    raw_arguments: None,
                    signature: None,
                    tool_obj: Some(provider_format),
                })
            }
        }
    }

    /// Convert to provider-specific assistant message format
    pub fn to_provider_assistant_message(&self, provider: Provider) -> serde_json::Value {
        match provider {
            Provider::Anthropic | Provider::Bedrock => {
                serde_json::json!({
                    "role": "assistant",
                    "content": [{
                        "type": "tool_use",
                        "id": self.tool_use_id,
                        "name": self.tool_name,
                        "input": self.args
                    }]
                })
            }
            Provider::OpenAI | Provider::OpenRouter => {
                // Use custom formatting to match Python's json.dumps (space after colon/comma)
                let args_str = self.raw_arguments.clone().unwrap_or_else(|| {
                    // Format to match Python's json.dumps with separators=(", ", ": ")
                    format_json_python_style(&self.args)
                });
                serde_json::json!({
                    "role": "assistant",
                    "tool_calls": [{
                        "id": self.tool_use_id,
                        "type": "function",
                        "function": {
                            "name": self.tool_name,
                            "arguments": args_str
                        }
                    }]
                })
            }
            Provider::OpenAIResponses | Provider::OpenRouterResponses => {
                let args_str = self.raw_arguments.clone().unwrap_or_else(|| {
                    serde_json::to_string(&self.args).unwrap_or_else(|_| "{}".to_string())
                });
                serde_json::json!({
                    "type": "function_call",
                    "id": format!("fc_{}", self.tool_use_id),
                    "call_id": self.tool_use_id,
                    "name": self.tool_name,
                    "arguments": args_str
                })
            }
            Provider::GoogleGenAI | Provider::GoogleAnthropic => {
                serde_json::json!({
                    "role": "model",
                    "parts": [{
                        "functionCall": {
                            "name": self.tool_name,
                            "args": self.args
                        }
                    }]
                })
            }
        }
    }
}

/// Result of a tool execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// ID matching the original tool call
    pub tool_use_id: String,

    /// Name of the tool that was called (needed for Google API)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,

    /// Result content (stringified)
    pub content: String,

    /// Whether the tool execution resulted in an error
    pub is_error: bool,

    /// Provider signature for reasoning preservation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,

    /// Original tool call object for reference (as JSON)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_obj: Option<serde_json::Value>,
}

impl ToolResult {
    /// Create a successful tool result
    pub fn success(tool_use_id: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            tool_use_id: tool_use_id.into(),
            tool_name: None,
            content: content.into(),
            is_error: false,
            signature: None,
            tool_obj: None,
        }
    }

    /// Create a successful tool result with tool name (for Google API)
    pub fn success_with_name(
        tool_use_id: impl Into<String>,
        tool_name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        Self {
            tool_use_id: tool_use_id.into(),
            tool_name: Some(tool_name.into()),
            content: content.into(),
            is_error: false,
            signature: None,
            tool_obj: None,
        }
    }

    /// Create an error tool result
    pub fn error(tool_use_id: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            tool_use_id: tool_use_id.into(),
            tool_name: None,
            content: error.into(),
            is_error: true,
            signature: None,
            tool_obj: None,
        }
    }

    /// Set the tool name
    pub fn with_tool_name(mut self, name: impl Into<String>) -> Self {
        self.tool_name = Some(name.into());
        self
    }

    /// Set the tool object (JSON representation)
    pub fn with_tool_obj(mut self, obj: serde_json::Value) -> Self {
        self.tool_obj = Some(obj);
        self
    }

    /// Convert to provider-specific format
    pub fn to_provider_format(&self, provider: Provider) -> serde_json::Value {
        match provider {
            Provider::Anthropic | Provider::Bedrock => {
                serde_json::json!({
                    "type": "tool_result",
                    "tool_use_id": self.tool_use_id,
                    "content": self.content,
                    "is_error": self.is_error
                })
            }
            Provider::OpenAI | Provider::OpenRouter => {
                serde_json::json!({
                    "role": "tool",
                    "tool_call_id": self.tool_use_id,
                    "content": self.content
                })
            }
            Provider::OpenAIResponses | Provider::OpenRouterResponses => {
                serde_json::json!({
                    "type": "function_call_output",
                    "call_id": self.tool_use_id,
                    "output": self.content
                })
            }
            Provider::GoogleGenAI | Provider::GoogleAnthropic => {
                // Try to get tool_name from: 1) tool_name field, 2) tool_obj["_tool_name"], 3) "unknown"
                let name = self.tool_name.clone().unwrap_or_else(|| {
                    self.tool_obj
                        .as_ref()
                        .and_then(|obj| obj.get("_tool_name"))
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| "unknown".to_string())
                });

                serde_json::json!({
                    "functionResponse": {
                        "name": name,
                        "response": {
                            "result": self.content
                        }
                    }
                })
            }
        }
    }
}

/// A reasoning segment (extended thinking)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningSegment {
    /// Reasoning content
    pub content: String,

    /// Index in sequence of reasoning segments
    pub segment_index: usize,

    /// Provider signature for reasoning preservation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,

    /// Provider-specific metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider_metadata: Option<serde_json::Value>,
}

impl ReasoningSegment {
    /// Create a new reasoning segment with just content (index defaults to 0)
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            segment_index: 0,
            signature: None,
            provider_metadata: None,
        }
    }

    /// Create a new reasoning segment with content and index
    pub fn with_index(content: impl Into<String>, segment_index: usize) -> Self {
        Self {
            content: content.into(),
            segment_index,
            signature: None,
            provider_metadata: None,
        }
    }

    /// Set the signature
    pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
        self.signature = Some(signature.into());
        self
    }

    /// Set provider metadata
    pub fn with_provider_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.provider_metadata = Some(metadata);
        self
    }

    /// Set segment index
    pub fn with_segment_index(mut self, index: usize) -> Self {
        self.segment_index = index;
        self
    }

    /// Convert to provider-specific format
    pub fn to_provider_format(&self, provider: Provider) -> serde_json::Value {
        match provider {
            // Anthropic, Bedrock, and GoogleAnthropic (Vertex AI Claude) all use Anthropic format
            Provider::Anthropic | Provider::Bedrock | Provider::GoogleAnthropic => {
                let mut obj = serde_json::json!({
                    "type": "thinking",
                    "thinking": self.content
                });
                if let Some(ref sig) = self.signature {
                    obj["signature"] = serde_json::Value::String(sig.clone());
                }
                obj
            }
            Provider::OpenAI | Provider::OpenRouter => {
                let mut obj = serde_json::json!({
                    "type": "reasoning",
                    "content": self.content
                });
                if let Some(ref sig) = self.signature {
                    obj["signature"] = serde_json::Value::String(sig.clone());
                }
                obj
            }
            Provider::OpenAIResponses | Provider::OpenRouterResponses => {
                let mut obj = serde_json::json!({
                    "type": "reasoning",
                    "content": [{
                        "type": "output_text",
                        "text": self.content
                    }]
                });
                if let Some(ref sig) = self.signature {
                    obj["signature"] = serde_json::Value::String(sig.clone());
                }
                obj
            }
            Provider::GoogleGenAI => {
                let mut obj = serde_json::json!({
                    "thought": true,
                    "text": self.content
                });
                if let Some(ref sig) = self.signature {
                    obj["thought_signature"] = serde_json::Value::String(sig.clone());
                }
                obj
            }
        }
    }
}

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

    #[test]
    fn test_provider_from_model_string() {
        let (provider, model) = Provider::from_model_string("anthropic:claude-3-opus").unwrap();
        assert_eq!(provider, Provider::Anthropic);
        assert_eq!(model, "claude-3-opus");

        let (provider, model) = Provider::from_model_string("openai:gpt-4").unwrap();
        assert_eq!(provider, Provider::OpenAI);
        assert_eq!(model, "gpt-4");

        let (provider, model) = Provider::from_model_string("openai:resp:gpt-4").unwrap();
        assert_eq!(provider, Provider::OpenAIResponses);
        assert_eq!(model, "gpt-4");

        let (provider, model) =
            Provider::from_model_string("openrouter:resp:openai/o4-mini").unwrap();
        assert_eq!(provider, Provider::OpenRouterResponses);
        assert_eq!(model, "openai/o4-mini");

        assert!(Provider::from_model_string("invalid").is_err());
    }

    #[test]
    fn test_provider_supports_native_tools() {
        assert!(Provider::Anthropic.supports_native_tools());
        assert!(Provider::OpenAI.supports_native_tools());
        assert!(Provider::OpenAIResponses.supports_native_tools());
        assert!(Provider::GoogleAnthropic.supports_native_tools());
        assert!(Provider::GoogleGenAI.supports_native_tools());
        assert!(Provider::OpenRouter.supports_native_tools());
        assert!(Provider::OpenRouterResponses.supports_native_tools());
        assert!(Provider::Bedrock.supports_native_tools());
    }

    #[test]
    fn test_chat_message_constructors() {
        let msg = ChatMessage::system("You are helpful");
        assert_eq!(msg.role, ChatRole::System);
        assert_eq!(msg.content, "You are helpful");

        let msg = ChatMessage::user("Hello");
        assert_eq!(msg.role, ChatRole::User);

        let msg = ChatMessage::assistant("Hi there").with_cache_marker(CacheMarker::Ephemeral);
        assert_eq!(msg.role, ChatRole::Assistant);
        assert!(msg.cache_marker.is_some());
    }

    #[test]
    fn test_token_usage() {
        let usage = TokenUsage::new(100, 50, 25);
        assert_eq!(usage.input_tokens, 100);
        assert_eq!(usage.output_tokens, 50);
        assert_eq!(usage.cached_tokens, 25);
        assert_eq!(usage.total_tokens(), 150);
    }

    #[test]
    fn test_tool_call_creation() {
        let tool_call = ToolCall::new("get_weather", serde_json::json!({"city": "SF"}));
        assert_eq!(tool_call.tool_name, "get_weather");
        assert_eq!(tool_call.args["city"], "SF");
        assert!(!tool_call.tool_use_id.is_empty());
    }

    #[test]
    fn test_tool_call_from_anthropic_format() {
        let format = serde_json::json!({
            "id": "toolu_123",
            "name": "get_weather",
            "input": {"city": "SF"}
        });

        let tool_call = ToolCall::from_provider_format(format, Provider::Anthropic).unwrap();
        assert_eq!(tool_call.tool_use_id, "toolu_123");
        assert_eq!(tool_call.tool_name, "get_weather");
        assert_eq!(tool_call.args["city"], "SF");
    }

    #[test]
    fn test_tool_call_from_openai_format() {
        let format = serde_json::json!({
            "id": "call_123",
            "function": {
                "name": "get_weather",
                "arguments": "{\"city\":\"SF\"}"
            }
        });

        let tool_call = ToolCall::from_provider_format(format, Provider::OpenAI).unwrap();
        assert_eq!(tool_call.tool_use_id, "call_123");
        assert_eq!(tool_call.tool_name, "get_weather");
        assert_eq!(tool_call.args["city"], "SF");
    }

    #[test]
    fn test_tool_result_success() {
        let result = ToolResult::success("toolu_123", "Sunny, 72°F");
        assert_eq!(result.tool_use_id, "toolu_123");
        assert_eq!(result.content, "Sunny, 72°F");
        assert!(!result.is_error);
    }

    #[test]
    fn test_tool_result_error() {
        let result = ToolResult::error("toolu_123", "API error");
        assert!(result.is_error);
    }

    #[test]
    fn test_tool_result_to_anthropic_format() {
        let result = ToolResult::success("toolu_123", "Result");
        let format = result.to_provider_format(Provider::Anthropic);

        assert_eq!(format["type"], "tool_result");
        assert_eq!(format["tool_use_id"], "toolu_123");
        assert_eq!(format["content"], "Result");
    }

    #[test]
    fn test_tool_result_to_openai_format() {
        let result = ToolResult::success("call_123", "Result");
        let format = result.to_provider_format(Provider::OpenAI);

        assert_eq!(format["role"], "tool");
        assert_eq!(format["tool_call_id"], "call_123");
        assert_eq!(format["content"], "Result");
    }

    #[test]
    fn test_reasoning_segment() {
        let segment = ReasoningSegment::with_index("Thinking...", 0);
        assert_eq!(segment.content, "Thinking...");
        assert_eq!(segment.segment_index, 0);
    }

    #[test]
    fn test_reasoning_segment_to_anthropic_format() {
        let segment = ReasoningSegment::with_index("Thinking...", 0);
        let format = segment.to_provider_format(Provider::Anthropic);

        assert_eq!(format["type"], "thinking");
        assert_eq!(format["thinking"], "Thinking...");
    }
}