rstructor 0.2.10

Rust equivalent of Python's Instructor + Pydantic: Extract structured, validated data from LLMs (OpenAI, Anthropic, Grok, Gemini) using type-safe Rust structs and enums
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
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
use crate::backend::{
    ChatMessage, MaterializeInternalOutput, TokenUsage, ValidationFailureContext,
};
use crate::error::{ApiErrorKind, RStructorError, Result};
use crate::model::Instructor;
use reqwest::Response;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::time::Duration;
use tokio::time::sleep;
use tracing::{debug, error, info, trace, warn};

/// Prepare a JSON schema for strict mode by recursively adding required fields
/// to all object types in the schema.
///
/// This is required by providers like OpenAI that use strict structured outputs, where
/// every object in the schema (including nested objects and array items) must have:
/// 1. `additionalProperties: false`
/// 2. A `required` array listing all property keys
///
/// # Arguments
///
/// * `schema` - The JSON schema to modify
///
/// # Returns
///
/// A new schema Value with strict mode requirements added to all objects
pub fn prepare_strict_schema(schema: &crate::schema::Schema) -> Value {
    let mut schema_json = schema.to_json();
    add_additional_properties_false(&mut schema_json);
    schema_json
}

/// Recursively prepares a JSON schema for strict mode by adding:
/// 1. `additionalProperties: false` to all object types
/// 2. `required` array with all property keys (if not already present)
fn add_additional_properties_false(schema: &mut Value) {
    if let Some(obj) = schema.as_object_mut() {
        // Check if this is an object type schema
        let is_object_type = obj
            .get("type")
            .and_then(|t| t.as_str())
            .is_some_and(|t| t == "object");

        // Also check if it has properties (even without explicit type: object)
        let has_properties = obj.contains_key("properties");

        if is_object_type || has_properties {
            obj.insert("additionalProperties".to_string(), serde_json::json!(false));

            // OpenAI strict mode requires ALL properties to be listed in `required`
            // This overrides any existing `required` array since the derive macro
            // only includes non-optional fields, but strict mode needs all of them
            if let Some(properties) = obj.get("properties")
                && let Some(props_obj) = properties.as_object()
            {
                let required_keys: Vec<Value> =
                    props_obj.keys().map(|k| serde_json::json!(k)).collect();
                if !required_keys.is_empty() {
                    obj.insert("required".to_string(), Value::Array(required_keys));
                }
            }
        }

        // Recursively process nested schemas
        // Process 'properties' object
        if let Some(properties) = obj.get_mut("properties")
            && let Some(props_obj) = properties.as_object_mut()
        {
            for (_key, prop_schema) in props_obj.iter_mut() {
                add_additional_properties_false(prop_schema);
            }
        }

        // Process 'items' for arrays
        if let Some(items) = obj.get_mut("items") {
            add_additional_properties_false(items);
        }

        // Process 'additionalItems' for arrays
        if let Some(additional_items) = obj.get_mut("additionalItems") {
            add_additional_properties_false(additional_items);
        }

        // Process 'allOf' array
        if let Some(all_of) = obj.get_mut("allOf")
            && let Some(arr) = all_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                add_additional_properties_false(item);
            }
        }

        // Process 'anyOf' array
        if let Some(any_of) = obj.get_mut("anyOf")
            && let Some(arr) = any_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                add_additional_properties_false(item);
            }
        }

        // Process 'oneOf' array
        if let Some(one_of) = obj.get_mut("oneOf")
            && let Some(arr) = one_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                add_additional_properties_false(item);
            }
        }

        // Process 'definitions' / '$defs' for reusable schemas
        if let Some(definitions) = obj.get_mut("definitions")
            && let Some(defs_obj) = definitions.as_object_mut()
        {
            for (_key, def_schema) in defs_obj.iter_mut() {
                add_additional_properties_false(def_schema);
            }
        }

        if let Some(defs) = obj.get_mut("$defs")
            && let Some(defs_obj) = defs.as_object_mut()
        {
            for (_key, def_schema) in defs_obj.iter_mut() {
                add_additional_properties_false(def_schema);
            }
        }

        // Process 'not' schema
        if let Some(not_schema) = obj.get_mut("not") {
            add_additional_properties_false(not_schema);
        }

        // Process 'if', 'then', 'else' schemas
        if let Some(if_schema) = obj.get_mut("if") {
            add_additional_properties_false(if_schema);
        }
        if let Some(then_schema) = obj.get_mut("then") {
            add_additional_properties_false(then_schema);
        }
        if let Some(else_schema) = obj.get_mut("else") {
            add_additional_properties_false(else_schema);
        }

        // Process 'patternProperties' object
        if let Some(pattern_props) = obj.get_mut("patternProperties")
            && let Some(pattern_obj) = pattern_props.as_object_mut()
        {
            for (_pattern, pattern_schema) in pattern_obj.iter_mut() {
                add_additional_properties_false(pattern_schema);
            }
        }

        // Process 'contains' for arrays
        if let Some(contains) = obj.get_mut("contains") {
            add_additional_properties_false(contains);
        }

        // Process 'propertyNames' schema
        if let Some(property_names) = obj.get_mut("propertyNames") {
            add_additional_properties_false(property_names);
        }
    }
}

/// Information about adjacently tagged enum transformations for response conversion
#[derive(Debug, Clone)]
pub struct AdjacentlyTaggedEnumInfo {
    pub tag_key: String,
    pub content_key: String,
    pub tag_values: Vec<String>,
}

/// Extract adjacently tagged enum info from a schema (before Gemini transformation)
/// Searches recursively through the schema tree
pub fn extract_adjacently_tagged_info(schema: &Value) -> Option<AdjacentlyTaggedEnumInfo> {
    // First check if this level has enum disjunction variants
    for key in ["oneOf", "anyOf"] {
        if let Some(variants) = schema.get(key).and_then(|v| v.as_array())
            && let Some(info) = extract_adjacently_tagged_info_from_variants(variants)
        {
            return Some(info);
        }
    }

    // Recursively search in properties
    if let Some(properties) = schema.get("properties").and_then(|p| p.as_object()) {
        for (_key, prop_schema) in properties {
            if let Some(info) = extract_adjacently_tagged_info(prop_schema) {
                return Some(info);
            }
        }
    }

    // Recursively search in array items
    if let Some(items) = schema.get("items")
        && let Some(info) = extract_adjacently_tagged_info(items)
    {
        return Some(info);
    }

    // Search in allOf, anyOf, oneOf
    for key in &["allOf", "anyOf", "oneOf"] {
        if let Some(arr) = schema.get(key).and_then(|v| v.as_array()) {
            for item in arr {
                if let Some(info) = extract_adjacently_tagged_info(item) {
                    return Some(info);
                }
            }
        }
    }

    None
}

fn extract_adjacently_tagged_info_from_variants(
    variants: &[Value],
) -> Option<AdjacentlyTaggedEnumInfo> {
    let mut tag_key = None;
    let mut content_key = None;
    let mut tag_values = Vec::new();

    for variant in variants {
        if let Some((t, c, v)) = detect_adjacently_tagged_variant(variant) {
            if tag_key.is_none() {
                tag_key = Some(t);
                content_key = Some(c);
            }
            tag_values.push(v);
        }
    }

    if let (Some(tag), Some(content)) = (tag_key, content_key) {
        Some(AdjacentlyTaggedEnumInfo {
            tag_key: tag,
            content_key: content,
            tag_values,
        })
    } else {
        None
    }
}

