aither-core 0.4.1

Core trait abstractions for aither
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
//! AI language model configuration and profiling types.
//!
//! This module provides types for configuring AI language models, including
//! parameters for model behavior, pricing information, and capability profiles.
//!
//! # Examples
//!
//! ## Creating a model profile
//!
//! ```rust,ignore
//! use aither::llm::model::{Profile, Ability, Pricing};
//!
//! let mut pricing = Pricing::default();
//!
//! pricing.prompt = 0.01; // $0.01 per 1K prompt tokens
//! pricing.completion = 0.03; // $0.03 per 1K completion tokens
//! pricing.request = 0.01; // $0.01 per request
//! pricing.image = 0.1; // $0.1 per image
//! pricing.web_search = 0.05; // $0.05 per web search
//! pricing.internal_reasoning = 0.003; // $0.003 per internal reasoning
//! pricing.input_cache_read = 0.0005; // $0.0005 per input cache read
//! pricing.input_cache_write = 0.001; // $0.001 per input cache write
//!
//! let profile = Profile::new("gpt-4", "GPT-4 model", 8192)
//!     .with_ability(Ability::ToolUse)
//!     .with_ability(Ability::Vision)
//!     .with_pricing(pricing);
//! ```
//!
//! ## Configuring model parameters
//!
//! ```rust,ignore
//! use aither::llm::model::Parameters;
//!
//! let params = Parameters::default()
//!     .temperature(0.7)
//!     .top_p(0.9)
//!     .max_tokens(1000)
//!     .seed(42);
//! ```

use alloc::{string::String, vec::Vec};
use schemars::Schema;
use serde_json::Value;

/// Parameters for configuring the behavior of a language model.
///
/// This struct contains various parameters that can be used to control
/// how a language model generates responses. All parameters are optional
/// and use the builder pattern for easy configuration.
///
/// # Examples
///
/// ```rust,ignore
/// use aither::llm::model::Parameters;
///
/// let params = Parameters::default()
///     .temperature(0.7)
///     .top_p(0.9)
///     .max_tokens(1000)
///     .seed(42);
/// ```
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[allow(clippy::struct_excessive_bools)]
pub struct Parameters {
    /// Sampling temperature.
    ///
    /// Controls randomness in generation. Higher values (e.g., 1.0) make output more random,
    /// lower values (e.g., 0.1) make it more deterministic.
    pub temperature: Option<f32>,
    /// Nucleus sampling probability.
    ///
    /// Only consider tokens with cumulative probability up to this value.
    /// Typical values are between 0.9 and 1.0.
    pub top_p: Option<f32>,
    /// Top-k sampling parameter.
    ///
    /// Only consider the k most likely tokens at each step.
    pub top_k: Option<u32>,
    /// Frequency penalty to reduce repetition.
    ///
    /// Positive values penalize tokens that have already appeared.
    pub frequency_penalty: Option<f32>,
    /// Presence penalty to encourage new tokens.
    ///
    /// Positive values encourage the model to talk about new topics.
    pub presence_penalty: Option<f32>,
    /// Repetition penalty to penalize repeated tokens.
    ///
    /// Values > 1.0 discourage repetition, values < 1.0 encourage it.
    ///
    /// Local inference only: this maps onto a llama.cpp sampler and none of the
    /// hosted provider APIs accept it, so setting it has no effect on them.
    pub repetition_penalty: Option<f32>,
    /// Minimum probability for nucleus sampling.
    ///
    /// Alternative to `top_p` that sets a minimum threshold for token probabilities.
    ///
    /// Local inference only, like [`Self::repetition_penalty`].
    pub min_p: Option<f32>,
    /// Random seed for reproducibility.
    ///
    /// Use the same seed to get deterministic outputs.
    pub seed: Option<u32>,
    /// Maximum number of tokens to generate.
    ///
    /// Limits the length of the generated response.
    pub max_tokens: Option<u32>,
    /// Biases for specific logits.
    ///
    /// Each tuple contains a token string and its bias value.
    pub logit_bias: Option<Vec<(String, f32)>>,
    /// Whether to return log probabilities.
    ///
    /// When true, the model returns probability information for tokens.
    pub logprobs: Option<bool>,
    /// Number of top log probabilities to return.
    ///
    /// Only used when logprobs is true.
    pub top_logprobs: Option<u8>,
    /// Stop sequences to end generation.
    ///
    /// Generation stops when any of these strings are encountered.
    pub stop: Option<Vec<String>>,
    /// Tool choice policy for the model.
    ///
    /// Controls whether tools are allowed, required, or constrained to a specific tool.
    pub tool_choice: ToolChoice,

    /// Whether the model may request several tools in a single turn.
    ///
    /// `None` leaves the decision to the provider's own default. Set it only to
    /// override that default — forcing `false` serializes an agent loop that
    /// could otherwise fan its tool calls out concurrently.
    pub parallel_tool_calls: Option<bool>,

    /// Preferred reasoning effort when supported.
    pub reasoning_effort: Option<ReasoningEffort>,

    /// Whether the provider should include reasoning summaries in the response stream.
    pub include_reasoning: bool,

    /// Whether to enable structured outputs.
    ///
    /// When true, the model will attempt to return outputs in a structured format (e.g., JSON).
    pub structured_outputs: bool,

    /// The expected response format schema.
    ///
    /// When set, the model will attempt to return outputs matching this schema.
    pub response_format: Option<Schema>,
    /// Whether to enable native Search tool for grounding.
    pub websearch: bool,
    /// Whether to enable native Code Execution tool.
    pub code_execution: bool,
    /// Provider-native tools that are not portable across API families.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "NativeTools::is_empty")
    )]
    pub native_tools: NativeTools,
    /// Provider-specific prompt cache controls.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "CacheOptions::is_empty")
    )]
    pub cache: CacheOptions,
}

macro_rules! impl_with_methods {
    (
        impl $ty:ty {
            $($field:ident : $field_ty:ty),* $(,)?
        }
    ) => {
        impl $ty {
            $(
                /// Sets the parameter value using a builder pattern.
                ///
                /// # Arguments
                ///
                /// * `value` - The value to set for this parameter
                #[allow(clippy::missing_const_for_fn)]
                #[must_use] pub fn $field(mut self, value: $field_ty) -> Self {
                    self.$field = Some(value);
                    self
                }
            )*
        }
    };
}