/// Transform internally tagged JSON back to adjacently tagged format
pub fn transform_internally_to_adjacently_tagged(
    json: &mut Value,
    enum_info: &AdjacentlyTaggedEnumInfo,
) {
    match json {
        Value::Object(obj) => {
            // Check if this object is an internally tagged enum instance
            if let Some(tag_value) = obj.get(&enum_info.tag_key).and_then(|v| v.as_str())
                && enum_info.tag_values.contains(&tag_value.to_string())
            {
                // This is an enum instance - extract all fields except the tag
                let mut content_fields = serde_json::Map::new();
                let mut keys_to_move: Vec<String> = Vec::new();

                for (key, _value) in obj.iter() {
                    if key != &enum_info.tag_key {
                        keys_to_move.push(key.clone());
                    }
                }

                // Move fields to content (unless it's a unit variant with only tag)
                if !keys_to_move.is_empty() {
                    for key in &keys_to_move {
                        if let Some(value) = obj.remove(key) {
                            content_fields.insert(key.clone(), value);
                        }
                    }

                    // Add content field
                    obj.insert(enum_info.content_key.clone(), Value::Object(content_fields));
                }
                // For unit variants (only tag), don't add content field
                return;
            }

            // Recursively process nested objects and arrays
            for value in obj.values_mut() {
                transform_internally_to_adjacently_tagged(value, enum_info);
            }
        }
        Value::Array(arr) => {
            for item in arr.iter_mut() {
                transform_internally_to_adjacently_tagged(item, enum_info);
            }
        }
        _ => {}
    }
}

/// Prepare a JSON schema for Gemini by stripping unsupported keywords.
///
/// Gemini's structured outputs API doesn't support certain JSON Schema keywords like
/// `examples`, `additionalProperties`, `title`, etc. This function recursively removes
/// them from the schema.
///
/// # Arguments
///
/// * `schema` - The JSON schema to modify
///
/// # Returns
///
/// A new schema Value with unsupported keywords removed
pub fn prepare_gemini_schema(schema: &crate::schema::Schema) -> Value {
    let mut schema_json = schema.to_json();
    strip_gemini_unsupported_keywords(&mut schema_json);
    schema_json
}

/// Recursively removes keywords unsupported by Gemini's structured outputs.
fn strip_gemini_unsupported_keywords(schema: &mut Value) {
    // First, resolve any $ref references by inlining definitions
    resolve_refs_for_gemini(schema);

    strip_gemini_unsupported_keywords_recursive(schema);
}

/// Resolves $ref references by inlining definitions for Gemini compatibility.
/// This handles recursive schemas by inlining to a limited depth.
fn resolve_refs_for_gemini(schema: &mut Value) {
    // Extract $defs if present
    let defs = if let Some(obj) = schema.as_object_mut() {
        obj.remove("$defs").or_else(|| obj.remove("definitions"))
    } else {
        None
    };

    if let Some(defs) = defs {
        // If schema has $ref at root, replace with the referenced definition
        if let Some(obj) = schema.as_object_mut()
            && let Some(ref_value) = obj.remove("$ref")
            && let Some(ref_str) = ref_value.as_str()
            && let Some(def_name) = ref_str
                .strip_prefix("#/$defs/")
                .or_else(|| ref_str.strip_prefix("#/definitions/"))
            && let Some(defs_obj) = defs.as_object()
            && let Some(definition) = defs_obj.get(def_name)
        {
            // Replace schema with the definition
            *schema = definition.clone();

            // Recursively inline refs in the new schema (with depth limit)
            inline_refs_recursive(schema, &defs, 3);
        }
    }
}

/// Recursively inlines $ref references with a depth limit to prevent infinite recursion.
fn inline_refs_recursive(schema: &mut Value, defs: &Value, depth: usize) {
    if depth == 0 {
        // At max depth, replace self-references with a simple object schema
        if let Some(obj) = schema.as_object_mut()
            && obj.contains_key("$ref")
        {
            obj.remove("$ref");
            obj.insert("type".to_string(), Value::String("object".to_string()));
            obj.insert(
                "description".to_string(),
                Value::String("Recursive reference (depth limit reached)".to_string()),
            );
        }
        return;
    }

    if let Some(obj) = schema.as_object_mut() {
        // Replace $ref with inline definition
        if let Some(ref_value) = obj.remove("$ref")
            && let Some(ref_str) = ref_value.as_str()
            && let Some(def_name) = ref_str
                .strip_prefix("#/$defs/")
                .or_else(|| ref_str.strip_prefix("#/definitions/"))
            && let Some(defs_obj) = defs.as_object()
            && let Some(definition) = defs_obj.get(def_name)
        {
            // Replace with inline definition
            *schema = definition.clone();
            // Continue recursively with reduced depth
            inline_refs_recursive(schema, defs, depth - 1);
            return;
        }

        // Process nested schemas
        if let Some(properties) = obj.get_mut("properties")
            && let Some(props_obj) = properties.as_object_mut()
        {
            for prop_schema in props_obj.values_mut() {
                inline_refs_recursive(prop_schema, defs, depth);
            }
        }

        if let Some(items) = obj.get_mut("items") {
            inline_refs_recursive(items, defs, depth);
        }

        if let Some(prefix_items) = obj.get_mut("prefixItems")
            && let Some(arr) = prefix_items.as_array_mut()
        {
            for item in arr.iter_mut() {
                inline_refs_recursive(item, defs, depth);
            }
        }

        if let Some(one_of) = obj.get_mut("oneOf")
            && let Some(arr) = one_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                inline_refs_recursive(item, defs, depth);
            }
        }

        if let Some(any_of) = obj.get_mut("anyOf")
            && let Some(arr) = any_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                inline_refs_recursive(item, defs, depth);
            }
        }

        if let Some(all_of) = obj.get_mut("allOf")
            && let Some(arr) = all_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                inline_refs_recursive(item, defs, depth);
            }
        }

        // Handle additionalProperties if it's a schema object (for maps)
        if let Some(additional) = obj.get_mut("additionalProperties")
            && additional.is_object()
        {
            inline_refs_recursive(additional, defs, depth);
        }
    }
}

/// Detects if a oneOf variant looks like an adjacently tagged enum variant.
/// Returns Some((tag_key, content_key, tag_value)) if it matches the pattern.
fn detect_adjacently_tagged_variant(variant: &Value) -> Option<(String, String, String)> {
    let obj = variant.as_object()?;

    // Must be an object type
    if obj.get("type")?.as_str()? != "object" {
        return None;
    }

    let properties = obj.get("properties")?.as_object()?;
    let required = obj.get("required")?.as_array()?;

    // Must have exactly 2 required fields
    if required.len() != 2 {
        return None;
    }

    // Find the tag field (has enum with single value) and content field (is object)
    let mut tag_key = None;
    let mut tag_value = None;
    let mut content_key = None;

    for (key, prop) in properties.iter() {
        if let Some(prop_obj) = prop.as_object() {
            // Check if it's a tag field (has enum with single value)
            if let Some(enum_array) = prop_obj.get("enum").and_then(|e| e.as_array())
                && enum_array.len() == 1
                && let Some(val) = enum_array[0].as_str()
            {
                tag_key = Some(key.clone());
                tag_value = Some(val.to_string());
                continue;
            }

            // Check if it's a content field (is object type)
            if prop_obj.get("type").and_then(|t| t.as_str()) == Some("object")
                && prop_obj.contains_key("properties")
            {
                content_key = Some(key.clone());
            }
        }
    }

    // Must have found both tag and content
    if let (Some(tag), Some(content), Some(value)) = (tag_key, content_key, tag_value) {
        Some((tag, content, value))
    } else {
        None
    }
}

/// Transforms adjacently tagged enum variants to internally tagged format for Gemini.
/// This is a workaround for Gemini's limitation with nested content objects.
fn transform_adjacently_tagged_to_internally_tagged(
    variant: &Value,
    _tag_key: &str,
    content_key: &str,
    _tag_value: &str,
) -> Value {
    let mut obj = variant.as_object().unwrap().clone();

    // Clone content properties and required fields before modifying
    let content_props_to_add: Vec<(String, Value)>;
    let content_required: Vec<Value>;

    {
        let properties = obj.get("properties").unwrap().as_object().unwrap();

        // Get the content object properties
        if let Some(content_obj) = properties.get(content_key).and_then(|c| c.as_object()) {
            if let Some(content_props) = content_obj.get("properties").and_then(|p| p.as_object()) {
                // Collect properties to add
                content_props_to_add = content_props
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect();
            } else {
                content_props_to_add = Vec::new();
            }

            // Collect required fields
            if let Some(req) = content_obj.get("required").and_then(|r| r.as_array()) {
                content_required = req.clone();
            } else {
                content_required = Vec::new();
            }
        } else {
            content_props_to_add = Vec::new();
            content_required = Vec::new();
        }
    }

    // Now modify properties
    if let Some(properties) = obj.get_mut("properties").and_then(|p| p.as_object_mut()) {
        // Add flattened properties
        for (key, value) in content_props_to_add {
            properties.insert(key, value);
        }

        // Remove the content field itself
        properties.remove(content_key);
    }

    // Update required array
    if let Some(required_array) = obj.get_mut("required").and_then(|r| r.as_array_mut()) {
        // Remove content_key from required
        required_array.retain(|v| v.as_str() != Some(content_key));

        // Add content's required fields
        for field in content_required {
            if !required_array.contains(&field) {
                required_array.push(field);
            }
        }
    }

    // Update description to note the transformation
    if let Some(desc) = obj.get("description").and_then(|d| d.as_str()) {
        let new_desc = format!("{} (flattened for Gemini compatibility)", desc);
        obj.insert("description".to_string(), Value::String(new_desc));
    }

    Value::Object(obj)
}

fn normalize_adjacently_tagged_variants(variants: &mut Vec<Value>) {
    // First, check if this looks like an adjacently tagged enum.
    // All variants should have the same tag/content keys.
    let mut adjacently_tagged_info: Option<(String, String)> = None;
    let mut all_adjacently_tagged = true;

    for variant in variants.iter() {
        if let Some((tag_key, content_key, _tag_value)) = detect_adjacently_tagged_variant(variant)
        {
            if let Some((ref existing_tag, ref existing_content)) = adjacently_tagged_info {
                if tag_key != *existing_tag || content_key != *existing_content {
                    all_adjacently_tagged = false;
                    break;
                }
            } else {
                adjacently_tagged_info = Some((tag_key, content_key));
            }
        } else {
            // Unit variant (only tag, no content) is still okay.
            if let Some(variant_obj) = variant.as_object()
                && let Some(props) = variant_obj.get("properties").and_then(|p| p.as_object())
                && props.len() == 1
                && variant_obj
                    .get("required")
                    .and_then(|r| r.as_array())
                    .map(|a| a.len())
                    == Some(1)
            {
                continue;
            }
            all_adjacently_tagged = false;
            break;
        }
    }

    if all_adjacently_tagged && adjacently_tagged_info.is_some() {
        *variants = variants
            .iter()
            .map(|variant| {
                if let Some((t, c, v)) = detect_adjacently_tagged_variant(variant) {
                    transform_adjacently_tagged_to_internally_tagged(variant, &t, &c, &v)
                } else {
                    variant.clone()
                }
            })
            .collect();
    }
}

/// Internal function that strips unsupported keywords after refs are resolved.
fn strip_gemini_unsupported_keywords_recursive(schema: &mut Value) {
    if let Some(obj) = schema.as_object_mut() {
        // Remove unsupported keywords
        obj.remove("examples");
        obj.remove("title");
        obj.remove("$schema");
        obj.remove("$id");
        obj.remove("default");
        obj.remove("$defs");
        obj.remove("definitions");
        obj.remove("$ref"); // Should be resolved by now, but remove if any remain

        // Handle additionalProperties: remove if boolean, keep if it's a schema for maps
        if let Some(additional) = obj.get("additionalProperties")
            && additional.is_boolean()
        {
            obj.remove("additionalProperties");
        }

        // For object types with additionalProperties but no properties, this is a Map type
        // Gemini requires properties to be non-empty for object types
        // Since Gemini doesn't support map types natively, we remove type constraint
        // and add a description. The response won't be strictly validated but should
        // parse correctly.
        let is_object = obj.get("type").and_then(|t| t.as_str()) == Some("object");
        let has_properties = obj.contains_key("properties");
        let has_additional_props = obj.contains_key("additionalProperties");

        if is_object && !has_properties && has_additional_props {
            // This is a map type - Gemini doesn't support this natively
            // We need to generate a workaround schema that Gemini can understand
            let additional = obj.remove("additionalProperties");

            // Get existing description if any
            let existing_desc = obj
                .get("description")
                .and_then(|d| d.as_str())
                .map(|s| s.to_string())
                .unwrap_or_default();

            // For Gemini, we'll define a few placeholder property keys that represent
            // the expected dynamic key structure. This is a workaround since Gemini
            // requires properties to be defined.
            let value_schema = additional.unwrap_or(serde_json::json!({}));

            // Try to extract specific keys from x-enum-keys extension field first,
            // then fall back to parsing the description string for backward compatibility
            let mut keys = vec!["key1".to_string(), "key2".to_string(), "key3".to_string()];
            if let Some(enum_keys) = obj.remove("x-enum-keys")
                && let Some(arr) = enum_keys.as_array()
            {
                let extracted_keys: Vec<String> = arr
                    .iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect();
                if !extracted_keys.is_empty() {
                    keys = extracted_keys;
                }
            } else if let Some(start) = existing_desc.find("Keys: [")
                && let Some(end) = existing_desc[start..].find(']')
            {
                let keys_str = &existing_desc[start + 7..start + end];
                let extracted_keys: Vec<String> = keys_str
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                if !extracted_keys.is_empty() {
                    keys = extracted_keys;
                }
            }

            // Create placeholder properties with the value schema
            // Using extracted keys if available, otherwise generic key names
            let mut placeholder_props = serde_json::Map::new();
            for key in &keys {
                placeholder_props.insert(key.clone(), value_schema.clone());
            }

            obj.insert("properties".to_string(), Value::Object(placeholder_props));

            // Update description to explain this is a map with specific or example keys
            let map_desc = if existing_desc.contains("Keys: [") {
                // If keys were specified, keep the original description as-is
                existing_desc
            } else if existing_desc.is_empty() {
                format!(
                    "Object with any string keys ({} are examples - use actual meaningful key names)",
                    keys.join(", ")
                )
            } else {
                format!(
                    "{} ({} are example keys - use actual meaningful key names)",
                    existing_desc,
                    keys.join(", ")
                )
            };
            obj.insert("description".to_string(), Value::String(map_desc));
        }

        // Strip x-enum-keys extension (consumed above for maps, not needed in final schema)
        obj.remove("x-enum-keys");

        // Recursively process nested schemas
        if let Some(properties) = obj.get_mut("properties")
            && let Some(props_obj) = properties.as_object_mut()
        {
            for prop_schema in props_obj.values_mut() {
                strip_gemini_unsupported_keywords_recursive(prop_schema);
            }
        }

        // Process 'items' for arrays
        if let Some(items) = obj.get_mut("items") {
            strip_gemini_unsupported_keywords_recursive(items);
        }

        // Handle tuples (prefixItems) - Gemini doesn't support prefixItems
        // Convert to a regular array with oneOf for the item types
        if let Some(prefix_items) = obj.remove("prefixItems")
            && let Some(arr) = prefix_items.as_array()
        {
            // Recursively process each item schema
            let mut processed_items: Vec<Value> = arr
                .iter()
                .map(|item| {
                    let mut item_clone = item.clone();
                    strip_gemini_unsupported_keywords_recursive(&mut item_clone);
                    item_clone
                })
                .collect();

            // Remove duplicates for cleaner schema
            processed_items.dedup();

            // If all items are the same type, use single items schema
            if processed_items.len() == 1 {
                obj.insert(
                    "items".to_string(),
                    processed_items.into_iter().next().unwrap(),
                );
            } else {
                // Use anyOf for mixed types
                obj.insert(
                    "items".to_string(),
                    serde_json::json!({
                        "anyOf": processed_items
                    }),
                );
            }

            // Remove minItems/maxItems since they're not strictly enforced without prefixItems
            obj.remove("minItems");
            obj.remove("maxItems");

            // Add description about tuple structure
            let existing_desc = obj
                .get("description")
                .and_then(|d| d.as_str())
                .map(|s| format!("{}. ", s))
                .unwrap_or_default();
            let tuple_len = arr.len();
            obj.insert(
                "description".to_string(),
                Value::String(format!(
                    "{}Fixed-length array (tuple) with {} elements",
                    existing_desc, tuple_len
                )),
            );
        }

        // Process 'allOf' array
        if let Some(all_of) = obj.get_mut("allOf")
            && let Some(arr) = all_of.as_array_mut()
        {
            for item in arr.iter_mut() {
                strip_gemini_unsupported_keywords_recursive(item);
            }
        }

        // Process enum disjunction arrays and normalize adjacently tagged variants.
        for key in ["anyOf", "oneOf"] {
            if let Some(disjunction) = obj.get_mut(key)
                && let Some(variants) = disjunction.as_array_mut()
            {
                normalize_adjacently_tagged_variants(variants);
                for variant in variants.iter_mut() {
                    strip_gemini_unsupported_keywords_recursive(variant);
                }
            }
        }

        // Handle additionalProperties if it's a schema object (for maps) - recurse into it
        if let Some(additional) = obj.get_mut("additionalProperties")
            && additional.is_object()
        {
            strip_gemini_unsupported_keywords_recursive(additional);
        }
    }
}