impl_with_methods! {
    impl Parameters {
        temperature: f32,
        top_p: f32,
        top_k: u32,
        frequency_penalty: f32,
        presence_penalty: f32,
        repetition_penalty: f32,
        min_p: f32,
        seed: u32,
        max_tokens: u32,
        logit_bias: Vec<(String, f32)>,
        logprobs: bool,
        top_logprobs: u8,
        stop: Vec<String>,
        parallel_tool_calls: bool,
    }
}

impl Parameters {
    /// Sets whether providers should include reasoning summaries.
    #[must_use]
    pub const fn include_reasoning(mut self, include: bool) -> Self {
        self.include_reasoning = include;
        self
    }

    /// Sets the preferred reasoning effort.
    #[must_use]
    pub const fn reasoning_effort(mut self, effort: ReasoningEffort) -> Self {
        self.reasoning_effort = Some(effort);
        self
    }

    /// Sets whether to enable native Google Search tool.
    #[must_use]
    pub const fn websearch(mut self, enabled: bool) -> Self {
        self.websearch = enabled;
        self
    }

    /// Sets whether to enable native Code Execution tool.
    #[must_use]
    pub const fn code_execution(mut self, enabled: bool) -> Self {
        self.code_execution = enabled;
        self
    }

    /// Sets provider-native tools.
    #[must_use]
    pub fn native_tools(mut self, tools: NativeTools) -> Self {
        self.native_tools = tools;
        self
    }

    /// Sets `OpenAI` Responses-native tools.
    #[must_use]
    pub fn openai_tools(mut self, tools: OpenAINativeTools) -> Self {
        self.native_tools.openai = tools;
        self
    }

    /// Sets Gemini-native tools.
    #[must_use]
    pub const fn gemini_tools(mut self, tools: GeminiNativeTools) -> Self {
        self.native_tools.gemini = tools;
        self
    }

    /// Sets Claude-native tools.
    #[must_use]
    pub const fn claude_tools(mut self, tools: ClaudeNativeTools) -> Self {
        self.native_tools.claude = tools;
        self
    }

    /// Sets the OpenAI-compatible prompt cache key.
    #[must_use]
    pub fn prompt_cache_key(mut self, key: impl Into<String>) -> Self {
        let cache = self
            .cache
            .openai
            .get_or_insert_with(OpenAIPromptCache::default);
        cache.key = Some(key.into());
        self
    }

    /// Sets the OpenAI-compatible prompt cache retention policy.
    #[must_use]
    pub fn prompt_cache_retention(mut self, retention: OpenAIPromptCacheRetention) -> Self {
        let cache = self
            .cache
            .openai
            .get_or_insert_with(OpenAIPromptCache::default);
        cache.retention = Some(retention);
        self
    }

    /// Sets Claude prompt caching options.
    #[must_use]
    pub const fn claude_prompt_cache(mut self, cache: ClaudePromptCache) -> Self {
        self.cache.claude = Some(cache);
        self
    }

    /// Sets Claude prompt caching with automatic top-level cache control.
    #[must_use]
    pub const fn claude_prompt_cache_automatic(mut self, ttl: ClaudePromptCacheTtl) -> Self {
        self.cache.claude = Some(ClaudePromptCache::automatic(ttl));
        self
    }

    /// Sets Claude prompt caching with explicit block-level cache breakpoints.
    #[must_use]
    pub const fn claude_prompt_cache_explicit(
        mut self,
        ttl: ClaudePromptCacheTtl,
        breakpoints: ClaudeExplicitCacheBreakpoints,
    ) -> Self {
        self.cache.claude = Some(ClaudePromptCache::explicit(ttl, breakpoints));
        self
    }

    /// Sets Claude prompt caching with automatic and explicit breakpoint modes combined.
    #[must_use]
    pub const fn claude_prompt_cache_automatic_with_explicit(
        mut self,
        ttl: ClaudePromptCacheTtl,
        breakpoints: ClaudeExplicitCacheBreakpoints,
    ) -> Self {
        self.cache.claude = Some(ClaudePromptCache::automatic_with_explicit(ttl, breakpoints));
        self
    }

    /// Sets the Gemini cached content resource name.
    #[must_use]
    pub fn gemini_cached_content(mut self, cached_content: impl Into<String>) -> Self {
        self.cache.gemini = Some(GeminiPromptCache::new(cached_content));
        self
    }

    /// Clears all provider-specific cache options.
    #[must_use]
    pub fn without_cache(mut self) -> Self {
        self.cache = CacheOptions {
            openai: None,
            claude: None,
            gemini: None,
        };
        self
    }

    /// Sets the tool choice policy.
    #[must_use]
    pub fn tool_choice(mut self, choice: ToolChoice) -> Self {
        self.tool_choice = choice;
        self
    }
}

/// Provider-native tool configuration.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NativeTools {
    /// `OpenAI` Responses API hosted tools.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "OpenAINativeTools::is_empty")
    )]
    pub openai: OpenAINativeTools,
    /// Gemini hosted and client-side tools.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "GeminiNativeTools::is_empty")
    )]
    pub gemini: GeminiNativeTools,
    /// Claude Anthropic-defined and server tools.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "ClaudeNativeTools::is_empty")
    )]
    pub claude: ClaudeNativeTools,
}

impl NativeTools {
    /// Returns true when no provider-native tools are configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.openai.is_empty() && self.gemini.is_empty() && self.claude.is_empty()
    }
}

/// `OpenAI` Responses API native tools.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAINativeTools {
    /// Hosted web search.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub web_search: Option<OpenAIWebSearchTool>,
    /// Hosted file search over vector stores.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub file_search: Vec<OpenAIFileSearchTool>,
    /// Hosted code interpreter.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub code_interpreter: Option<OpenAICodeInterpreterTool>,
    /// Hosted image generation.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub image_generation: Option<OpenAIImageGenerationTool>,
    /// Remote MCP servers.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub mcp: Vec<OpenAIMcpTool>,
    /// Computer use preview.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub computer_use: Option<OpenAIComputerUseTool>,
}

impl OpenAINativeTools {
    /// Returns true when no `OpenAI` native tools are configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.web_search.is_none()
            && self.file_search.is_empty()
            && self.code_interpreter.is_none()
            && self.image_generation.is_none()
            && self.mcp.is_empty()
            && self.computer_use.is_none()
    }

    /// Enables hosted web search with default API settings.
    #[must_use]
    pub fn with_web_search(mut self, tool: OpenAIWebSearchTool) -> Self {
        self.web_search = Some(tool);
        self
    }

    /// Enables hosted web search with default API settings.
    #[must_use]
    pub fn enable_web_search(mut self) -> Self {
        self.web_search = Some(OpenAIWebSearchTool::default());
        self
    }

    /// Adds a file search tool.
    #[must_use]
    pub fn with_file_search(mut self, tool: OpenAIFileSearchTool) -> Self {
        self.file_search.push(tool);
        self
    }

    /// Enables hosted code interpreter.
    #[must_use]
    pub fn with_code_interpreter(mut self, tool: OpenAICodeInterpreterTool) -> Self {
        self.code_interpreter = Some(tool);
        self
    }

    /// Enables hosted image generation.
    #[must_use]
    pub const fn with_image_generation(mut self, tool: OpenAIImageGenerationTool) -> Self {
        self.image_generation = Some(tool);
        self
    }

    /// Adds a remote MCP server.
    #[must_use]
    pub fn with_mcp(mut self, tool: OpenAIMcpTool) -> Self {
        self.mcp.push(tool);
        self
    }

    /// Enables computer use preview.
    #[must_use]
    pub fn with_computer_use(mut self, tool: OpenAIComputerUseTool) -> Self {
        self.computer_use = Some(tool);
        self
    }
}

/// `OpenAI` hosted web search configuration.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIWebSearchTool {
    /// Whether live web access is allowed. `None` uses `OpenAI`'s default.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub external_web_access: Option<bool>,
    /// Official filter object, such as `allowed_domains`.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub filters: Option<Value>,
    /// Official user location object.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub user_location: Option<Value>,
}

impl OpenAIWebSearchTool {
    /// Sets whether live web access is allowed.
    #[must_use]
    pub const fn external_web_access(mut self, allowed: bool) -> Self {
        self.external_web_access = Some(allowed);
        self
    }

    /// Sets the official filter object.
    #[must_use]
    pub fn filters(mut self, filters: Value) -> Self {
        self.filters = Some(filters);
        self
    }

    /// Sets the official user location object.
    #[must_use]
    pub fn user_location(mut self, location: Value) -> Self {
        self.user_location = Some(location);
        self
    }
}

/// `OpenAI` hosted file search configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIFileSearchTool {
    /// Vector stores to search.
    pub vector_store_ids: Vec<String>,
    /// Maximum number of search results.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub max_num_results: Option<u32>,
    /// Whether to request `file_search_call.results` in the response include list.
    pub include_results: bool,
    /// Official filter object.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub filters: Option<Value>,
}

impl OpenAIFileSearchTool {
    /// Creates file search over the provided vector stores.
    #[must_use]
    pub fn new(vector_store_ids: impl Into<Vec<String>>) -> Self {
        Self {
            vector_store_ids: vector_store_ids.into(),
            max_num_results: None,
            include_results: false,
            filters: None,
        }
    }

    /// Sets maximum result count.
    #[must_use]
    pub const fn max_num_results(mut self, value: u32) -> Self {
        self.max_num_results = Some(value);
        self
    }

    /// Requests file search result inclusion.
    #[must_use]
    pub const fn include_results(mut self, include: bool) -> Self {
        self.include_results = include;
        self
    }

    /// Sets the official filter object.
    #[must_use]
    pub fn filters(mut self, filters: Value) -> Self {
        self.filters = Some(filters);
        self
    }
}

/// `OpenAI` code interpreter configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAICodeInterpreterTool {
    /// Container selection.
    pub container: OpenAICodeInterpreterContainer,
}

impl Default for OpenAICodeInterpreterTool {
    fn default() -> Self {
        Self {
            container: OpenAICodeInterpreterContainer::Auto(OpenAIAutoContainer::default()),
        }
    }
}

impl OpenAICodeInterpreterTool {
    /// Uses an automatically managed container.
    #[must_use]
    pub const fn auto() -> Self {
        Self {
            container: OpenAICodeInterpreterContainer::Auto(OpenAIAutoContainer::new()),
        }
    }

    /// Uses an existing container ID.
    #[must_use]
    pub fn existing(container_id: impl Into<String>) -> Self {
        Self {
            container: OpenAICodeInterpreterContainer::Existing(container_id.into()),
        }
    }
}

/// `OpenAI` code interpreter container selection.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum OpenAICodeInterpreterContainer {
    /// Automatically create or reuse a container.
    Auto(OpenAIAutoContainer),
    /// Use an existing container ID.
    Existing(String),
}

/// `OpenAI` automatically managed code interpreter container.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIAutoContainer {
    /// Memory tier such as `1g`, `4g`, `16g`, or `64g`.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub memory_limit: Option<String>,
    /// File IDs to preload into the container.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub file_ids: Vec<String>,
}

impl OpenAIAutoContainer {
    /// Creates an auto container with default API settings.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            memory_limit: None,
            file_ids: Vec::new(),
        }
    }

    /// Sets the memory tier.
    #[must_use]
    pub fn memory_limit(mut self, memory_limit: impl Into<String>) -> Self {
        self.memory_limit = Some(memory_limit.into());
        self
    }

    /// Preloads file IDs.
    #[must_use]
    pub fn file_ids(mut self, file_ids: impl Into<Vec<String>>) -> Self {
        self.file_ids = file_ids.into();
        self
    }
}

/// `OpenAI` image generation tool configuration.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIImageGenerationTool {
    /// Number of partial image events to stream.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub partial_images: Option<u8>,
}

impl OpenAIImageGenerationTool {
    /// Sets partial image count.
    #[must_use]
    pub const fn partial_images(mut self, count: u8) -> Self {
        self.partial_images = Some(count);
        self
    }
}

/// `OpenAI` remote MCP server configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIMcpTool {
    /// Label for the server.
    pub server_label: String,
    /// Server URL.
    pub server_url: String,
    /// Approval policy, such as `never` or `always`.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub require_approval: Option<String>,
    /// Optional allowlist of tool names.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub allowed_tools: Vec<String>,
}

impl OpenAIMcpTool {
    /// Creates a remote MCP server tool.
    #[must_use]
    pub fn new(server_label: impl Into<String>, server_url: impl Into<String>) -> Self {
        Self {
            server_label: server_label.into(),
            server_url: server_url.into(),
            require_approval: None,
            allowed_tools: Vec::new(),
        }
    }

    /// Sets approval policy.
    #[must_use]
    pub fn require_approval(mut self, policy: impl Into<String>) -> Self {
        self.require_approval = Some(policy.into());
        self
    }

    /// Sets allowed tools.
    #[must_use]
    pub fn allowed_tools(mut self, tools: impl Into<Vec<String>>) -> Self {
        self.allowed_tools = tools.into();
        self
    }
}