/// JSON Schema format specification for structured outputs.
///
/// This struct is used by OpenAI and Grok (and potentially other OpenAI-compatible APIs)
/// for their native structured outputs feature.
#[derive(Debug, Serialize)]
pub struct JsonSchemaFormat {
    /// Name of the schema (usually the type name)
    pub name: String,
    /// Optional description of the schema
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The JSON schema itself
    pub schema: Value,
    /// Whether to use strict mode (required for structured outputs)
    pub strict: bool,
}

/// Response format for structured outputs (OpenAI-compatible).
#[derive(Debug, Serialize)]
#[serde(tag = "type")]
pub enum ResponseFormat {
    /// JSON Schema structured output format
    #[serde(rename = "json_schema")]
    JsonSchema {
        /// The JSON schema specification
        json_schema: JsonSchemaFormat,
    },
}

impl ResponseFormat {
    /// Create a new JSON schema response format for structured outputs.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the schema (usually the type name)
    /// * `schema` - The JSON schema for the expected output
    /// * `description` - Optional description of what the output should contain
    pub fn json_schema(name: String, schema: Value, description: Option<String>) -> Self {
        ResponseFormat::JsonSchema {
            json_schema: JsonSchemaFormat {
                name,
                description,
                schema,
                strict: true,
            },
        }
    }
}

/// Parse a raw JSON response and validate it against the Instructor trait.
///
/// This function handles:
/// 1. JSON parsing with detailed error messages
/// 2. Custom validation via the Instructor trait
///
/// # Arguments
///
/// * `raw_response` - The raw JSON string from the LLM
///
/// # Returns
///
/// The parsed and validated data, or an error with validation context
pub fn parse_and_validate_response<T>(
    raw_response: &str,
) -> std::result::Result<T, (RStructorError, Option<ValidationFailureContext>)>
where
    T: Instructor + DeserializeOwned,
{
    // Parse the JSON content into our target type
    let result: T = match serde_json::from_str(raw_response) {
        Ok(parsed) => parsed,
        Err(e) => {
            let error_msg = format!(
                "Failed to parse response as JSON: {}\nPartial JSON: {}",
                e, raw_response
            );
            error!(
                error = %e,
                content = %raw_response,
                "JSON parsing error"
            );
            return Err((
                RStructorError::ValidationError(error_msg.clone()),
                Some(ValidationFailureContext::new(
                    error_msg,
                    raw_response.to_string(),
                )),
            ));
        }
    };

    // Apply any custom validation (business logic beyond schema)
    if let Err(e) = result.validate() {
        error!(error = ?e, "Custom validation failed");
        let error_msg = e.to_string();
        return Err((
            e,
            Some(ValidationFailureContext::new(
                error_msg,
                raw_response.to_string(),
            )),
        ));
    }

    Ok(result)
}

/// Helper to create a successful MaterializeInternalOutput from parsed data.
///
/// This is a convenience function that combines parsing, validation, and
/// output construction in one step.
///
/// # Arguments
///
/// * `raw_response` - The raw JSON string from the LLM
/// * `usage` - Optional token usage information
///
/// # Returns
///
/// A MaterializeInternalOutput with the parsed data, or an error
pub fn parse_validate_and_create_output<T>(
    raw_response: String,
    usage: Option<TokenUsage>,
) -> std::result::Result<
    MaterializeInternalOutput<T>,
    (RStructorError, Option<ValidationFailureContext>),
>
where
    T: Instructor + DeserializeOwned,
{
    let result = parse_and_validate_response::<T>(&raw_response)?;
    info!("Successfully generated and validated structured data");
    Ok(MaterializeInternalOutput::new(result, raw_response, usage))
}

/// Convert a reqwest error to a RStructorError, handling timeout errors specially.
pub fn handle_http_error(e: reqwest::Error, provider_name: &str) -> RStructorError {
    error!(error = %e, "HTTP request to {} failed", provider_name);
    if e.is_timeout() {
        RStructorError::Timeout
    } else {
        RStructorError::HttpError(e)
    }
}

/// Parse retry-after header value to Duration.
fn parse_retry_after(value: &str) -> Option<Duration> {
    // Try parsing as seconds (most common)
    if let Ok(secs) = value.parse::<u64>() {
        return Some(Duration::from_secs(secs));
    }
    // Could also parse HTTP-date format, but seconds is most common
    None
}

/// Classify an API error based on HTTP status code and response body.
fn classify_api_error(
    status: reqwest::StatusCode,
    error_text: &str,
    retry_after: Option<Duration>,
    model_hint: Option<&str>,
) -> ApiErrorKind {
    let code = status.as_u16();
    let error_lower = error_text.to_lowercase();

    match code {
        // Authentication errors
        401 => ApiErrorKind::AuthenticationFailed,

        // Permission errors
        403 => ApiErrorKind::PermissionDenied,

        // Not found - check if it's a model error
        404 => {
            // Check if the error message mentions "model"
            if error_lower.contains("model") {
                let model = model_hint
                    .map(|s| s.to_string())
                    .or_else(|| extract_model_from_error(&error_lower))
                    .unwrap_or_else(|| "unknown".to_string());
                ApiErrorKind::InvalidModel {
                    model,
                    suggestion: suggest_model(&error_lower),
                }
            } else {
                ApiErrorKind::Other {
                    code,
                    message: error_text.to_string(),
                }
            }
        }

        // Bad request
        400 => ApiErrorKind::BadRequest {
            details: truncate_message(error_text, 200),
        },

        // Payload too large
        413 => ApiErrorKind::RequestTooLarge,

        // Rate limited
        429 => ApiErrorKind::RateLimited { retry_after },

        // Server errors
        500 | 502 => ApiErrorKind::ServerError { code },

        // Service unavailable
        503 => ApiErrorKind::ServiceUnavailable,

        // Gateway/Cloudflare errors
        520..=524 => ApiErrorKind::GatewayError { code },

        // Other errors
        _ => ApiErrorKind::Other {
            code,
            message: truncate_message(error_text, 500),
        },
    }
}