/// `OpenAI` computer use preview tool configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIComputerUseTool {
    /// Display width in pixels.
    pub display_width: u32,
    /// Display height in pixels.
    pub display_height: u32,
    /// Environment such as `browser`.
    pub environment: String,
}

impl OpenAIComputerUseTool {
    /// Creates a computer use preview tool.
    #[must_use]
    pub fn new(display_width: u32, display_height: u32, environment: impl Into<String>) -> Self {
        Self {
            display_width,
            display_height,
            environment: environment.into(),
        }
    }
}

/// Gemini-native tools.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GeminiNativeTools {
    /// Grounding with Google Search.
    pub google_search: bool,
    /// Built-in code execution.
    pub code_execution: bool,
    /// URL Context tool.
    pub url_context: bool,
}

impl GeminiNativeTools {
    /// Returns true when no Gemini-native tools are configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        !self.google_search && !self.code_execution && !self.url_context
    }

    /// Enables Grounding with Google Search.
    #[must_use]
    pub const fn google_search(mut self, enabled: bool) -> Self {
        self.google_search = enabled;
        self
    }

    /// Enables Code Execution.
    #[must_use]
    pub const fn code_execution(mut self, enabled: bool) -> Self {
        self.code_execution = enabled;
        self
    }

    /// Enables URL Context.
    #[must_use]
    pub const fn url_context(mut self, enabled: bool) -> Self {
        self.url_context = enabled;
        self
    }
}

/// Claude-native tools.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClaudeNativeTools {
    /// Server-side web search.
    pub web_search: bool,
    /// Server-side web fetch.
    pub web_fetch: bool,
    /// Server-side code execution.
    pub code_execution: bool,
    /// Client-side bash tool.
    pub bash: bool,
    /// Client-side text editor tool.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub text_editor: Option<ClaudeTextEditorTool>,
}

impl ClaudeNativeTools {
    /// Returns true when no Claude-native tools are configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        !self.web_search
            && !self.web_fetch
            && !self.code_execution
            && !self.bash
            && self.text_editor.is_none()
    }

    /// Enables server-side web search.
    #[must_use]
    pub const fn web_search(mut self, enabled: bool) -> Self {
        self.web_search = enabled;
        self
    }

    /// Enables server-side web fetch.
    #[must_use]
    pub const fn web_fetch(mut self, enabled: bool) -> Self {
        self.web_fetch = enabled;
        self
    }

    /// Enables server-side code execution.
    #[must_use]
    pub const fn code_execution(mut self, enabled: bool) -> Self {
        self.code_execution = enabled;
        self
    }

    /// Enables client-side bash.
    #[must_use]
    pub const fn bash(mut self, enabled: bool) -> Self {
        self.bash = enabled;
        self
    }

    /// Enables client-side text editor.
    #[must_use]
    pub const fn text_editor(mut self, tool: ClaudeTextEditorTool) -> Self {
        self.text_editor = Some(tool);
        self
    }
}

/// Claude text editor tool configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClaudeTextEditorTool {
    /// Optional maximum characters returned by the `view` command.
    pub max_characters: Option<u32>,
}

impl ClaudeTextEditorTool {
    /// Sets maximum characters for view results.
    #[must_use]
    pub const fn max_characters(mut self, value: u32) -> Self {
        self.max_characters = Some(value);
        self
    }
}

/// Tool choice policy for tool calling.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ToolChoice {
    /// Let the model decide whether to call tools.
    #[default]
    Auto,
    /// Disallow tool calls.
    None,
    /// Require a tool call (any available tool).
    Required,
    /// Constrain the model to a specific tool.
    Exact(String),
}

/// Effort levels available for reasoning-focused models.
///
/// The ladder is ordered from least to most reasoning, and spans the union of
/// what the providers accept. **No provider accepts every level**, and the
/// supported set varies by model within a provider, so each provider crate maps
/// this to its own wire vocabulary and rejects a level its API does not have —
/// rather than silently clamping to the nearest one, which would bill the
/// caller for a depth they did not ask for.
///
/// Deliberately carries no `as_str`: the wire spelling is not shared. `Minimal`
/// is `"minimal"` on `OpenAI` and Gemini and does not exist on Claude; `XHigh`
/// and `Max` exist on Claude and `OpenAI` but not Gemini.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum ReasoningEffort {
    /// No reasoning at all: answer directly.
    ///
    /// On Claude this disables thinking, which the API rejects on models whose
    /// thinking is always on.
    None,
    /// The least reasoning a model will do while still reasoning.
    Minimal,
    /// Shallow reasoning, for latency-sensitive work.
    Low,
    /// Balanced reasoning depth.
    Medium,
    /// Thorough reasoning. The default on current Claude models.
    High,
    /// Beyond `High`, where the extra depth pays for itself.
    XHigh,
    /// The most reasoning available, for quality-first workloads.
    Max,
}

/// Provider-specific prompt cache controls.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CacheOptions {
    /// OpenAI-compatible prompt cache controls (`OpenAI`, `Copilot`).
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub openai: Option<OpenAIPromptCache>,
    /// Anthropic Claude prompt cache controls.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub claude: Option<ClaudePromptCache>,
    /// Gemini cached content reference.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub gemini: Option<GeminiPromptCache>,
}

impl CacheOptions {
    /// Returns true when no provider cache options are set.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.openai.is_none() && self.claude.is_none() && self.gemini.is_none()
    }
}

/// OpenAI-compatible prompt cache controls.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OpenAIPromptCache {
    /// Stable key used to route related prompts to the same cache shard.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub key: Option<String>,
    /// Retention policy for prompt cache entries.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub retention: Option<OpenAIPromptCacheRetention>,
}

/// `OpenAI` prompt cache retention policies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum OpenAIPromptCacheRetention {
    /// Keep cache entries in-memory (default `OpenAI` retention mode).
    InMemory,
    /// Keep cache entries for 24 hours.
    #[cfg_attr(feature = "serde", serde(rename = "24h"))]
    Hours24,
}

impl OpenAIPromptCacheRetention {
    /// Returns the API value expected by OpenAI-compatible endpoints.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InMemory => "in-memory",
            Self::Hours24 => "24h",
        }
    }
}

/// Claude prompt cache control for the Messages API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClaudePromptCache {
    /// Requested cache TTL policy.
    pub ttl: ClaudePromptCacheTtl,
    /// Cache application strategy.
    pub strategy: ClaudePromptCacheStrategy,
}

impl ClaudePromptCache {
    /// Build a cache configuration with the chosen TTL.
    #[must_use]
    pub const fn new(ttl: ClaudePromptCacheTtl) -> Self {
        Self {
            ttl,
            strategy: ClaudePromptCacheStrategy::Automatic,
        }
    }

    /// Build an automatic top-level cache configuration.
    #[must_use]
    pub const fn automatic(ttl: ClaudePromptCacheTtl) -> Self {
        Self::new(ttl)
    }

    /// Build an explicit block-level cache configuration.
    #[must_use]
    pub const fn explicit(
        ttl: ClaudePromptCacheTtl,
        breakpoints: ClaudeExplicitCacheBreakpoints,
    ) -> Self {
        Self {
            ttl,
            strategy: ClaudePromptCacheStrategy::Explicit(breakpoints),
        }
    }

    /// Build a cache configuration that combines automatic and explicit breakpoints.
    #[must_use]
    pub const fn automatic_with_explicit(
        ttl: ClaudePromptCacheTtl,
        breakpoints: ClaudeExplicitCacheBreakpoints,
    ) -> Self {
        Self {
            ttl,
            strategy: ClaudePromptCacheStrategy::AutomaticAndExplicit(breakpoints),
        }
    }

    /// Override the cache strategy.
    #[must_use]
    pub const fn with_strategy(mut self, strategy: ClaudePromptCacheStrategy) -> Self {
        self.strategy = strategy;
        self
    }
}

/// Claude prompt cache TTL values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ClaudePromptCacheTtl {
    /// Short-lived cache (5 minutes).
    #[default]
    FiveMinutes,
    /// Extended cache (1 hour).
    OneHour,
}

impl ClaudePromptCacheTtl {
    /// Returns the API value expected by Claude.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::FiveMinutes => "5m",
            Self::OneHour => "1h",
        }
    }
}

/// Claude prompt cache strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ClaudePromptCacheStrategy {
    /// Add top-level `cache_control` (automatic caching).
    #[default]
    Automatic,
    /// Place `cache_control` on selected cacheable blocks.
    Explicit(ClaudeExplicitCacheBreakpoints),
    /// Use top-level automatic caching and explicit breakpoints together.
    AutomaticAndExplicit(ClaudeExplicitCacheBreakpoints),
}

/// Explicit Claude cache breakpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClaudeExplicitCacheBreakpoint {
    /// Block target where cache control should be applied.
    pub target: ClaudeCacheBreakpointTarget,
    /// Optional TTL override for this breakpoint.
    ///
    /// When omitted, request-level `ClaudePromptCache::ttl` is used.
    pub ttl: Option<ClaudePromptCacheTtl>,
}

impl ClaudeExplicitCacheBreakpoint {
    /// Creates a breakpoint for the given target using request-level default TTL.
    #[must_use]
    pub const fn new(target: ClaudeCacheBreakpointTarget) -> Self {
        Self { target, ttl: None }
    }

    /// Overrides TTL for this breakpoint.
    #[must_use]
    pub const fn with_ttl(mut self, ttl: ClaudePromptCacheTtl) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Returns the effective TTL for this breakpoint.
    #[must_use]
    pub const fn effective_ttl(self, default_ttl: ClaudePromptCacheTtl) -> ClaudePromptCacheTtl {
        match self.ttl {
            Some(ttl) => ttl,
            None => default_ttl,
        }
    }
}

/// Explicit Claude cache breakpoint placement target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ClaudeCacheBreakpointTarget {
    /// The last tool definition.
    LastTool,
    /// A specific tool definition by index.
    Tool(usize),
    /// The last non-empty system text block.
    LastSystem,
    /// A specific system text block by index.
    System(usize),
    /// The last cacheable content block in messages.
    LastMessage,
    /// A specific message content block by message and block indices.
    Message {
        /// Message index in `messages`.
        message_index: usize,
        /// Content block index within the message.
        block_index: usize,
    },
}

/// Up to four explicit Claude cache breakpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClaudeExplicitCacheBreakpoints {
    /// First explicit breakpoint.
    pub first: ClaudeExplicitCacheBreakpoint,
    /// Optional second explicit breakpoint.
    pub second: Option<ClaudeExplicitCacheBreakpoint>,
    /// Optional third explicit breakpoint.
    pub third: Option<ClaudeExplicitCacheBreakpoint>,
    /// Optional fourth explicit breakpoint.
    pub fourth: Option<ClaudeExplicitCacheBreakpoint>,
}

impl ClaudeExplicitCacheBreakpoints {
    /// Creates an explicit breakpoint set with one mandatory breakpoint.
    #[must_use]
    pub const fn new(first: ClaudeExplicitCacheBreakpoint) -> Self {
        Self {
            first,
            second: None,
            third: None,
            fourth: None,
        }
    }

    /// Sets the second breakpoint.
    #[must_use]
    pub const fn with_second(mut self, second: ClaudeExplicitCacheBreakpoint) -> Self {
        self.second = Some(second);
        self
    }

    /// Sets the third breakpoint.
    #[must_use]
    pub const fn with_third(mut self, third: ClaudeExplicitCacheBreakpoint) -> Self {
        self.third = Some(third);
        self
    }

    /// Sets the fourth breakpoint.
    #[must_use]
    pub const fn with_fourth(mut self, fourth: ClaudeExplicitCacheBreakpoint) -> Self {
        self.fourth = Some(fourth);
        self
    }

    /// Returns all configured breakpoints in declared order.
    pub fn iter(self) -> impl Iterator<Item = ClaudeExplicitCacheBreakpoint> {
        [Some(self.first), self.second, self.third, self.fourth]
            .into_iter()
            .flatten()
    }

    /// Number of configured breakpoints.
    #[must_use]
    pub const fn count(&self) -> usize {
        1 + self.second.is_some() as usize
            + self.third.is_some() as usize
            + self.fourth.is_some() as usize
    }

    /// Returns true when all four breakpoint slots are in use.
    #[must_use]
    pub const fn is_full(&self) -> bool {
        self.fourth.is_some()
    }

    /// Cache only the last cacheable message content block.
    #[must_use]
    pub const fn messages_only() -> Self {
        Self::new(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::LastMessage,
        ))
    }

    /// Cache tool definitions, system blocks, and message blocks.
    #[must_use]
    pub const fn all() -> Self {
        Self::new(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::LastTool,
        ))
        .with_second(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::LastSystem,
        ))
        .with_third(ClaudeExplicitCacheBreakpoint::new(
            ClaudeCacheBreakpointTarget::LastMessage,
        ))
    }
}

impl Default for ClaudeExplicitCacheBreakpoints {
    fn default() -> Self {
        Self::messages_only()
    }
}

/// Gemini cached content reference.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GeminiPromptCache {
    /// Resource name returned by Gemini cache creation APIs.
    pub cached_content: String,
}