/// Extract model name from error message if present.
fn extract_model_from_error(error_text: &str) -> Option<String> {
    // Look for quoted model names like 'gpt-4' or "gpt-4"
    for quote in ['\'', '"'] {
        if let Some(start) = error_text.find(quote) {
            let rest = &error_text[start + 1..];
            if let Some(end) = rest.find(quote) {
                let candidate = &rest[..end];
                // Model names typically have alphanumeric chars, dots, or dashes
                if candidate.len() > 2
                    && candidate
                        .chars()
                        .all(|c| c.is_alphanumeric() || c == '-' || c == '.' || c == '_')
                {
                    return Some(candidate.to_string());
                }
            }
        }
    }
    None
}

/// Suggest an alternative model based on error context.
fn suggest_model(error_text: &str) -> Option<String> {
    // Common model name patterns and their suggestions
    if error_text.contains("gpt") {
        Some("gpt-5.5".to_string())
    } else if error_text.contains("claude") || error_text.contains("sonnet") {
        Some("claude-sonnet-4-6".to_string())
    } else if error_text.contains("gemini") {
        Some("gemini-3.1-pro-preview".to_string())
    } else {
        None
    }
}

/// Truncate a message to a maximum length.
///
/// Uses `floor_char_boundary` to ensure we don't slice in the middle of a
/// multi-byte UTF-8 character, which would cause a panic.
fn truncate_message(msg: &str, max_len: usize) -> String {
    if msg.len() <= max_len {
        msg.to_string()
    } else {
        // Find a valid UTF-8 character boundary at or before max_len
        let boundary = msg.floor_char_boundary(max_len);
        format!("{}...", &msg[..boundary])
    }
}

/// Check HTTP response status and extract error message if unsuccessful.
///
/// This function classifies errors into actionable types (rate limit, auth failure, etc.)
/// and provides user-friendly error messages with suggested actions.
pub async fn check_response_status(response: Response, provider_name: &str) -> Result<Response> {
    if !response.status().is_success() {
        let status = response.status();

        // Extract retry-after header if present
        let retry_after = response
            .headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok())
            .and_then(parse_retry_after);

        let error_text = response.text().await?;

        let kind = classify_api_error(status, &error_text, retry_after, None);

        error!(
            status = %status,
            error = %error_text,
            kind = %kind,
            "{} API returned error response", provider_name
        );

        return Err(RStructorError::api_error(provider_name, kind));
    }
    Ok(response)
}

/// Helper function to execute generation with retry logic using conversation history.
///
/// This function maintains a conversation history across retry attempts, which enables:
/// - **Prompt caching**: Providers like Anthropic and OpenAI can cache the prefix of the
///   conversation, reducing token costs and latency on retries.
/// - **Better error correction**: The model sees its previous (failed) response and the
///   specific error, making it more likely to produce a correct response.
///
/// # How it works
///
/// 1. On first attempt: Sends `[User(prompt)]`
/// 2. On validation failure: Appends `[Assistant(failed_response), User(error_feedback)]`
/// 3. On retry: Sends the full conversation history
///
/// This approach preserves the original prompt exactly, maximizing cache hit rates.
///
/// # Arguments
///
/// * `generate_fn` - Function that takes a conversation history and returns the result plus raw response
/// * `prompt` - The initial user prompt
/// * `max_retries` - Maximum number of retry attempts (None or 0 means no retries)
pub async fn generate_with_retry_with_history<F, Fut, T>(
    generate_fn: F,
    prompt: &str,
    max_retries: Option<usize>,
) -> Result<MaterializeInternalOutput<T>>
where
    F: FnMut(Vec<ChatMessage>) -> Fut,
    Fut: std::future::Future<
            Output = std::result::Result<
                MaterializeInternalOutput<T>,
                (RStructorError, Option<ValidationFailureContext>),
            >,
        >,
{
    generate_with_retry_with_initial_messages(
        generate_fn,
        vec![ChatMessage::user(prompt)],
        max_retries,
    )
    .await
}

/// Helper function to execute generation with retry logic using a custom initial
/// conversation history.
///
/// This is primarily used for multimodal prompts where the initial user message
/// may contain attached media in addition to text.
pub async fn generate_with_retry_with_initial_messages<F, Fut, T>(
    mut generate_fn: F,
    initial_messages: Vec<ChatMessage>,
    max_retries: Option<usize>,
) -> Result<MaterializeInternalOutput<T>>
where
    F: FnMut(Vec<ChatMessage>) -> Fut,
    Fut: std::future::Future<
            Output = std::result::Result<
                MaterializeInternalOutput<T>,
                (RStructorError, Option<ValidationFailureContext>),
            >,
        >,
{
    let Some(max_retries) = max_retries.filter(|&n| n > 0) else {
        // No retries configured - just run once with the provided initial messages
        return generate_fn(initial_messages).await.map_err(|(err, _)| err);
    };

    let max_attempts = max_retries + 1; // +1 for initial attempt

    // Initialize conversation history with the provided starting messages.
    let mut messages = initial_messages;

    trace!(
        "Starting structured generation with conversation history: max_attempts={}",
        max_attempts
    );

    for attempt in 0..max_attempts {
        // Log attempt information
        info!(
            attempt = attempt + 1,
            total_attempts = max_attempts,
            history_len = messages.len(),
            "Generation attempt with conversation history"
        );

        // Attempt to generate structured data
        match generate_fn(messages.clone()).await {
            Ok(result) => {
                if attempt > 0 {
                    info!(
                        attempts_used = attempt + 1,
                        "Successfully generated after {} retries (with conversation history)",
                        attempt
                    );
                } else {
                    debug!("Successfully generated on first attempt");
                }
                return Ok(result);
            }
            Err((err, validation_ctx)) => {
                let is_last_attempt = attempt >= max_attempts - 1;

                // Handle validation errors with conversation history
                if let RStructorError::ValidationError(ref msg) = err {
                    if !is_last_attempt {
                        warn!(
                            attempt = attempt + 1,
                            error = msg,
                            "Validation error in generation attempt"
                        );

                        // Build conversation history for retry with error feedback
                        if let Some(ctx) = validation_ctx {
                            // Add the failed assistant response to history
                            messages.push(ChatMessage::assistant(&ctx.raw_response));

                            // Add user message with error feedback
                            let error_feedback = format!(
                                "Your previous response contained validation errors. Please provide a complete, valid JSON response that includes ALL required fields and follows the schema exactly.\n\nError details:\n{}\n\nPlease fix the issues in your response. Make sure to:\n1. Include ALL required fields exactly as specified in the schema\n2. For enum fields, use EXACTLY one of the allowed values from the description\n3. CRITICAL: For arrays where items.type = 'object':\n   - You MUST provide an array of OBJECTS, not strings or primitive values\n   - Each object must be a complete JSON object with all its required fields\n   - Include multiple items (at least 2-3) in arrays of objects\n4. Verify all nested objects have their complete structure\n5. Follow ALL type specifications (string, number, boolean, array, object)",
                                ctx.error_message
                            );
                            messages.push(ChatMessage::user(error_feedback));

                            debug!(
                                history_len = messages.len(),
                                "Updated conversation history for retry"
                            );
                        } else {
                            // Fallback: no raw response context available.
                            // We cannot add error feedback without the raw response because:
                            // 1. Adding only a user message would create consecutive user messages,
                            //    violating the alternating user/assistant pattern expected by LLM APIs
                            // 2. The error message references "your previous response" but we can't show it
                            // Instead, we retry with the original conversation (no history modification)
                            warn!(
                                "Validation error occurred but no raw response context available. \
                                 Retrying without error feedback in conversation history."
                            );
                        }

                        // Wait briefly before retrying
                        sleep(Duration::from_millis(500)).await;
                        continue;
                    } else {
                        error!(
                            attempts = max_attempts,
                            error = msg,
                            "Failed after maximum retry attempts with validation errors"
                        );
                    }
                }
                // Handle retryable API errors (rate limits, transient failures)
                else if err.is_retryable() && !is_last_attempt {
                    let delay = err.retry_delay().unwrap_or(Duration::from_secs(1));
                    warn!(
                        attempt = attempt + 1,
                        error = ?err,
                        delay_ms = delay.as_millis(),
                        "Retryable API error, waiting before retry"
                    );
                    // For API errors, we don't modify the conversation history
                    // Just retry with the same messages
                    sleep(delay).await;
                    continue;
                }
                // Non-retryable errors or last attempt
                else if is_last_attempt {
                    error!(
                        attempts = max_attempts,
                        error = ?err,
                        "Failed after maximum retry attempts"
                    );
                } else {
                    error!(
                        error = ?err,
                        "Non-retryable error occurred during generation"
                    );
                }

                return Err(err);
            }
        }
    }

    // This should never be reached due to the returns in the loop
    unreachable!()
}

/// Helper for provider implementations of `materialize_with_media`.
///
/// Builds an initial media-bearing user message and runs the shared retry/history flow.
pub async fn materialize_with_media_with_retry<F, Fut, T>(
    generate_fn: F,
    prompt: &str,
    media: &[crate::backend::client::MediaFile],
    max_retries: Option<usize>,
) -> Result<T>
where
    F: FnMut(Vec<ChatMessage>) -> Fut,
    Fut: std::future::Future<
            Output = std::result::Result<
                MaterializeInternalOutput<T>,
                (RStructorError, Option<ValidationFailureContext>),
            >,
        >,
{
    let initial_messages = vec![ChatMessage::user_with_media(prompt, media.to_vec())];
    let output =
        generate_with_retry_with_initial_messages(generate_fn, initial_messages, max_retries)
            .await?;
    Ok(output.data)
}

/// Macro to generate standard builder methods for LLM clients.
///
/// This macro generates `model()`, `temperature()`, `max_tokens()`, and `timeout()` methods
/// that are identical across all LLM client implementations.
#[macro_export]
macro_rules! impl_client_builder_methods {
    (
        client_type: $client:ty,
        config_type: $config:ty,
        model_type: $model:ty,
        provider_name: $provider:expr
    ) => {
        impl $client {
            /// Set the model to use. Accepts either a Model enum variant or a string.
            ///
            /// When a string is provided, it will be converted to a Model enum. If the string
            /// matches a known model variant, that variant is used; otherwise, it becomes `Custom(name)`.
            /// This allows using any model name, including new models or local LLMs, without needing
            /// to update the enum.
            #[tracing::instrument(skip(self, model))]
            pub fn model<M: Into<$model>>(mut self, model: M) -> Self {
                let model = model.into();
                tracing::debug!(
                    previous_model = ?self.config.model,
                    new_model = ?model,
                    "Setting {} model", $provider
                );
                self.config.model = model;
                self
            }

            /// Set the temperature (0.0 to 1.0, lower = more deterministic)
            #[tracing::instrument(skip(self))]
            pub fn temperature(mut self, temp: f32) -> Self {
                tracing::debug!(
                    previous_temp = self.config.temperature,
                    new_temp = temp,
                    "Setting temperature"
                );
                self.config.temperature = temp;
                self
            }

            /// Set the maximum tokens to generate
            #[tracing::instrument(skip(self))]
            pub fn max_tokens(mut self, max: u32) -> Self {
                tracing::debug!(
                    previous_max = ?self.config.max_tokens,
                    new_max = max,
                    "Setting max_tokens"
                );
                // Ensure max_tokens is at least 1 to avoid API errors
                self.config.max_tokens = Some(max.max(1));
                self
            }

            /// Set the timeout for HTTP requests.
            ///
            /// This sets the timeout for both the connection and the entire request.
            /// The timeout applies to each HTTP request made by the client.
            ///
            /// # Arguments
            ///
            /// * `timeout` - Timeout duration (e.g., `Duration::from_secs(30)` for 30 seconds)
            #[tracing::instrument(skip(self))]
            pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
                tracing::debug!(
                    previous_timeout = ?self.config.timeout,
                    new_timeout = ?timeout,
                    "Setting timeout"
                );
                self.config.timeout = Some(timeout);

                // Rebuild reqwest client with timeout immediately
                self.client = reqwest::Client::builder()
                    .timeout(timeout)
                    .build()
                    .unwrap_or_else(|e| {
                        tracing::warn!(
                            error = %e,
                            "Failed to build reqwest client with timeout, using default"
                        );
                        reqwest::Client::new()
                    });

                self
            }

            /// Set the maximum number of retry attempts for validation errors.
            ///
            /// When `materialize` encounters a validation error, it will automatically
            /// retry up to this many times, including the validation error message in subsequent attempts.
            ///
            /// The default is 3 retries. Use `.no_retries()` to disable retries entirely.
            ///
            /// # Arguments
            ///
            /// * `max_retries` - Maximum number of retry attempts (0 = no retries, only single attempt)
            ///
            /// # Examples
            ///
            /// ```no_run
            /// # use rstructor::OpenAIClient;
            /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
            /// let client = OpenAIClient::new("api-key")?
            ///     .max_retries(5);  // Increase to 5 retries (default is 3)
            /// # Ok(())
            /// # }
            /// ```
            #[tracing::instrument(skip(self))]
            pub fn max_retries(mut self, max_retries: usize) -> Self {
                tracing::debug!(
                    previous_max_retries = ?self.config.max_retries,
                    new_max_retries = max_retries,
                    "Setting max_retries"
                );
                self.config.max_retries = Some(max_retries);
                self
            }

            /// Disable automatic retries on validation errors.
            ///
            /// By default, the client retries up to 3 times when validation errors occur.
            /// Use this method to disable retries and fail immediately on the first error.
            ///
            /// # Examples
            ///
            /// ```no_run
            /// # use rstructor::OpenAIClient;
            /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
            /// let client = OpenAIClient::new("api-key")?
            ///     .no_retries();  // Fail immediately on validation errors
            /// # Ok(())
            /// # }
            /// ```
            #[tracing::instrument(skip(self))]
            pub fn no_retries(mut self) -> Self {
                tracing::debug!(
                    previous_max_retries = ?self.config.max_retries,
                    "Disabling retries"
                );
                self.config.max_retries = Some(0);
                self
            }
        }
    };
}

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

    #[test]
    fn test_add_additional_properties_simple_object() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            }
        });
        add_additional_properties_false(&mut schema);
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
    }

    #[test]
    fn test_add_additional_properties_nested_object() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "user": {
                    "type": "object",
                    "properties": {
                        "name": { "type": "string" }
                    }
                }
            }
        });
        add_additional_properties_false(&mut schema);
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
        assert_eq!(
            schema["properties"]["user"]["additionalProperties"],
            serde_json::json!(false)
        );
    }

    #[test]
    fn test_add_additional_properties_array_items() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "ingredients": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": { "type": "string" },
                            "amount": { "type": "string" }
                        }
                    }
                }
            }
        });
        add_additional_properties_false(&mut schema);
        // Top-level should have additionalProperties: false
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
        // Array items object should also have additionalProperties: false
        assert_eq!(
            schema["properties"]["ingredients"]["items"]["additionalProperties"],
            serde_json::json!(false)
        );
    }

    #[test]
    fn test_add_additional_properties_deeply_nested() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "recipe": {
                    "type": "object",
                    "properties": {
                        "ingredients": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "details": {
                                        "type": "object",
                                        "properties": {
                                            "brand": { "type": "string" }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        add_additional_properties_false(&mut schema);

        // All object levels should have additionalProperties: false
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
        assert_eq!(
            schema["properties"]["recipe"]["additionalProperties"],
            serde_json::json!(false)
        );
        assert_eq!(
            schema["properties"]["recipe"]["properties"]["ingredients"]["items"]["additionalProperties"],
            serde_json::json!(false)
        );
        assert_eq!(
            schema["properties"]["recipe"]["properties"]["ingredients"]["items"]["properties"]["details"]
                ["additionalProperties"],
            serde_json::json!(false)
        );
    }

    #[test]
    fn test_add_additional_properties_anyof() {
        let mut schema = serde_json::json!({
            "anyOf": [
                {
                    "type": "object",
                    "properties": {
                        "name": { "type": "string" }
                    }
                },
                {
                    "type": "object",
                    "properties": {
                        "id": { "type": "number" }
                    }
                }
            ]
        });
        add_additional_properties_false(&mut schema);

        assert_eq!(
            schema["anyOf"][0]["additionalProperties"],
            serde_json::json!(false)
        );
        assert_eq!(
            schema["anyOf"][1]["additionalProperties"],
            serde_json::json!(false)
        );
    }

    #[test]
    fn test_add_additional_properties_definitions() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "item": { "$ref": "#/definitions/Item" }
            },
            "definitions": {
                "Item": {
                    "type": "object",
                    "properties": {
                        "name": { "type": "string" }
                    }
                }
            }
        });
        add_additional_properties_false(&mut schema);

        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
        assert_eq!(
            schema["definitions"]["Item"]["additionalProperties"],
            serde_json::json!(false)
        );
    }

    #[test]
    fn test_add_additional_properties_preserves_existing() {
        // If additionalProperties is already set, it should be overwritten
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            },
            "additionalProperties": true
        });
        add_additional_properties_false(&mut schema);
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
    }

    #[test]
    fn test_add_additional_properties_no_type() {
        // Object with properties but no explicit type should still get additionalProperties: false
        let mut schema = serde_json::json!({
            "properties": {
                "name": { "type": "string" }
            }
        });
        add_additional_properties_false(&mut schema);
        assert_eq!(schema["additionalProperties"], serde_json::json!(false));
    }

    #[test]
    fn test_adds_required_array() {
        // Schema without required array should get one added with all property keys
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "number" }
            }
        });
        add_additional_properties_false(&mut schema);

        let required = schema["required"]
            .as_array()
            .expect("required should be an array");
        assert_eq!(required.len(), 2);
        assert!(required.contains(&serde_json::json!("name")));
        assert!(required.contains(&serde_json::json!("age")));
    }

    #[test]
    fn test_overrides_existing_required_array() {
        // Schema with existing required array should be overridden to include all properties
        // (OpenAI strict mode requires ALL properties in required, even optional ones)
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" },
                "age": { "type": "number" }
            },
            "required": ["name"]
        });
        add_additional_properties_false(&mut schema);

        let required = schema["required"]
            .as_array()
            .expect("required should be an array");
        // Now it should include ALL properties, not just the original
        assert_eq!(required.len(), 2);
        assert!(required.contains(&serde_json::json!("name")));
        assert!(required.contains(&serde_json::json!("age")));
    }

    #[test]
    fn test_adds_required_array_to_nested_objects() {
        // Nested objects should also get required arrays
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "steps": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "number": { "type": "integer" },
                            "description": { "type": "string" }
                        }
                    }
                }
            }
        });
        add_additional_properties_false(&mut schema);

        // Top-level should have required
        let required = schema["required"]
            .as_array()
            .expect("required should be an array");
        assert!(required.contains(&serde_json::json!("steps")));

        // Nested array items should also have required
        let nested_required = schema["properties"]["steps"]["items"]["required"]
            .as_array()
            .expect("nested required should be an array");
        assert!(nested_required.contains(&serde_json::json!("number")));
        assert!(nested_required.contains(&serde_json::json!("description")));
    }

    #[test]
    fn truncate_message_ascii_within_limit() {
        let msg = "Hello, world!";
        assert_eq!(truncate_message(msg, 20), "Hello, world!");
    }

    #[test]
    fn truncate_message_ascii_exact_limit() {
        let msg = "Hello";
        assert_eq!(truncate_message(msg, 5), "Hello");
    }

    #[test]
    fn truncate_message_ascii_exceeds_limit() {
        let msg = "Hello, world!";
        assert_eq!(truncate_message(msg, 5), "Hello...");
    }

    #[test]
    fn truncate_message_utf8_within_limit() {
        let msg = "你好世界"; // 12 bytes (3 bytes per character)
        assert_eq!(truncate_message(msg, 20), "你好世界");
    }

    #[test]
    fn truncate_message_utf8_boundary_safe() {
        // "你好世界" is 12 bytes total (3 bytes per character)
        // Truncating at 5 bytes would fall in the middle of the second character
        // floor_char_boundary(5) should return 3 (end of first character)
        let msg = "你好世界";
        let result = truncate_message(msg, 5);
        assert_eq!(result, "你...");
    }

    #[test]
    fn truncate_message_utf8_exact_boundary() {
        // Truncating at exactly 6 bytes should include first two characters
        let msg = "你好世界";
        let result = truncate_message(msg, 6);
        assert_eq!(result, "你好...");
    }

    #[test]
    fn truncate_message_emoji() {
        // Emojis are typically 4 bytes each
        let msg = "🎉🎊🎈";
        // Truncating at 5 bytes falls in the middle of second emoji
        // floor_char_boundary(5) should return 4 (end of first emoji)
        let result = truncate_message(msg, 5);
        assert_eq!(result, "🎉...");
    }

    #[test]
    fn truncate_message_mixed_utf8() {
        let msg = "Error: 无效的请求";
        // "Error: " is 7 bytes, then Chinese characters are 3 bytes each
        // Truncating at 10 bytes falls at the boundary after the first Chinese char
        // floor_char_boundary(10) should return 10 (end of first Chinese char after "Error: ")
        let result = truncate_message(msg, 10);
        assert_eq!(result, "Error: 无...");
    }

    #[test]
    fn truncate_message_empty_string() {
        let msg = "";
        assert_eq!(truncate_message(msg, 10), "");
    }

    #[test]
    fn truncate_message_zero_limit() {
        let msg = "Hello";
        // floor_char_boundary(0) returns 0, so we get just "..."
        assert_eq!(truncate_message(msg, 0), "...");
    }

    #[test]
    fn test_gemini_schema_strips_unsupported_keywords() {
        use crate::schema::Schema;

        // Create a schema with examples and other unsupported keywords
        let schema = Schema::new(serde_json::json!({
            "type": "object",
            "title": "Movie",
            "properties": {
                "title": { "type": "string", "description": "Movie title" },
                "year": { "type": "integer", "description": "Release year" }
            },
            "examples": [{
                "title": "The Matrix",
                "year": 1999
            }]
        }));

        let gemini_schema = prepare_gemini_schema(&schema);

        // Verify examples is stripped
        assert!(
            gemini_schema.get("examples").is_none(),
            "examples should be stripped from Gemini schema"
        );

        // Verify title is stripped (Gemini doesn't support it)
        assert!(
            gemini_schema.get("title").is_none(),
            "title should be stripped from Gemini schema"
        );

        // Verify the basic schema structure is preserved
        assert_eq!(gemini_schema["type"], "object");
        assert!(gemini_schema["properties"]["title"].is_object());
        assert!(gemini_schema["properties"]["year"].is_object());
    }

    #[test]
    fn test_gemini_schema_strips_nested_examples() {
        use crate::schema::Schema;

        // Create a schema with nested objects that have examples
        let schema = Schema::new(serde_json::json!({
            "type": "object",
            "properties": {
                "recipe_name": { "type": "string" },
                "ingredients": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": { "type": "string" },
                            "amount": { "type": "number" }
                        },
                        "examples": [{
                            "name": "flour",
                            "amount": 2.5
                        }]
                    }
                }
            },
            "examples": [{
                "recipe_name": "Cookies",
                "ingredients": []
            }]
        }));

        let gemini_schema = prepare_gemini_schema(&schema);

        // Verify examples is stripped at root
        assert!(
            gemini_schema.get("examples").is_none(),
            "root examples should be stripped"
        );

        // Verify examples is stripped from array items (nested object)
        assert!(
            gemini_schema["properties"]["ingredients"]["items"]
                .get("examples")
                .is_none(),
            "nested examples should be stripped"
        );
    }

    #[test]
    fn test_gemini_schema_strips_additional_properties() {
        let mut schema_json = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            },
            "additionalProperties": false
        });

        strip_gemini_unsupported_keywords(&mut schema_json);

        assert!(
            schema_json.get("additionalProperties").is_none(),
            "additionalProperties should be stripped"
        );
    }

    #[test]
    fn test_gemini_schema_strips_title_and_schema() {
        let mut schema_json = serde_json::json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "title": "Movie",
            "type": "object",
            "properties": {
                "name": {
                    "title": "MovieName",
                    "type": "string"
                }
            }
        });

        strip_gemini_unsupported_keywords(&mut schema_json);

        assert!(
            schema_json.get("$schema").is_none(),
            "$schema should be stripped"
        );
        assert!(
            schema_json.get("title").is_none(),
            "title should be stripped"
        );
        assert!(
            schema_json["properties"]["name"].get("title").is_none(),
            "nested title should be stripped"
        );
    }

    #[test]
    fn test_extract_adjacently_tagged_info_anyof() {
        let schema = serde_json::json!({
            "anyOf": [
                {
                    "type": "object",
                    "properties": {
                        "status": { "type": "string", "enum": ["Success"] },
                        "data": {
                            "type": "object",
                            "properties": {
                                "output": { "type": "string" }
                            },
                            "required": ["output"]
                        }
                    },
                    "required": ["status", "data"]
                },
                {
                    "type": "object",
                    "properties": {
                        "status": { "type": "string", "enum": ["Failure"] },
                        "data": {
                            "type": "object",
                            "properties": {
                                "reason": { "type": "string" }
                            },
                            "required": ["reason"]
                        }
                    },
                    "required": ["status", "data"]
                }
            ]
        });

        let info = extract_adjacently_tagged_info(&schema).expect("should detect anyOf enum info");
        assert_eq!(info.tag_key, "status");
        assert_eq!(info.content_key, "data");
        assert_eq!(info.tag_values.len(), 2);
        assert!(info.tag_values.contains(&"Success".to_string()));
        assert!(info.tag_values.contains(&"Failure".to_string()));
    }

    #[test]
    fn test_gemini_anyof_adjacently_tagged_variants_are_flattened() {
        let mut schema = serde_json::json!({
            "anyOf": [
                {
                    "type": "object",
                    "properties": {
                        "status": { "type": "string", "enum": ["Success"] },
                        "data": {
                            "type": "object",
                            "properties": {
                                "output": { "type": "string" }
                            },
                            "required": ["output"]
                        }
                    },
                    "required": ["status", "data"],
                    "description": "Success variant"
                },
                {
                    "type": "object",
                    "properties": {
                        "status": { "type": "string", "enum": ["Failure"] },
                        "data": {
                            "type": "object",
                            "properties": {
                                "reason": { "type": "string" }
                            },
                            "required": ["reason"]
                        }
                    },
                    "required": ["status", "data"],
                    "description": "Failure variant"
                }
            ]
        });

        strip_gemini_unsupported_keywords_recursive(&mut schema);

        let first_props = schema["anyOf"][0]["properties"]
            .as_object()
            .expect("properties should be object");
        assert!(first_props.contains_key("status"));
        assert!(first_props.contains_key("output"));
        assert!(!first_props.contains_key("data"));

        let first_required = schema["anyOf"][0]["required"]
            .as_array()
            .expect("required should be array");
        assert!(first_required.contains(&serde_json::json!("status")));
        assert!(first_required.contains(&serde_json::json!("output")));
        assert!(!first_required.contains(&serde_json::json!("data")));
    }

    #[test]
    fn test_gemini_map_with_x_enum_keys() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "counts": {
                    "type": "object",
                    "additionalProperties": { "type": "integer" },
                    "description": "Map using enum keys. Keys: [info, warn, error]",
                    "x-enum-keys": ["info", "warn", "error"]
                }
            }
        });
        strip_gemini_unsupported_keywords_recursive(&mut schema);
        let props = schema["properties"]["counts"]["properties"]
            .as_object()
            .unwrap();
        assert!(props.contains_key("info"), "should have 'info' key");
        assert!(props.contains_key("warn"), "should have 'warn' key");
        assert!(props.contains_key("error"), "should have 'error' key");
        assert!(
            !props.contains_key("key1"),
            "should not have placeholder 'key1'"
        );
        assert!(
            schema["properties"]["counts"].get("x-enum-keys").is_none(),
            "x-enum-keys should be stripped from final schema"
        );
    }

    #[test]
    fn test_gemini_map_with_description_only_keys_hint() {
        // Backward compat: description-only "Keys: [...]" pattern still works
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "counts": {
                    "type": "object",
                    "additionalProperties": { "type": "integer" },
                    "description": "Keys: [alpha, beta, gamma]"
                }
            }
        });
        strip_gemini_unsupported_keywords_recursive(&mut schema);
        let props = schema["properties"]["counts"]["properties"]
            .as_object()
            .unwrap();
        assert!(props.contains_key("alpha"), "should have 'alpha' key");
        assert!(props.contains_key("beta"), "should have 'beta' key");
        assert!(props.contains_key("gamma"), "should have 'gamma' key");
        assert!(
            !props.contains_key("key1"),
            "should not have placeholder 'key1'"
        );
    }

    #[test]
    fn test_gemini_x_enum_keys_stripped_from_non_map_schema() {
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "x-enum-keys": ["a", "b"]
                }
            }
        });
        strip_gemini_unsupported_keywords_recursive(&mut schema);
        assert!(
            schema["properties"]["name"].get("x-enum-keys").is_none(),
            "x-enum-keys should be stripped from non-map schemas"
        );
    }

    #[tokio::test]
    async fn test_generate_with_retry_with_initial_messages_preserves_media() {
        let initial = vec![ChatMessage::user_with_media(
            "describe image",
            vec![crate::backend::client::MediaFile::from_bytes(
                b"hello-image",
                "image/png",
            )],
        )];

        let output = generate_with_retry_with_initial_messages(
            |messages: Vec<ChatMessage>| async move {
                assert_eq!(messages.len(), 1);
                assert_eq!(messages[0].media.len(), 1);
                Ok(MaterializeInternalOutput::new(
                    "ok".to_string(),
                    "{\"ok\":true}".to_string(),
                    None,
                ))
            },
            initial,
            Some(0),
        )
        .await
        .expect("generation should succeed");

        assert_eq!(output.data, "ok");
    }

    #[tokio::test]
    async fn test_generate_with_retry_with_initial_messages_adds_feedback_history() {
        let initial = vec![ChatMessage::user_with_media(
            "describe image",
            vec![crate::backend::client::MediaFile::from_bytes(
                b"hello-image",
                "image/png",
            )],
        )];

        let mut attempts = 0usize;
        let output = generate_with_retry_with_initial_messages(
            |messages: Vec<ChatMessage>| {
                attempts += 1;
                async move {
                    if attempts == 1 {
                        Err((
                            RStructorError::ValidationError("schema validation failed".to_string()),
                            Some(ValidationFailureContext::new(
                                "missing required field: summary",
                                "{\"subject\":\"rust\"}",
                            )),
                        ))
                    } else {
                        assert_eq!(messages.len(), 3);
                        assert_eq!(messages[0].media.len(), 1);
                        assert_eq!(messages[1].role, crate::backend::ChatRole::Assistant);
                        assert_eq!(messages[2].role, crate::backend::ChatRole::User);
                        Ok(MaterializeInternalOutput::new(
                            "ok".to_string(),
                            "{\"ok\":true}".to_string(),
                            None,
                        ))
                    }
                }
            },
            initial,
            Some(1),
        )
        .await
        .expect("generation should succeed after retry");

        assert_eq!(attempts, 2);
        assert_eq!(output.data, "ok");
    }
}