impl GeminiPromptCache {
    /// Creates a Gemini cached content reference.
    #[must_use]
    pub fn new(cached_content: impl Into<String>) -> Self {
        Self {
            cached_content: cached_content.into(),
        }
    }
}

/// Represents a language model's profile, including its name, description, abilities, context length, and optional pricing.
///
/// A model profile provides comprehensive information about a language model's
/// capabilities, limitations, and pricing structure. This allows applications
/// to make informed decisions about which model to use for specific tasks.
///
/// # Examples
///
/// ```rust,ignore
/// use aither::llm::model::{Profile, Ability, Pricing};
///
/// let profile = Profile::new("gpt-4", "GPT-4 Turbo", 128000)
///     .with_ability(Ability::ToolUse)
///     .with_ability(Ability::Vision);
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Profile {
    /// The name of the model.
    pub name: String,
    /// The author of the model.
    pub author: String,
    /// The slug of the model.
    pub slug: String,
    /// A description of the model.
    pub description: String,
    /// The abilities supported by the model.
    pub abilities: Vec<Ability>,
    /// The maximum context length supported by the model.
    pub context_length: u32,
    /// Optional pricing information for the model.
    pub pricing: Option<Pricing>,
}

/// Pricing information for a model's various capabilities (unit: USD).
///
/// This struct contains detailed pricing information for different aspects
/// of model usage. All prices are in USD and typically represent costs
/// per unit (token, request, image, etc.).
///
/// # Examples
///
/// ```rust,ignore
/// use aither::llm::model::Pricing;
///
/// let mut pricing = Pricing::default();
///
/// pricing.prompt = 0.01; // $0.01 per 1K prompt tokens
/// pricing.completion = 0.03; // $0.03 per 1K completion tokens
/// pricing.image = 0.25; // $0.25 per image
/// pricing.web_search = 0.005; // $0.005 per search
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Pricing {
    /// Price per prompt token.
    pub prompt: f64,
    /// Price per completion token.
    pub completion: f64,
    /// Price per request.
    pub request: f64,
    /// Price per image processed.
    pub image: f64,
    /// Price per web search.
    pub web_search: f64,
    /// Price for internal reasoning.
    pub internal_reasoning: f64,
    /// Price for reading from input cache.
    pub input_cache_read: f64,
    /// Price for writing to input cache.
    pub input_cache_write: f64,
}

/// Indicates which parameters are supported by a model.
///
/// This struct is used to communicate which configuration parameters
/// a specific model supports, allowing applications to adjust their
/// requests accordingly.
///
/// # Examples
///
/// ```rust,ignore
/// use aither::llm::model::SupportedParameters;
///
/// let mut support = SupportedParameters::default();
///
/// support.temperature = true;
/// support.max_tokens = true;
/// support.top_p = true;
/// support.stop = true;
/// support.seed = true;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[allow(clippy::struct_excessive_bools)]
#[non_exhaustive]
pub struct SupportedParameters {
    /// Whether `max_tokens` is supported.
    pub max_tokens: bool,
    /// Whether temperature is supported.
    pub temperature: bool,
    /// Whether `top_p` is supported.
    pub top_p: bool,
    /// Whether reasoning is supported.
    pub reasoning: bool,
    /// Whether including reasoning is supported.
    pub include_reasoning: bool,
    /// Whether structured outputs are supported.
    pub structured_outputs: bool,
    /// Whether response format is supported.
    pub response_format: bool,
    /// Whether stop sequences are supported.
    pub stop: bool,
    /// Whether frequency penalty is supported.
    pub frequency_penalty: bool,
    /// Whether presence penalty is supported.
    pub presence_penalty: bool,
    /// Whether seed is supported.
    pub seed: bool,
}

impl Profile {
    /// Creates a new `Profile` with the given name, description, and context length.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the model (e.g., "gpt-4", "claude-3-opus")
    /// * `description` - A human-readable description of the model
    /// * `context_length` - Maximum number of tokens the model can process
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use aither::llm::model::Profile;
    ///
    /// let profile = Profile::new("gpt-4", "GPT-4 Turbo", 128000);
    /// ```
    pub fn new(
        name: impl Into<String>,
        author: impl Into<String>,
        slug: impl Into<String>,
        description: impl Into<String>,
        context_length: u32,
    ) -> Self {
        Self {
            name: name.into(),
            author: author.into(),
            slug: slug.into(),
            description: description.into(),
            abilities: Vec::new(),
            context_length,
            pricing: None,
        }
    }

    /// Adds a single ability to the profile.
    ///
    /// # Arguments
    ///
    /// * `ability` - The ability to add to this profile
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use aither::llm::model::{Profile, Ability};
    ///
    /// let profile = Profile::new("vision-model", "A vision-capable model", 8192)
    ///     .with_ability(Ability::Vision);
    /// ```
    #[must_use]
    pub fn with_ability(self, ability: Ability) -> Self {
        self.with_abilities([ability])
    }

    /// Adds multiple abilities to the profile.
    ///
    /// # Arguments
    ///
    /// * `abilities` - An iterable collection of abilities to add
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use aither::llm::model::{Profile, Ability};
    ///
    /// let abilities = [Ability::ToolUse, Ability::Vision, Ability::Audio];
    /// let profile = Profile::new("multimodal", "A multimodal model", 32768)
    ///     .with_abilities(abilities);
    /// ```
    #[must_use]
    pub fn with_abilities(mut self, abilities: impl IntoIterator<Item = Ability>) -> Self {
        self.abilities.extend(abilities);
        self
    }

    /// Sets the pricing information for the profile.
    ///
    /// # Arguments
    ///
    /// * `pricing` - The pricing structure for this model
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use aither::llm::model::{Profile, Pricing};
    ///
    /// let mut pricing = Pricing::default();
    ///
    /// pricing.prompt = 0.01;
    /// pricing.completion = 0.03;
    ///
    /// let profile = Profile::new("paid-model", "A paid model", 4096)
    ///     .with_pricing(pricing);
    /// ```
    #[must_use]
    pub const fn with_pricing(mut self, pricing: Pricing) -> Self {
        self.pricing = Some(pricing);
        self
    }
}

/// Represents the capabilities that a language model may support.
///
/// This enum defines the various advanced capabilities that modern language
/// models can possess beyond basic text generation. These capabilities can
/// be used to determine which models are suitable for specific use cases.
///
/// # Examples
///
/// ```rust,ignore
/// use aither::llm::model::Ability;
///
/// // Check if a model supports vision
/// let abilities = [Ability::Vision, Ability::ToolUse];
/// let has_vision = abilities.contains(&Ability::Vision);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Ability {
    /// The model can use external tools/functions.
    ToolUse,
    /// The model can process and understand images.
    Vision,
    /// The model can process and understand audio.
    Audio,
    /// The model can generate audio output.
    AudioOutput,
    /// The model can process and understand video.
    Video,
    /// The model can perform web searches natively.
    WebSearch,
    /// The model can directly read and reason over PDF or document attachments.
    Pdf,
    /// The model can execute code.
    CodeExecution,
    /// The model supports extended thinking/reasoning.
    Reasoning,
    /// The model can generate images.
    ImageGeneration,
    /// The model supports computer use / desktop interaction.
    ComputerUse,
    /// The model supports prompt caching.
    PromptCaching,
    /// The model supports assistant prefill (pre-filling assistant responses).
    AssistantPrefill,
}

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

    #[test]
    fn profile_creation() {
        let profile = Profile::new("Test model", "test", "test-model", "A test model", 4096);

        assert_eq!(profile.name, "Test model");
        assert_eq!(profile.slug, "test-model");
        assert_eq!(profile.description, "A test model");
        assert_eq!(profile.context_length, 4096);
        assert!(
            profile.abilities.is_empty(),
            "expected no abilities, got {:?}",
            profile.abilities
        );
        assert!(profile.pricing.is_none());
    }

    #[test]
    fn profile_with_single_ability() {
        let profile = Profile::new(
            "Test vision model",
            "test",
            "vision-model",
            "A vision model",
            8192,
        )
        .with_ability(Ability::Vision);

        assert_eq!(profile.abilities.len(), 1);
        assert_eq!(profile.abilities[0], Ability::Vision);
    }

    #[test]
    fn profile_with_multiple_abilities() {
        let abilities = [Ability::ToolUse, Ability::Vision, Ability::Audio];
        let profile = Profile::new(
            "Test",
            "test",
            "multimodal-model",
            "A multimodal model",
            16384,
        )
        .with_abilities(abilities);

        assert_eq!(profile.abilities.len(), 3);
        assert_eq!(profile.abilities, abilities);
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn profile_with_pricing() {
        let pricing = Pricing {
            prompt: 0.0001,
            completion: 0.0002,
            request: 0.001,
            image: 0.01,
            web_search: 0.005,
            internal_reasoning: 0.0003,
            input_cache_read: 0.00005,
            input_cache_write: 0.0001,
        };

        let profile = Profile::new(
            "Test paid model",
            "test",
            "paid-model",
            "A paid model",
            2048,
        )
        .with_pricing(pricing);

        assert!(profile.pricing.is_some());
        let profile_pricing = profile.pricing.unwrap();
        assert_eq!(profile_pricing.prompt, 0.0001);
        assert_eq!(profile_pricing.completion, 0.0002);
        assert_eq!(profile_pricing.request, 0.001);
        assert_eq!(profile_pricing.image, 0.01);
        assert_eq!(profile_pricing.web_search, 0.005);
        assert_eq!(profile_pricing.internal_reasoning, 0.0003);
        assert_eq!(profile_pricing.input_cache_read, 0.00005);
        assert_eq!(profile_pricing.input_cache_write, 0.0001);
    }

    #[test]
    fn profile_builder_pattern() {
        let pricing = Pricing {
            prompt: 0.001,
            completion: 0.002,
            request: 0.01,
            image: 0.1,
            web_search: 0.05,
            internal_reasoning: 0.003,
            input_cache_read: 0.0005,
            input_cache_write: 0.001,
        };

        let profile = Profile::new("Test", "test", "full-model", "A full-featured model", 32768)
            .with_ability(Ability::ToolUse)
            .with_ability(Ability::Vision)
            .with_abilities([Ability::Audio, Ability::WebSearch])
            .with_pricing(pricing);

        assert_eq!(profile.name, "Test");
        assert_eq!(profile.slug, "full-model");
        assert_eq!(profile.description, "A full-featured model");
        assert_eq!(profile.context_length, 32768);
        assert_eq!(profile.abilities.len(), 4);
        assert!(profile.abilities.contains(&Ability::ToolUse));
        assert!(profile.abilities.contains(&Ability::Vision));
        assert!(profile.abilities.contains(&Ability::Audio));
        assert!(profile.abilities.contains(&Ability::WebSearch));
        assert!(profile.pricing.is_some());
    }

    #[test]
    fn ability_equality() {
        assert_eq!(Ability::ToolUse, Ability::ToolUse);
        assert_eq!(Ability::Vision, Ability::Vision);
        assert_eq!(Ability::Audio, Ability::Audio);
        assert_eq!(Ability::WebSearch, Ability::WebSearch);

        assert_ne!(Ability::ToolUse, Ability::Vision);
        assert_ne!(Ability::Audio, Ability::WebSearch);
    }

    #[test]
    fn ability_debug() {
        let ability = Ability::ToolUse;
        let debug_str = alloc::format!("{ability:?}");
        assert!(debug_str.contains("ToolUse"));
    }

    #[test]
    fn profile_debug() {
        let profile = Profile::new("Test model", "test", "debug-model", "A debug model", 1024);
        let debug_str = alloc::format!("{profile:?}");
        assert!(debug_str.contains("debug-model"));
        assert!(debug_str.contains("A debug model"));
        assert!(debug_str.contains("1024"));
    }

    #[test]
    fn profile_clone() {
        let original = Profile::new("Test model", "test", "original", "Original model", 2048)
            .with_ability(Ability::Vision);
        let cloned = original.clone();

        assert_eq!(original.name, cloned.name);
        assert_eq!(original.description, cloned.description);
        assert_eq!(original.context_length, cloned.context_length);
        assert_eq!(original.abilities, cloned.abilities);
    }

    #[test]
    fn pricing_debug() {
        let pricing = Pricing {
            prompt: 0.001,
            completion: 0.002,
            request: 0.01,
            image: 0.1,
            web_search: 0.05,
            internal_reasoning: 0.003,
            input_cache_read: 0.0005,
            input_cache_write: 0.001,
        };

        let debug_str = alloc::format!("{pricing:?}");
        assert!(debug_str.contains("0.001"));
        assert!(debug_str.contains("0.002"));
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn pricing_clone() {
        let original = Pricing {
            prompt: 0.001,
            completion: 0.002,
            request: 0.01,
            image: 0.1,
            web_search: 0.05,
            internal_reasoning: 0.003,
            input_cache_read: 0.0005,
            input_cache_write: 0.001,
        };
        let cloned = original.clone();

        assert_eq!(original.prompt, cloned.prompt);
        assert_eq!(original.completion, cloned.completion);
        assert_eq!(original.request, cloned.request);
        assert_eq!(original.image, cloned.image);
        assert_eq!(original.web_search, cloned.web_search);
        assert_eq!(original.internal_reasoning, cloned.internal_reasoning);
        assert_eq!(original.input_cache_read, cloned.input_cache_read);
        assert_eq!(original.input_cache_write, cloned.input_cache_write);
    }

    #[test]
    fn pricing_equality() {
        let pricing1 = Pricing {
            prompt: 0.001,
            completion: 0.002,
            request: 0.01,
            image: 0.1,
            web_search: 0.05,
            internal_reasoning: 0.003,
            input_cache_read: 0.0005,
            input_cache_write: 0.001,
        };

        let pricing2 = Pricing {
            prompt: 0.001,
            completion: 0.002,
            request: 0.01,
            image: 0.1,
            web_search: 0.05,
            internal_reasoning: 0.003,
            input_cache_read: 0.0005,
            input_cache_write: 0.001,
        };

        let pricing3 = Pricing {
            prompt: 0.002, // Different value
            completion: 0.002,
            request: 0.01,
            image: 0.1,
            web_search: 0.05,
            internal_reasoning: 0.003,
            input_cache_read: 0.0005,
            input_cache_write: 0.001,
        };

        assert_eq!(pricing1, pricing2);
        assert_ne!(pricing1, pricing3);
    }

    #[test]
    fn supported_parameters() {
        let params = SupportedParameters {
            max_tokens: true,
            temperature: true,
            top_p: false,
            structured_outputs: true,
            stop: true,
            presence_penalty: true,
            ..Default::default()
        };

        assert!(params.max_tokens);
        assert!(params.temperature);
        assert!(!params.top_p);
    }

    #[test]
    fn parameters_debug() {
        let params = Parameters::default()
            .temperature(0.7)
            .top_p(0.9)
            .top_k(40)
            .seed(42)
            .max_tokens(1000);

        let debug_str = alloc::format!("{params:?}");
        assert!(debug_str.contains("0.7"));
        assert!(debug_str.contains("42"));
        assert!(debug_str.contains("1000"));
    }

    #[test]
    fn parameters_cache_builder_sets_expected_fields() {
        let params = Parameters::default()
            .prompt_cache_key("project:chat:42")
            .prompt_cache_retention(OpenAIPromptCacheRetention::Hours24)
            .claude_prompt_cache(ClaudePromptCache::new(ClaudePromptCacheTtl::OneHour))
            .gemini_cached_content("cachedContents/session-42");

        let openai_cache = params
            .cache
            .openai
            .as_ref()
            .expect("openai cache should be set");
        assert_eq!(openai_cache.key.as_deref(), Some("project:chat:42"));
        assert_eq!(
            openai_cache.retention,
            Some(OpenAIPromptCacheRetention::Hours24)
        );
        assert_eq!(
            params.cache.claude,
            Some(ClaudePromptCache::new(ClaudePromptCacheTtl::OneHour))
        );
        assert_eq!(
            params
                .cache
                .gemini
                .as_ref()
                .map(|cache| cache.cached_content.as_str()),
            Some("cachedContents/session-42")
        );
    }

    #[test]
    fn cache_options_empty_state_changes_with_provider_values() {
        let mut cache = CacheOptions::default();
        assert!(cache.is_empty());

        cache.openai = Some(OpenAIPromptCache::default());
        assert!(!cache.is_empty());
    }

    #[test]
    fn prompt_cache_retention_string_values_match_api() {
        assert_eq!(OpenAIPromptCacheRetention::InMemory.as_str(), "in-memory");
        assert_eq!(OpenAIPromptCacheRetention::Hours24.as_str(), "24h");
    }

    #[test]
    fn claude_prompt_cache_ttl_string_values_match_api() {
        assert_eq!(ClaudePromptCacheTtl::FiveMinutes.as_str(), "5m");
        assert_eq!(ClaudePromptCacheTtl::OneHour.as_str(), "1h");
    }

    #[test]
    fn claude_cache_default_strategy_is_automatic() {
        let cache = ClaudePromptCache::new(ClaudePromptCacheTtl::FiveMinutes);
        assert_eq!(cache.strategy, ClaudePromptCacheStrategy::Automatic);
    }

    #[test]
    fn claude_explicit_breakpoints_default_to_messages_only() {
        let breakpoints = ClaudeExplicitCacheBreakpoints::default();
        assert_eq!(breakpoints.count(), 1);
        assert_eq!(
            breakpoints.first.target,
            ClaudeCacheBreakpointTarget::LastMessage
        );
        assert!(breakpoints.second.is_none());
    }

    #[test]
    fn claude_prompt_cache_explicit_builder_preserves_breakpoints() {
        let breakpoints = ClaudeExplicitCacheBreakpoints::all();
        let params = Parameters::default()
            .claude_prompt_cache_explicit(ClaudePromptCacheTtl::OneHour, breakpoints);
        let cache = params
            .cache
            .claude
            .expect("claude cache should be set by explicit builder");
        assert_eq!(cache.ttl, ClaudePromptCacheTtl::OneHour);
        assert_eq!(
            cache.strategy,
            ClaudePromptCacheStrategy::Explicit(breakpoints)
        );
    }

    #[test]
    fn claude_explicit_breakpoint_supports_per_block_ttl_override() {
        let breakpoint = ClaudeExplicitCacheBreakpoint::new(ClaudeCacheBreakpointTarget::Tool(0))
            .with_ttl(ClaudePromptCacheTtl::OneHour);
        assert_eq!(breakpoint.ttl, Some(ClaudePromptCacheTtl::OneHour));
        assert_eq!(
            breakpoint.effective_ttl(ClaudePromptCacheTtl::FiveMinutes),
            ClaudePromptCacheTtl::OneHour
        );
    }

    #[test]
    fn claude_prompt_cache_automatic_with_explicit_builder_preserves_breakpoints() {
        let breakpoints = ClaudeExplicitCacheBreakpoints::messages_only();
        let params = Parameters::default().claude_prompt_cache_automatic_with_explicit(
            ClaudePromptCacheTtl::FiveMinutes,
            breakpoints,
        );
        let cache = params
            .cache
            .claude
            .expect("claude cache should be set by combined builder");
        assert_eq!(
            cache.strategy,
            ClaudePromptCacheStrategy::AutomaticAndExplicit(breakpoints)
        );
    }
}