anyllm_translate 0.2.0

Pure translation layer between Anthropic Messages API and OpenAI Chat Completions
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
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
//! Anthropic <-> OpenAI message/content mapping.
//!
//! Stateless conversion functions: `anthropic_to_openai_request` (forward translation),
//! `openai_to_anthropic_request` and `anthropic_to_openai_response` (reverse translation).
//! All functions are pure — no I/O, no side effects.

use crate::anthropic;
use crate::mapping::{streaming_map, tools_map, usage_map, warnings::TranslationWarnings};
use crate::openai;
use crate::util;

/// Extract system prompt text from Anthropic's System type.
/// Warns if cache_control is present (no equivalent in downstream APIs).
pub fn extract_system_text(system: &anthropic::System) -> String {
    if let anthropic::System::Blocks(blocks) = system {
        if blocks.iter().any(|b| b.cache_control.is_some()) {
            tracing::warn!("cache_control on system blocks dropped: no downstream equivalent");
        }
    }
    match system {
        anthropic::System::Text(s) => s.clone(),
        anthropic::System::Blocks(blocks) => blocks
            .iter()
            .map(|b| b.text.as_str())
            .collect::<Vec<_>>()
            .join("\n"),
    }
}

/// Compute degradation warnings for an Anthropic request without performing translation.
///
/// Returns a `TranslationWarnings` value listing every feature that will be silently
/// dropped or degraded when this request is translated to an OpenAI request.
/// The proxy injects these as an `x-anyllm-degradation` response header so clients
/// can detect silent drops without inspecting server logs.
pub fn compute_request_warnings(req: &anthropic::MessageCreateRequest) -> TranslationWarnings {
    let mut w = TranslationWarnings::default();
    if req.top_k.is_some() {
        w.add("top_k");
    }
    if req.thinking.is_some() {
        w.add("thinking_config");
    }
    if let Some(ref seqs) = req.stop_sequences {
        if seqs.len() > 4 {
            w.add("stop_sequences_truncated");
        }
    }
    if let Some(anthropic::System::Blocks(blocks)) = &req.system {
        if blocks.iter().any(|b| b.cache_control.is_some()) {
            w.add("cache_control");
        }
    }
    let has_document = req.messages.iter().any(|msg| match &msg.content {
        anthropic::Content::Blocks(blocks) => blocks
            .iter()
            .any(|b| matches!(b, anthropic::ContentBlock::Document { .. })),
        _ => false,
    });
    if has_document {
        w.add("document_blocks");
    }
    w
}

/// Convert an Anthropic MessageCreateRequest to an OpenAI ChatCompletionRequest.
///
/// Anthropic: <https://docs.anthropic.com/en/api/messages>
/// OpenAI: <https://platform.openai.com/docs/api-reference/chat/create>
pub fn anthropic_to_openai_request(
    req: &anthropic::MessageCreateRequest,
) -> openai::ChatCompletionRequest {
    let mut messages = Vec::new();

    if let Some(ref system) = req.system {
        let text = extract_system_text(system);
        // Uses System role instead of Developer for backward compat with
        // local LLMs (vLLM, Ollama, llama-server) that don't recognize
        // "developer". Trade-off: OpenAI o1/o3 require "developer" and
        // reject "system". We chose broader compat over o-series support
        // because most proxy users target GPT-4o or local models.
        messages.push(openai::ChatMessage {
            role: openai::ChatRole::System,
            content: Some(openai::ChatContent::Text(text)),
            name: None,
            tool_calls: None,
            tool_call_id: None,
            refusal: None,
            reasoning_content: None,
        });
    }

    for msg in &req.messages {
        convert_anthropic_message(msg, &mut messages);
    }

    let tools = req
        .tools
        .as_ref()
        .map(|t| tools_map::anthropic_tools_to_openai(t));

    let tool_choice = req
        .tool_choice
        .as_ref()
        .map(tools_map::anthropic_tool_choice_to_openai);

    // Map disable_parallel_tool_use to OpenAI parallel_tool_calls.
    // Compat spec: "Fully supported". See: https://docs.anthropic.com/en/api/openai-sdk#tools--functions-fields
    let parallel_tool_calls = match req.tool_choice.as_ref() {
        Some(anthropic::ToolChoice::Auto {
            disable_parallel_tool_use: Some(true),
        })
        | Some(anthropic::ToolChoice::Any {
            disable_parallel_tool_use: Some(true),
        }) => Some(false),
        _ => None,
    };

    // Map metadata.user_id to OpenAI user field.
    // Compat spec: user is "Ignored", but we forward it for traceability.
    // See: https://docs.anthropic.com/en/api/openai-sdk#simple-fields
    let user = req.metadata.as_ref().and_then(|m| m.user_id.clone());
    if req.top_k.is_some() {
        tracing::warn!("top_k parameter dropped: no OpenAI equivalent");
    }
    // Map Anthropic thinking config to OpenAI reasoning_effort (via extra).
    // Thinking content blocks in messages are separately mapped to reasoning_content.
    // Thresholds (4 k / 16 k tokens) are proxy-inferred approximations; OpenAI does not
    // document exact token counts for each effort level. Chosen to match common usage:
    //   low  ≈ quick CoT drafts (< 4 k), medium ≈ standard reasoning, high ≈ extended thinking.
    let reasoning_effort = match &req.thinking {
        Some(crate::anthropic::ThinkingConfig::Enabled { budget_tokens }) => {
            let effort = if *budget_tokens < 4_000 {
                "low"
            } else if *budget_tokens < 16_000 {
                "medium"
            } else {
                "high"
            };
            tracing::info!(
                budget_tokens,
                reasoning_effort = effort,
                "thinking config mapped to reasoning_effort"
            );
            Some(effort)
        }
        _ => None,
    };

    // OpenAI caps stop sequences at 4; empty array is invalid (requires 1-4 elements)
    let stop = req.stop_sequences.as_ref().and_then(|seqs| {
        if seqs.is_empty() {
            return None;
        }
        if seqs.len() > 4 {
            tracing::warn!(
                count = seqs.len(),
                "stop_sequences truncated from {} to 4 (OpenAI limit)",
                seqs.len()
            );
        }
        let capped: Vec<String> = seqs.iter().take(4).cloned().collect();
        Some(if capped.len() == 1 {
            openai::Stop::Single(capped.into_iter().next().unwrap())
        } else {
            openai::Stop::Multiple(capped)
        })
    });

    let mut oai_req = openai::ChatCompletionRequest {
        model: req.model.clone(),
        messages,
        // Default: set both for local LLM compat (vLLM, ollama only
        // recognize max_tokens). Overridden below for o-series models.
        max_tokens: Some(req.max_tokens),
        max_completion_tokens: Some(req.max_tokens),
        // Compat spec: "Between 0 and 1 (inclusive). Values greater than 1 are capped at 1."
        // See: https://docs.anthropic.com/en/api/openai-sdk#simple-fields
        temperature: req.temperature.map(|t| t.clamp(0.0, 1.0)),
        top_p: req.top_p,
        stop,
        tools,
        tool_choice,
        stream: req.stream,
        // Required for the streaming translator: without include_usage=true,
        // OpenAI omits the final usage chunk and we cannot report token counts
        // back to the Anthropic client. Local LLMs that don't support
        // stream_options may reject this with 400.
        stream_options: if req.stream == Some(true) {
            Some(openai::StreamOptions {
                include_usage: true,
            })
        } else {
            None
        },
        presence_penalty: None,
        frequency_penalty: None,
        response_format: None,
        user,
        parallel_tool_calls,
        extra: req.extra.clone(),
    };

    // Inject reasoning_effort if derived from thinking config and not already set.
    if let Some(effort) = reasoning_effort {
        oai_req
            .extra
            .entry("reasoning_effort")
            .or_insert_with(|| serde_json::Value::String(effort.to_owned()));
    }

    // Anthropic API returns single completions only; strip n to avoid
    // wasting tokens on choices that get discarded (only choices[0] is used).
    if let Some(n_val) = oai_req.extra.remove("n") {
        if n_val != serde_json::Value::Number(1.into()) {
            tracing::warn!(n = %n_val, "n parameter stripped: Anthropic API returns single completions only");
        }
    }

    // o-series reasoning models require "developer" role instead of "system",
    // reject max_tokens (use max_completion_tokens instead), and reject
    // temperature/top_p — all variants, including GA releases.
    if is_o_series_model(&oai_req.model) {
        oai_req.max_tokens = None;
        oai_req.temperature = None;
        oai_req.top_p = None;
        for msg in &mut oai_req.messages {
            if msg.role == openai::ChatRole::System {
                msg.role = openai::ChatRole::Developer;
            }
        }
    }

    // When a specific tool is forced, enable OpenAI strict structured outputs for it.
    // This guarantees the returned JSON exactly matches the schema.
    if let Some(forced_name) = req.tool_choice.as_ref().and_then(extract_forced_tool_name) {
        if let Some(ref mut tools) = oai_req.tools {
            apply_strict_mode_to_tool(tools, &forced_name);
        }
    }

    oai_req
}

/// Extract the forced tool name from an Anthropic ToolChoice, if any.
fn extract_forced_tool_name(tc: &anthropic::ToolChoice) -> Option<String> {
    match tc {
        anthropic::ToolChoice::Tool { name } => Some(name.clone()),
        _ => None,
    }
}

/// Set strict=true and normalize the parameter schema for the named tool.
/// Other tools in the vec are left unchanged.
fn apply_strict_mode_to_tool(tools: &mut [openai::ChatTool], forced_name: &str) {
    for tool in tools.iter_mut() {
        if tool.function.name == forced_name {
            tool.function.strict = Some(true);
            if let Some(params) = tool.function.parameters.take() {
                tool.function.parameters = Some(tools_map::normalize_schema_for_strict(params));
            }
            // Tool names are unique; stop after the first match.
            break;
        }
    }
}

/// Returns true if the model name matches an OpenAI o-series reasoning model
/// (o1, o2, o3, o4, o5, o10, etc.). Does not match "gpt-4o" where 'o' is a suffix.
/// Pattern: starts with 'o' or 'O', then one or more ASCII digits, then end-of-string or '-'.
fn is_o_series_model(model: &str) -> bool {
    // Matches: o1, o2, o3, o10, o1-mini, O4-preview, etc.
    // Rejects: gpt-4o (suffix 'o'), openai-x, o-preview (no digit after 'o').
    let bytes = model.as_bytes();
    if bytes.is_empty() || !bytes[0].eq_ignore_ascii_case(&b'o') {
        return false;
    }
    // Must have at least one digit after the 'o'.
    if bytes.len() < 2 || !bytes[1].is_ascii_digit() {
        return false;
    }
    // Skip remaining digits.
    let after_digits = bytes[1..]
        .iter()
        .position(|b| !b.is_ascii_digit())
        .map(|p| 1 + p)
        .unwrap_or(bytes.len());
    // After the digits: either end-of-string or a '-'.
    after_digits == bytes.len() || bytes[after_digits] == b'-'
}

/// Convert a single Anthropic InputMessage into one or more OpenAI ChatMessages.
/// An assistant message with tool_use blocks produces tool_calls.
/// A user message with tool_result blocks produces OpenAI tool-role messages.
fn convert_anthropic_message(msg: &anthropic::InputMessage, out: &mut Vec<openai::ChatMessage>) {
    let role = match msg.role {
        anthropic::Role::User => openai::ChatRole::User,
        anthropic::Role::Assistant => openai::ChatRole::Assistant,
    };

    match &msg.content {
        anthropic::Content::Text(text) => {
            out.push(openai::ChatMessage {
                role,
                content: Some(openai::ChatContent::Text(text.clone())),
                name: None,
                tool_calls: None,
                tool_call_id: None,
                refusal: None,
                reasoning_content: None,
            });
        }
        anthropic::Content::Blocks(blocks) => {
            if msg.role == anthropic::Role::Assistant {
                convert_assistant_blocks(blocks, out);
            } else {
                convert_user_blocks(blocks, out);
            }
        }
    }
}

/// Assistant blocks: text parts become content, tool_use blocks become tool_calls.
fn convert_assistant_blocks(
    blocks: &[anthropic::ContentBlock],
    out: &mut Vec<openai::ChatMessage>,
) {
    let mut text_parts = Vec::new();
    let mut tool_calls = Vec::new();
    let mut thinking_parts = Vec::new();

    for block in blocks {
        match block {
            anthropic::ContentBlock::Text { text } => {
                text_parts.push(text.clone());
            }
            anthropic::ContentBlock::ToolUse { id, name, input } => {
                tool_calls.push(openai::ToolCall {
                    id: id.clone(),
                    call_type: "function".to_string(),
                    function: openai::FunctionCall {
                        name: name.clone(),
                        arguments: util::json::value_to_json_string(input),
                    },
                });
            }
            anthropic::ContentBlock::Thinking { thinking, .. } => {
                thinking_parts.push(thinking.clone());
            }
            // RedactedThinking has no meaningful content to forward
            _ => {}
        }
    }

    let content = if text_parts.is_empty() {
        None
    } else {
        Some(openai::ChatContent::Text(text_parts.join("")))
    };

    let reasoning_content = if thinking_parts.is_empty() {
        None
    } else {
        Some(thinking_parts.join(""))
    };

    out.push(openai::ChatMessage {
        role: openai::ChatRole::Assistant,
        content,
        name: None,
        tool_calls: if tool_calls.is_empty() {
            None
        } else {
            Some(tool_calls)
        },
        tool_call_id: None,
        refusal: None,
        reasoning_content,
    });
}

/// Resolve an Anthropic ImageSource to a URL string (data URI or direct URL).
fn image_source_to_url(source: &anthropic::messages::ImageSource) -> Option<String> {
    if let Some(ref url) = source.url {
        Some(url.clone())
    } else if let Some(ref data) = source.data {
        let mt = source.media_type.as_deref().unwrap_or("image/png");
        Some(format!("data:{};base64,{}", mt, data))
    } else {
        None
    }
}

/// Simplify a Vec of content parts: use plain Text when there's a single text part,
/// multipart array otherwise. Moves data out of the Vec to avoid cloning.
fn simplify_content_parts(mut parts: Vec<openai::ChatContentPart>) -> openai::ChatContent {
    if parts.len() == 1 {
        match parts.remove(0) {
            openai::ChatContentPart::Text { text } => openai::ChatContent::Text(text),
            other => openai::ChatContent::Parts(vec![other]),
        }
    } else {
        openai::ChatContent::Parts(parts)
    }
}

/// User blocks: text/image parts become content, tool_result blocks become
/// separate OpenAI tool-role messages.
fn convert_user_blocks(blocks: &[anthropic::ContentBlock], out: &mut Vec<openai::ChatMessage>) {
    let mut content_parts: Vec<openai::ChatContentPart> = Vec::new();
    let mut tool_results: Vec<(String, Vec<openai::ChatContentPart>)> = Vec::new();

    for block in blocks {
        match block {
            anthropic::ContentBlock::Text { text } => {
                content_parts.push(openai::ChatContentPart::Text { text: text.clone() });
            }
            anthropic::ContentBlock::Image { source } => {
                if let Some(url) = image_source_to_url(source) {
                    content_parts.push(openai::ChatContentPart::ImageUrl {
                        image_url: openai::chat_completions::ImageUrl { url, detail: None },
                    });
                }
            }
            anthropic::ContentBlock::ToolResult {
                tool_use_id,
                content,
                is_error,
            } => {
                let mut parts: Vec<openai::ChatContentPart> = Vec::new();
                match content {
                    Some(anthropic::messages::ToolResultContent::Text(s)) => {
                        parts.push(openai::ChatContentPart::Text { text: s.clone() });
                    }
                    Some(anthropic::messages::ToolResultContent::Blocks(inner)) => {
                        for b in inner {
                            match b {
                                anthropic::ContentBlock::Text { text } => {
                                    parts
                                        .push(openai::ChatContentPart::Text { text: text.clone() });
                                }
                                anthropic::ContentBlock::Image { source } => {
                                    if let Some(url) = image_source_to_url(source) {
                                        parts.push(openai::ChatContentPart::ImageUrl {
                                            image_url: openai::chat_completions::ImageUrl {
                                                url,
                                                detail: None,
                                            },
                                        });
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                    None => {}
                };
                // Anthropic's is_error flag has no direct OpenAI equivalent.
                // We surface it as a text prefix so the backend model sees the
                // error context in message history.
                if *is_error == Some(true) {
                    // Prefix the first text part (or add one) with "Error: "
                    if let Some(openai::ChatContentPart::Text { ref mut text }) = parts
                        .iter_mut()
                        .find(|p| matches!(p, openai::ChatContentPart::Text { .. }))
                    {
                        *text = format!("Error: {}", text);
                    } else {
                        parts.insert(
                            0,
                            openai::ChatContentPart::Text {
                                text: "Error".to_string(),
                            },
                        );
                    }
                }
                // Use empty text if no content was provided
                if parts.is_empty() {
                    parts.push(openai::ChatContentPart::Text {
                        text: String::new(),
                    });
                }
                tool_results.push((tool_use_id.clone(), parts));
            }
            anthropic::ContentBlock::Document { source, title } => {
                // OpenAI Chat Completions has no inline document support;
                // the Responses API (input_file.file_data) would be needed
                // for full fidelity. Degrade to a text note so the model
                // still sees that a document was attached.
                let label = title.as_deref().unwrap_or("document");
                tracing::warn!(
                    label = label,
                    "document block degraded to text note: no OpenAI Chat Completions equivalent"
                );
                let note = format!(
                    "[Attached {}: {} ({} bytes base64)]",
                    label,
                    source.media_type,
                    source.data.len()
                );
                content_parts.push(openai::ChatContentPart::Text { text: note });
            }
            // ToolUse and Thinking blocks don't appear in user messages; ignore if present
            anthropic::ContentBlock::ToolUse { .. }
            | anthropic::ContentBlock::Thinking { .. }
            | anthropic::ContentBlock::RedactedThinking { .. } => {}
        }
    }

    // Emit tool results before user content: OpenAI enforces strict turn
    // ordering where Tool messages must immediately follow the Assistant
    // message that produced the tool_calls. Violating this causes 400s.
    for (tool_call_id, parts) in tool_results {
        let content = Some(simplify_content_parts(parts));
        out.push(openai::ChatMessage {
            role: openai::ChatRole::Tool,
            content,
            name: None,
            tool_calls: None,
            tool_call_id: Some(tool_call_id),
            refusal: None,
            reasoning_content: None,
        });
    }

    // Emit user content message after tool results
    if !content_parts.is_empty() {
        let content = Some(simplify_content_parts(content_parts));
        out.push(openai::ChatMessage {
            role: openai::ChatRole::User,
            content,
            name: None,
            tool_calls: None,
            tool_call_id: None,
            refusal: None,
            reasoning_content: None,
        });
    }
}

/// Convert an OpenAI ChatCompletionResponse back to an Anthropic MessageResponse.
///
/// OpenAI: <https://platform.openai.com/docs/api-reference/chat/object>
/// Anthropic: <https://docs.anthropic.com/en/api/messages>
pub fn openai_to_anthropic_response(
    resp: &openai::ChatCompletionResponse,
    model: &str,
) -> anthropic::MessageResponse {
    let choice = resp.choices.first();

    let mut content = Vec::new();
    let mut stop_reason = Some(anthropic::StopReason::EndTurn);

    if let Some(choice) = choice {
        stop_reason = choice
            .finish_reason
            .as_ref()
            .map(streaming_map::map_finish_reason);

        // Map reasoning_content (DeepSeek/Qwen thinking) to Anthropic thinking block.
        // Thinking blocks precede text content in Anthropic responses.
        if let Some(ref reasoning) = choice.message.reasoning_content {
            if !reasoning.is_empty() {
                content.push(anthropic::ContentBlock::Thinking {
                    thinking: reasoning.clone(),
                    signature: None,
                });
            }
        }

        // Map content
        if let Some(ref chat_content) = choice.message.content {
            match chat_content {
                openai::ChatContent::Text(text) => {
                    if !text.is_empty() {
                        content.push(anthropic::ContentBlock::Text { text: text.clone() });
                    }
                }
                openai::ChatContent::Parts(parts) => {
                    for part in parts {
                        if let openai::ChatContentPart::Text { text } = part {
                            content.push(anthropic::ContentBlock::Text { text: text.clone() });
                        }
                    }
                }
            }
        }

        // Map refusal to text block (same pattern as Responses API path)
        if let Some(ref refusal) = choice.message.refusal {
            if !refusal.is_empty() {
                content.push(anthropic::ContentBlock::Text {
                    text: super::format_refusal(refusal),
                });
            }
        }

        // Map tool calls with robustness for local LLMs (llama-server, ollama)
        // that may produce empty IDs, empty names, or malformed arguments.
        if let Some(ref tool_calls) = choice.message.tool_calls {
            for tc in tool_calls {
                if tc.function.name.is_empty() {
                    tracing::warn!(id = tc.id, "skipping tool call with empty function name");
                    continue;
                }
                let id = if tc.id.is_empty() {
                    let synthetic = util::ids::generate_tool_use_id();
                    tracing::warn!(
                        name = tc.function.name,
                        synthetic_id = synthetic,
                        "tool call had empty ID; generated synthetic toolu_ ID"
                    );
                    synthetic
                } else {
                    tc.id.clone()
                };
                content.push(anthropic::ContentBlock::ToolUse {
                    id,
                    name: tc.function.name.clone(),
                    input: util::json::parse_tool_arguments(&tc.function.arguments),
                });
            }
        }
    }

    let usage = resp
        .usage
        .as_ref()
        .map(usage_map::openai_to_anthropic_usage)
        .unwrap_or_default();

    anthropic::MessageResponse {
        id: util::ids::generate_message_id(),
        response_type: "message".to_string(),
        role: anthropic::Role::Assistant,
        content,
        model: model.to_string(),
        stop_reason,
        stop_sequence: None,
        usage,
        created: resp.created,
    }
}

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

    // --- Helper: build a minimal Anthropic request ---

    fn basic_request() -> anthropic::MessageCreateRequest {
        anthropic::MessageCreateRequest {
            model: "claude-3-5-sonnet-20241022".to_string(),
            max_tokens: 1024,
            messages: vec![anthropic::InputMessage {
                role: anthropic::Role::User,
                content: anthropic::Content::Text("Hello".to_string()),
            }],
            system: None,
            temperature: None,
            top_p: None,
            top_k: None,
            stop_sequences: None,
            tools: None,
            tool_choice: None,
            metadata: None,
            thinking: None,
            stream: None,
            extra: serde_json::Map::new(),
        }
    }

    fn basic_openai_response() -> openai::ChatCompletionResponse {
        openai::ChatCompletionResponse {
            id: "chatcmpl-abc123".to_string(),
            object: "chat.completion".to_string(),
            model: "gpt-4o".to_string(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text("Hi there!".to_string())),
                    name: None,
                    tool_calls: None,
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::Stop),
                logprobs: None,
            }],
            usage: Some(openai::ChatUsage {
                prompt_tokens: 10,
                completion_tokens: 5,
                total_tokens: 15,
                completion_tokens_details: None,
                prompt_tokens_details: None,
            }),
            created: Some(1700000000),
            system_fingerprint: None,
            service_tier: None,
        }
    }

    // --- Request translation tests ---

    #[test]
    fn basic_text_request() {
        let req = basic_request();
        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.model, "claude-3-5-sonnet-20241022");
        assert_eq!(oai.max_tokens, Some(1024));
        assert_eq!(oai.max_completion_tokens, Some(1024));
        assert_eq!(oai.messages.len(), 1);
        assert_eq!(oai.messages[0].role, openai::ChatRole::User);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "Hello"
        ));
        assert!(oai.tools.is_none());
        assert!(oai.tool_choice.is_none());
        assert!(oai.stream_options.is_none());
    }

    #[test]
    fn system_prompt_string_becomes_developer_message() {
        let mut req = basic_request();
        req.system = Some(anthropic::System::Text(
            "You are a helpful assistant.".to_string(),
        ));

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.messages.len(), 2);
        assert_eq!(oai.messages[0].role, openai::ChatRole::System);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "You are a helpful assistant."
        ));
    }

    #[test]
    fn system_prompt_blocks_concatenated_into_developer_message() {
        let mut req = basic_request();
        req.system = Some(anthropic::System::Blocks(vec![
            anthropic::messages::SystemBlock {
                block_type: "text".to_string(),
                text: "Be concise.".to_string(),
                cache_control: None,
            },
            anthropic::messages::SystemBlock {
                block_type: "text".to_string(),
                text: "Respond in JSON.".to_string(),
                cache_control: None,
            },
        ]));

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.messages[0].role, openai::ChatRole::System);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "Be concise.\nRespond in JSON."
        ));
    }

    #[test]
    fn tool_definitions_mapped() {
        let schema = json!({
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"]
        });

        let mut req = basic_request();
        req.tools = Some(vec![anthropic::Tool {
            name: "get_weather".to_string(),
            description: Some("Get weather for a location".to_string()),
            input_schema: schema.clone(),
        }]);

        let oai = anthropic_to_openai_request(&req);

        let tools = oai.tools.unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].tool_type, "function");
        assert_eq!(tools[0].function.name, "get_weather");
        assert_eq!(
            tools[0].function.description.as_deref(),
            Some("Get weather for a location")
        );
        assert_eq!(tools[0].function.parameters, Some(schema));
    }

    #[test]
    fn tool_choice_auto() {
        let mut req = basic_request();
        req.tool_choice = Some(anthropic::ToolChoice::Auto {
            disable_parallel_tool_use: None,
        });
        let oai = anthropic_to_openai_request(&req);
        assert!(matches!(
            oai.tool_choice,
            Some(openai::ChatToolChoice::Simple(ref s)) if s == "auto"
        ));
    }

    #[test]
    fn tool_choice_any_becomes_required() {
        let mut req = basic_request();
        req.tool_choice = Some(anthropic::ToolChoice::Any {
            disable_parallel_tool_use: None,
        });
        let oai = anthropic_to_openai_request(&req);
        assert!(matches!(
            oai.tool_choice,
            Some(openai::ChatToolChoice::Simple(ref s)) if s == "required"
        ));
    }

    #[test]
    fn tool_choice_none() {
        let mut req = basic_request();
        req.tool_choice = Some(anthropic::ToolChoice::None);
        let oai = anthropic_to_openai_request(&req);
        assert!(matches!(
            oai.tool_choice,
            Some(openai::ChatToolChoice::Simple(ref s)) if s == "none"
        ));
    }

    #[test]
    fn tool_choice_specific_tool() {
        let mut req = basic_request();
        req.tool_choice = Some(anthropic::ToolChoice::Tool {
            name: "get_weather".to_string(),
        });
        let oai = anthropic_to_openai_request(&req);
        match oai.tool_choice {
            Some(openai::ChatToolChoice::Named(ref n)) => {
                assert_eq!(n.choice_type, "function");
                assert_eq!(n.function.name, "get_weather");
            }
            other => panic!("expected Named tool choice, got {:?}", other),
        }
    }

    #[test]
    fn disable_parallel_tool_use_sets_parallel_tool_calls_false() {
        let mut req = basic_request();
        req.tool_choice = Some(anthropic::ToolChoice::Auto {
            disable_parallel_tool_use: Some(true),
        });
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.parallel_tool_calls, Some(false));
    }

    #[test]
    fn disable_parallel_tool_use_false_leaves_parallel_tool_calls_none() {
        let mut req = basic_request();
        req.tool_choice = Some(anthropic::ToolChoice::Auto {
            disable_parallel_tool_use: Some(false),
        });
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.parallel_tool_calls.is_none());
    }

    #[test]
    fn no_tool_choice_leaves_parallel_tool_calls_none() {
        let req = basic_request();
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.parallel_tool_calls.is_none());
    }

    #[test]
    fn stop_sequences_capped_at_four() {
        let mut req = basic_request();
        req.stop_sequences = Some(vec![
            "a".into(),
            "b".into(),
            "c".into(),
            "d".into(),
            "e".into(),
        ]);

        let oai = anthropic_to_openai_request(&req);

        match oai.stop {
            Some(openai::Stop::Multiple(ref v)) => assert_eq!(v.len(), 4),
            other => panic!("expected Multiple stop, got {:?}", other),
        }
    }

    #[test]
    fn single_stop_sequence_is_single() {
        let mut req = basic_request();
        req.stop_sequences = Some(vec!["END".into()]);

        let oai = anthropic_to_openai_request(&req);

        assert!(matches!(
            oai.stop,
            Some(openai::Stop::Single(ref s)) if s == "END"
        ));
    }

    #[test]
    fn empty_stop_sequences_becomes_none() {
        let mut req = basic_request();
        req.stop_sequences = Some(vec![]);

        let oai = anthropic_to_openai_request(&req);

        assert!(
            oai.stop.is_none(),
            "empty stop_sequences should map to None, not Stop::Multiple([])"
        );
    }

    #[test]
    fn streaming_sets_stream_options() {
        let mut req = basic_request();
        req.stream = Some(true);

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.stream, Some(true));
        assert!(oai.stream_options.as_ref().unwrap().include_usage);
    }

    #[test]
    fn conversation_with_tool_use_and_tool_result() {
        let mut req = basic_request();
        req.messages = vec![
            // User asks
            anthropic::InputMessage {
                role: anthropic::Role::User,
                content: anthropic::Content::Text("What is the weather in NYC?".to_string()),
            },
            // Assistant calls tool
            anthropic::InputMessage {
                role: anthropic::Role::Assistant,
                content: anthropic::Content::Blocks(vec![
                    anthropic::ContentBlock::Text {
                        text: "Let me check.".to_string(),
                    },
                    anthropic::ContentBlock::ToolUse {
                        id: "call_001".to_string(),
                        name: "get_weather".to_string(),
                        input: json!({"location": "NYC"}),
                    },
                ]),
            },
            // User provides tool result
            anthropic::InputMessage {
                role: anthropic::Role::User,
                content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::ToolResult {
                    tool_use_id: "call_001".to_string(),
                    content: Some(anthropic::messages::ToolResultContent::Text(
                        "72F, sunny".to_string(),
                    )),
                    is_error: None,
                }]),
            },
        ];

        let oai = anthropic_to_openai_request(&req);

        // msg 0: user text
        assert_eq!(oai.messages[0].role, openai::ChatRole::User);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "What is the weather in NYC?"
        ));

        // msg 1: assistant with text + tool_calls
        assert_eq!(oai.messages[1].role, openai::ChatRole::Assistant);
        assert!(matches!(
            &oai.messages[1].content,
            Some(openai::ChatContent::Text(t)) if t == "Let me check."
        ));
        let tc = oai.messages[1].tool_calls.as_ref().unwrap();
        assert_eq!(tc.len(), 1);
        assert_eq!(tc[0].id, "call_001");
        assert_eq!(tc[0].function.name, "get_weather");
        assert_eq!(tc[0].function.arguments, r#"{"location":"NYC"}"#);

        // msg 2: tool result
        assert_eq!(oai.messages[2].role, openai::ChatRole::Tool);
        assert_eq!(oai.messages[2].tool_call_id.as_deref(), Some("call_001"));
        assert!(matches!(
            &oai.messages[2].content,
            Some(openai::ChatContent::Text(t)) if t == "72F, sunny"
        ));
    }

    #[test]
    fn tool_result_error_prefixed() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::ToolResult {
                tool_use_id: "call_err".to_string(),
                content: Some(anthropic::messages::ToolResultContent::Text(
                    "not found".to_string(),
                )),
                is_error: Some(true),
            }]),
        }];

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.messages[0].role, openai::ChatRole::Tool);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "Error: not found"
        ));
    }

    #[test]
    fn image_block_to_image_url_part() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::Text {
                    text: "Describe this".to_string(),
                },
                anthropic::ContentBlock::Image {
                    source: anthropic::messages::ImageSource {
                        source_type: "base64".to_string(),
                        media_type: Some("image/jpeg".to_string()),
                        data: Some("abc123".to_string()),
                        url: None,
                    },
                },
            ]),
        }];

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.messages.len(), 1);
        match &oai.messages[0].content {
            Some(openai::ChatContent::Parts(parts)) => {
                assert_eq!(parts.len(), 2);
                assert!(matches!(
                    &parts[0],
                    openai::ChatContentPart::Text { text } if text == "Describe this"
                ));
                match &parts[1] {
                    openai::ChatContentPart::ImageUrl { image_url } => {
                        assert_eq!(image_url.url, "data:image/jpeg;base64,abc123");
                    }
                    other => panic!("expected ImageUrl, got {:?}", other),
                }
            }
            other => panic!("expected Parts, got {:?}", other),
        }
    }

    #[test]
    fn image_block_with_url_uses_url_directly() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::Image {
                source: anthropic::messages::ImageSource {
                    source_type: "url".to_string(),
                    media_type: None,
                    data: None,
                    url: Some("https://example.com/img.png".to_string()),
                },
            }]),
        }];

        let oai = anthropic_to_openai_request(&req);

        // Single image part still wrapped in Parts (not a text shortcut)
        match &oai.messages[0].content {
            Some(openai::ChatContent::Parts(parts)) => {
                assert_eq!(parts.len(), 1);
                match &parts[0] {
                    openai::ChatContentPart::ImageUrl { image_url } => {
                        assert_eq!(image_url.url, "https://example.com/img.png");
                    }
                    other => panic!("expected ImageUrl, got {:?}", other),
                }
            }
            other => panic!("expected Parts, got {:?}", other),
        }
    }

    #[test]
    fn single_text_block_user_message_flattened() {
        // A single text block in user content should produce ChatContent::Text, not Parts.
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::Text {
                text: "just text".to_string(),
            }]),
        }];

        let oai = anthropic_to_openai_request(&req);

        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "just text"
        ));
    }

    // --- Response translation tests ---

    #[test]
    fn openai_text_response_to_anthropic() {
        let resp = basic_openai_response();
        let anth = openai_to_anthropic_response(&resp, "claude-3-5-sonnet-20241022");

        assert!(anth.id.starts_with("msg_"));
        assert_eq!(anth.response_type, "message");
        assert_eq!(anth.role, anthropic::Role::Assistant);
        assert_eq!(anth.model, "claude-3-5-sonnet-20241022");
        assert_eq!(anth.content.len(), 1);
        assert!(matches!(
            &anth.content[0],
            anthropic::ContentBlock::Text { text } if text == "Hi there!"
        ));
        assert_eq!(anth.stop_reason, Some(anthropic::StopReason::EndTurn));
        assert!(anth.stop_sequence.is_none());
        assert_eq!(anth.usage.input_tokens, 10);
        assert_eq!(anth.usage.output_tokens, 5);
    }

    #[test]
    fn openai_tool_calls_response_to_anthropic() {
        let resp = openai::ChatCompletionResponse {
            id: "chatcmpl-xyz".to_string(),
            object: "chat.completion".to_string(),
            model: "gpt-4o".to_string(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: None,
                    name: None,
                    tool_calls: Some(vec![openai::ToolCall {
                        id: "call_abc".to_string(),
                        call_type: "function".to_string(),
                        function: openai::FunctionCall {
                            name: "get_weather".to_string(),
                            arguments: r#"{"location":"NYC"}"#.to_string(),
                        },
                    }]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: Some(openai::ChatUsage {
                prompt_tokens: 20,
                completion_tokens: 10,
                total_tokens: 30,
                completion_tokens_details: None,
                prompt_tokens_details: None,
            }),
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "claude-3-5-sonnet-20241022");

        assert_eq!(anth.stop_reason, Some(anthropic::StopReason::ToolUse));
        assert_eq!(anth.content.len(), 1);
        match &anth.content[0] {
            anthropic::ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call_abc");
                assert_eq!(name, "get_weather");
                assert_eq!(input, &json!({"location": "NYC"}));
            }
            other => panic!("expected ToolUse, got {:?}", other),
        }
    }

    #[test]
    fn stop_reason_mapping() {
        let cases = vec![
            (openai::FinishReason::Stop, anthropic::StopReason::EndTurn),
            (
                openai::FinishReason::Length,
                anthropic::StopReason::MaxTokens,
            ),
            (
                openai::FinishReason::ToolCalls,
                anthropic::StopReason::ToolUse,
            ),
            (
                openai::FinishReason::ContentFilter,
                anthropic::StopReason::EndTurn,
            ),
            (
                openai::FinishReason::FunctionCall,
                anthropic::StopReason::ToolUse,
            ),
        ];

        for (oai_reason, expected) in cases {
            let resp = openai::ChatCompletionResponse {
                id: "x".into(),
                object: "chat.completion".into(),
                model: "gpt-4o".into(),
                choices: vec![openai::Choice {
                    index: 0,
                    message: openai::ChatMessage {
                        role: openai::ChatRole::Assistant,
                        content: Some(openai::ChatContent::Text("ok".into())),
                        name: None,
                        tool_calls: None,
                        tool_call_id: None,
                        refusal: None,
                        reasoning_content: None,
                    },
                    finish_reason: Some(oai_reason),
                    logprobs: None,
                }],
                usage: None,
                created: None,
                system_fingerprint: None,
                service_tier: None,
            };
            let anth = openai_to_anthropic_response(&resp, "m");
            assert_eq!(anth.stop_reason, Some(expected));
        }
    }

    #[test]
    fn empty_content_response() {
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "gpt-4o".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text(String::new())),
                    name: None,
                    tool_calls: None,
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::Stop),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        // Empty text is not added to content blocks
        assert!(anth.content.is_empty());
    }

    #[test]
    fn no_choices_produces_default_response() {
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "gpt-4o".into(),
            choices: vec![],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        assert!(anth.content.is_empty());
        // Default stop_reason when no choice
        assert_eq!(anth.stop_reason, Some(anthropic::StopReason::EndTurn));
    }

    #[test]
    fn missing_usage_produces_defaults() {
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "gpt-4o".into(),
            choices: vec![],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        assert_eq!(anth.usage.input_tokens, 0);
        assert_eq!(anth.usage.output_tokens, 0);
    }

    #[test]
    fn tool_result_blocks_content_concatenated() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::ToolResult {
                tool_use_id: "call_1".to_string(),
                content: Some(anthropic::messages::ToolResultContent::Blocks(vec![
                    anthropic::ContentBlock::Text {
                        text: "part1".to_string(),
                    },
                    anthropic::ContentBlock::Text {
                        text: "part2".to_string(),
                    },
                ])),
                is_error: None,
            }]),
        }];

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.messages[0].role, openai::ChatRole::Tool);
        // Multiple text blocks are now preserved as separate parts (not concatenated)
        // to support mixed text+image content in tool results.
        match &oai.messages[0].content {
            Some(openai::ChatContent::Parts(parts)) => {
                assert_eq!(parts.len(), 2);
                assert!(
                    matches!(&parts[0], openai::ChatContentPart::Text { text } if text == "part1")
                );
                assert!(
                    matches!(&parts[1], openai::ChatContentPart::Text { text } if text == "part2")
                );
            }
            other => panic!("expected Parts with 2 text entries, got {:?}", other),
        }
    }

    #[test]
    fn tool_result_none_content_becomes_empty_string() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::ToolResult {
                tool_use_id: "call_1".to_string(),
                content: None,
                is_error: None,
            }]),
        }];

        let oai = anthropic_to_openai_request(&req);

        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t.is_empty()
        ));
    }

    #[test]
    fn mixed_user_content_and_tool_results_produces_multiple_messages() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::Text {
                    text: "Here are the results".to_string(),
                },
                anthropic::ContentBlock::ToolResult {
                    tool_use_id: "call_1".to_string(),
                    content: Some(anthropic::messages::ToolResultContent::Text(
                        "result1".to_string(),
                    )),
                    is_error: None,
                },
            ]),
        }];

        let oai = anthropic_to_openai_request(&req);

        // Should produce two messages: tool result first (must follow assistant),
        // then user text.
        assert_eq!(oai.messages.len(), 2);
        assert_eq!(oai.messages[0].role, openai::ChatRole::Tool);
        assert_eq!(oai.messages[1].role, openai::ChatRole::User);
    }

    #[test]
    fn assistant_text_and_tool_use_combined() {
        // Assistant message with both text and tool_use should produce a single
        // OpenAI message with content + tool_calls.
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::Assistant,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::Text {
                    text: "Thinking...".to_string(),
                },
                anthropic::ContentBlock::ToolUse {
                    id: "call_1".to_string(),
                    name: "search".to_string(),
                    input: json!({"q": "rust"}),
                },
            ]),
        }];

        let oai = anthropic_to_openai_request(&req);

        assert_eq!(oai.messages.len(), 1);
        assert_eq!(oai.messages[0].role, openai::ChatRole::Assistant);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "Thinking..."
        ));
        let tc = oai.messages[0].tool_calls.as_ref().unwrap();
        assert_eq!(tc.len(), 1);
        assert_eq!(tc[0].id, "call_1");
    }

    #[test]
    fn openai_response_with_text_and_tool_calls() {
        // OpenAI can return both content and tool_calls in a single choice.
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "gpt-4o".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text("Let me check.".into())),
                    name: None,
                    tool_calls: Some(vec![openai::ToolCall {
                        id: "call_1".into(),
                        call_type: "function".into(),
                        function: openai::FunctionCall {
                            name: "lookup".into(),
                            arguments: "{}".into(),
                        },
                    }]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: Some(openai::ChatUsage {
                prompt_tokens: 5,
                completion_tokens: 3,
                total_tokens: 8,
                completion_tokens_details: None,
                prompt_tokens_details: None,
            }),
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");

        assert_eq!(anth.content.len(), 2);
        assert!(matches!(
            &anth.content[0],
            anthropic::ContentBlock::Text { text } if text == "Let me check."
        ));
        assert!(matches!(
            &anth.content[1],
            anthropic::ContentBlock::ToolUse { id, name, .. } if id == "call_1" && name == "lookup"
        ));
    }

    #[test]
    fn malformed_tool_arguments_handled() {
        // If OpenAI returns invalid JSON in arguments, parse_json_lenient wraps it as a string.
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "gpt-4o".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: None,
                    name: None,
                    tool_calls: Some(vec![openai::ToolCall {
                        id: "call_bad".into(),
                        call_type: "function".into(),
                        function: openai::FunctionCall {
                            name: "broken".into(),
                            arguments: "not json".into(),
                        },
                    }]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        match &anth.content[0] {
            anthropic::ContentBlock::ToolUse { input, .. } => {
                // parse_tool_arguments wraps invalid JSON in an object
                assert_eq!(input, &json!({"_raw_error": "not json"}));
            }
            other => panic!("expected ToolUse, got {:?}", other),
        }
    }

    #[test]
    fn document_block_converted_to_text_note() {
        let req = anthropic::MessageCreateRequest {
            model: "claude-opus-4-6".into(),
            max_tokens: 1024,
            messages: vec![anthropic::InputMessage {
                role: anthropic::Role::User,
                content: anthropic::Content::Blocks(vec![
                    anthropic::ContentBlock::Text {
                        text: "Summarize this PDF".into(),
                    },
                    anthropic::ContentBlock::Document {
                        source: anthropic::messages::DocumentSource {
                            source_type: "base64".into(),
                            media_type: "application/pdf".into(),
                            data: "AAAA".into(),
                        },
                        title: Some("report.pdf".into()),
                    },
                ]),
            }],
            system: None,
            temperature: None,
            top_p: None,
            top_k: None,
            stop_sequences: None,
            tools: None,
            tool_choice: None,
            metadata: None,
            thinking: None,
            stream: None,
            extra: serde_json::Map::new(),
        };

        let openai_req = anthropic_to_openai_request(&req);
        // Should produce a single user message with multipart content
        assert_eq!(openai_req.messages.len(), 1);
        match &openai_req.messages[0].content {
            Some(openai::ChatContent::Parts(parts)) => {
                assert_eq!(parts.len(), 2);
                // Second part should be the document note
                if let openai::ChatContentPart::Text { text } = &parts[1] {
                    assert!(text.contains("report.pdf"));
                    assert!(text.contains("application/pdf"));
                } else {
                    panic!("expected text part for document");
                }
            }
            other => panic!("expected Parts, got {:?}", other),
        }
    }

    #[test]
    fn created_timestamp_preserved_from_openai() {
        let resp = basic_openai_response();
        assert_eq!(resp.created, Some(1700000000));
        let anth = openai_to_anthropic_response(&resp, "claude-sonnet-4-6");
        assert_eq!(anth.created, Some(1700000000));
    }

    #[test]
    fn created_timestamp_none_when_absent() {
        let mut resp = basic_openai_response();
        resp.created = None;
        let anth = openai_to_anthropic_response(&resp, "claude-sonnet-4-6");
        assert_eq!(anth.created, None);
        // Verify None created is omitted from JSON
        let json = serde_json::to_string(&anth).unwrap();
        assert!(!json.contains("\"created\""));
    }

    #[test]
    fn thinking_config_stripped_in_translation() {
        let mut req = basic_request();
        req.thinking = Some(anthropic::ThinkingConfig::Enabled {
            budget_tokens: 4096,
        });
        let oai = anthropic_to_openai_request(&req);
        // Thinking has no OpenAI equivalent; verify translation succeeds
        // and the OpenAI request has no thinking field (it's not in the struct)
        assert_eq!(oai.max_completion_tokens, Some(1024));
    }

    #[test]
    fn thinking_block_mapped_to_reasoning_content_in_assistant_translation() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::Assistant,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::Thinking {
                    thinking: "Let me reason...".into(),
                    signature: Some("sig_abc".into()),
                },
                anthropic::ContentBlock::Text {
                    text: "Here is my answer.".into(),
                },
            ]),
        }];

        let oai = anthropic_to_openai_request(&req);

        // Thinking block mapped to reasoning_content, text block preserved
        assert_eq!(oai.messages.len(), 1);
        assert_eq!(
            oai.messages[0].reasoning_content.as_deref(),
            Some("Let me reason...")
        );
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "Here is my answer."
        ));
    }

    #[test]
    fn redacted_thinking_block_dropped_in_assistant_translation() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::Assistant,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::RedactedThinking {
                    data: "encrypted_data".into(),
                },
                anthropic::ContentBlock::Text {
                    text: "My answer.".into(),
                },
            ]),
        }];

        let oai = anthropic_to_openai_request(&req);

        // RedactedThinking block dropped, text block preserved
        assert_eq!(oai.messages.len(), 1);
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "My answer."
        ));
    }

    #[test]
    fn temperature_clamped_to_zero_one() {
        let mut req = basic_request();
        req.temperature = Some(1.5);
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.temperature, Some(1.0));

        req.temperature = Some(0.5);
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.temperature, Some(0.5));

        req.temperature = Some(-0.1);
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.temperature, Some(0.0));

        req.temperature = None;
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.temperature.is_none());
    }

    #[test]
    fn metadata_user_id_maps_to_openai_user() {
        let mut req = basic_request();
        req.metadata = Some(anthropic::messages::Metadata {
            user_id: Some("u-abc123".into()),
        });
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.user.as_deref(), Some("u-abc123"));

        // No metadata: user is None
        req.metadata = None;
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.user.is_none());
    }

    // --- Claude Code parallel tool use ---

    #[test]
    fn claude_code_parallel_tool_use_request() {
        // Assistant message with 2 tool_use blocks -> OpenAI message with 2 tool_calls
        let mut req = basic_request();
        req.messages = vec![
            anthropic::InputMessage {
                role: anthropic::Role::User,
                content: anthropic::Content::Text("Read config and list tests.".into()),
            },
            anthropic::InputMessage {
                role: anthropic::Role::Assistant,
                content: anthropic::Content::Blocks(vec![
                    anthropic::ContentBlock::Text {
                        text: "I'll do both.".into(),
                    },
                    anthropic::ContentBlock::ToolUse {
                        id: "toolu_01A".into(),
                        name: "Read".into(),
                        input: json!({"file_path": "/config.toml"}),
                    },
                    anthropic::ContentBlock::ToolUse {
                        id: "toolu_01B".into(),
                        name: "Glob".into(),
                        input: json!({"pattern": "**/*test*"}),
                    },
                ]),
            },
        ];
        let oai = anthropic_to_openai_request(&req);
        // Should produce: user msg, assistant msg with tool_calls
        let assistant_msg = &oai.messages[1];
        assert_eq!(assistant_msg.role, openai::ChatRole::Assistant);
        match assistant_msg.content.as_ref().unwrap() {
            openai::ChatContent::Text(t) => assert_eq!(t, "I'll do both."),
            other => panic!("expected Text content, got {:?}", other),
        }
        let tool_calls = assistant_msg.tool_calls.as_ref().unwrap();
        assert_eq!(tool_calls.len(), 2);
        assert_eq!(tool_calls[0].id, "toolu_01A");
        assert_eq!(tool_calls[0].function.name, "Read");
        assert_eq!(tool_calls[1].id, "toolu_01B");
        assert_eq!(tool_calls[1].function.name, "Glob");
    }

    #[test]
    fn claude_code_tool_result_request() {
        // User message with tool_result blocks -> OpenAI tool-role messages
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::ToolResult {
                    tool_use_id: "toolu_01A".into(),
                    content: Some(anthropic::messages::ToolResultContent::Text(
                        "file contents here".into(),
                    )),
                    is_error: Some(false),
                },
                anthropic::ContentBlock::ToolResult {
                    tool_use_id: "toolu_01B".into(),
                    content: Some(anthropic::messages::ToolResultContent::Text(
                        "test1.rs\ntest2.rs".into(),
                    )),
                    is_error: Some(false),
                },
            ]),
        }];
        let oai = anthropic_to_openai_request(&req);
        // Should produce 2 tool-role messages
        assert_eq!(oai.messages.len(), 2);
        assert_eq!(oai.messages[0].role, openai::ChatRole::Tool);
        assert_eq!(oai.messages[0].tool_call_id.as_deref(), Some("toolu_01A"));
        assert_eq!(oai.messages[1].role, openai::ChatRole::Tool);
        assert_eq!(oai.messages[1].tool_call_id.as_deref(), Some("toolu_01B"));
    }

    #[test]
    fn claude_code_tool_response_roundtrip() {
        // OpenAI tool_call response -> Anthropic tool_use, verify fields survive
        let resp = openai::ChatCompletionResponse {
            id: "chatcmpl-llama001".into(),
            object: "chat.completion".into(),
            model: "llama-3.3-70b".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text("Reading file.".into())),
                    name: None,
                    tool_calls: Some(vec![
                        openai::ToolCall {
                            id: "call_read_001".into(),
                            call_type: "function".into(),
                            function: openai::FunctionCall {
                                name: "Read".into(),
                                arguments: r#"{"file_path":"/config.toml"}"#.into(),
                            },
                        },
                        openai::ToolCall {
                            id: "call_glob_001".into(),
                            call_type: "function".into(),
                            function: openai::FunctionCall {
                                name: "Glob".into(),
                                arguments: r#"{"pattern":"**/*test*"}"#.into(),
                            },
                        },
                    ]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: Some(openai::ChatUsage {
                prompt_tokens: 100,
                completion_tokens: 50,
                total_tokens: 150,
                completion_tokens_details: None,
                prompt_tokens_details: None,
            }),
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "claude-sonnet-4-20250514");
        assert_eq!(anth.stop_reason, Some(anthropic::StopReason::ToolUse));
        // First block is text
        match &anth.content[0] {
            anthropic::ContentBlock::Text { text } => assert_eq!(text, "Reading file."),
            other => panic!("expected Text, got {:?}", other),
        }
        // Second and third blocks are tool_use
        match &anth.content[1] {
            anthropic::ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call_read_001");
                assert_eq!(name, "Read");
                assert_eq!(input["file_path"], "/config.toml");
            }
            other => panic!("expected ToolUse, got {:?}", other),
        }
        match &anth.content[2] {
            anthropic::ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "call_glob_001");
                assert_eq!(name, "Glob");
                assert_eq!(input["pattern"], "**/*test*");
            }
            other => panic!("expected ToolUse, got {:?}", other),
        }
    }

    // --- Local LLM robustness ---

    #[test]
    fn tool_call_empty_id_gets_synthetic_id() {
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "llama".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: None,
                    name: None,
                    tool_calls: Some(vec![openai::ToolCall {
                        id: "".into(), // empty ID from local LLM
                        call_type: "function".into(),
                        function: openai::FunctionCall {
                            name: "Read".into(),
                            arguments: r#"{"file_path":"/tmp/x"}"#.into(),
                        },
                    }]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        match &anth.content[0] {
            anthropic::ContentBlock::ToolUse { id, name, .. } => {
                assert!(
                    id.starts_with("toolu_"),
                    "expected synthetic toolu_ ID, got: {}",
                    id
                );
                assert_eq!(name, "Read");
            }
            other => panic!("expected ToolUse, got {:?}", other),
        }
    }

    #[test]
    fn tool_call_empty_arguments_becomes_empty_object() {
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "llama".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: None,
                    name: None,
                    tool_calls: Some(vec![openai::ToolCall {
                        id: "call_1".into(),
                        call_type: "function".into(),
                        function: openai::FunctionCall {
                            name: "Bash".into(),
                            arguments: "".into(), // empty args from local LLM
                        },
                    }]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        match &anth.content[0] {
            anthropic::ContentBlock::ToolUse { input, .. } => {
                assert_eq!(input, &json!({}));
            }
            other => panic!("expected ToolUse, got {:?}", other),
        }
    }

    #[test]
    fn tool_call_missing_name_skipped() {
        let resp = openai::ChatCompletionResponse {
            id: "x".into(),
            object: "chat.completion".into(),
            model: "llama".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text("text".into())),
                    name: None,
                    tool_calls: Some(vec![
                        openai::ToolCall {
                            id: "call_1".into(),
                            call_type: "function".into(),
                            function: openai::FunctionCall {
                                name: "".into(), // empty name
                                arguments: "{}".into(),
                            },
                        },
                        openai::ToolCall {
                            id: "call_2".into(),
                            call_type: "function".into(),
                            function: openai::FunctionCall {
                                name: "Read".into(),
                                arguments: r#"{"file_path":"/x"}"#.into(),
                            },
                        },
                    ]),
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ToolCalls),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        // Empty-name tool call skipped; text + valid tool call remain
        assert_eq!(anth.content.len(), 2);
        match &anth.content[0] {
            anthropic::ContentBlock::Text { text } => assert_eq!(text, "text"),
            other => panic!("expected Text, got {:?}", other),
        }
        match &anth.content[1] {
            anthropic::ContentBlock::ToolUse { name, .. } => assert_eq!(name, "Read"),
            other => panic!("expected ToolUse, got {:?}", other),
        }
    }

    #[test]
    fn refusal_mapped_to_text_block() {
        let resp = openai::ChatCompletionResponse {
            id: "chatcmpl-1".into(),
            object: "chat.completion".into(),
            model: "gpt-4o".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: None,
                    name: None,
                    tool_calls: None,
                    tool_call_id: None,
                    refusal: Some("I cannot help with that request.".into()),
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::ContentFilter),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };

        let anth = openai_to_anthropic_response(&resp, "m");
        assert_eq!(anth.content.len(), 1);
        match &anth.content[0] {
            anthropic::ContentBlock::Text { text } => {
                assert!(text.contains("Refusal"));
                assert!(text.contains("I cannot help with that request."));
            }
            other => panic!("expected Text with refusal, got {:?}", other),
        }
    }

    #[test]
    fn extra_fields_forwarded_to_openai_request() {
        let mut req = basic_request();
        req.extra
            .insert("seed".into(), serde_json::Value::Number(42.into()));
        req.extra
            .insert("logprobs".into(), serde_json::Value::Bool(true));

        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.extra.get("seed"), Some(&json!(42)));
        assert_eq!(oai.extra.get("logprobs"), Some(&json!(true)));
    }

    #[test]
    fn n_parameter_stripped_from_extra() {
        let mut req = basic_request();
        req.extra.insert("n".into(), json!(4));
        req.extra.insert("seed".into(), json!(42));
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.extra.get("n").is_none());
        assert_eq!(oai.extra.get("seed"), Some(&json!(42)));
    }

    #[test]
    fn n_parameter_one_stripped_silently() {
        let mut req = basic_request();
        req.extra.insert("n".into(), json!(1));
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.extra.get("n").is_none());
    }

    #[test]
    fn reasoning_content_mapped_to_thinking_block_in_response() {
        let oai_resp = openai::ChatCompletionResponse {
            id: "chatcmpl-1".into(),
            object: "chat.completion".into(),
            model: "deepseek-reasoner".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text("The answer is 4.".into())),
                    name: None,
                    tool_calls: None,
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: Some("Let me think... 2+2=4".into()),
                },
                finish_reason: Some(openai::FinishReason::Stop),
                logprobs: None,
            }],
            usage: Some(openai::ChatUsage {
                prompt_tokens: 10,
                completion_tokens: 20,
                total_tokens: 30,
                completion_tokens_details: None,
                prompt_tokens_details: None,
            }),
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };
        let resp = openai_to_anthropic_response(&oai_resp, "deepseek-reasoner");
        // First block should be thinking, second should be text
        assert_eq!(resp.content.len(), 2);
        match &resp.content[0] {
            anthropic::ContentBlock::Thinking {
                thinking,
                signature,
            } => {
                assert_eq!(thinking, "Let me think... 2+2=4");
                assert!(signature.is_none());
            }
            other => panic!("expected Thinking block, got {:?}", other),
        }
        match &resp.content[1] {
            anthropic::ContentBlock::Text { text } => {
                assert_eq!(text, "The answer is 4.");
            }
            other => panic!("expected Text block, got {:?}", other),
        }
    }

    #[test]
    fn thinking_block_mapped_to_reasoning_content_in_request() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::Assistant,
            content: anthropic::Content::Blocks(vec![
                anthropic::ContentBlock::Thinking {
                    thinking: "Let me reason...".into(),
                    signature: Some("sig_abc".into()),
                },
                anthropic::ContentBlock::Text {
                    text: "Here is my answer.".into(),
                },
            ]),
        }];

        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.messages.len(), 1);
        assert_eq!(
            oai.messages[0].reasoning_content.as_deref(),
            Some("Let me reason...")
        );
        assert!(matches!(
            &oai.messages[0].content,
            Some(openai::ChatContent::Text(t)) if t == "Here is my answer."
        ));
    }

    #[test]
    fn unknown_finish_reason_maps_to_end_turn() {
        let oai_resp = openai::ChatCompletionResponse {
            id: "chatcmpl-1".into(),
            object: "chat.completion".into(),
            model: "deepseek-chat".into(),
            choices: vec![openai::Choice {
                index: 0,
                message: openai::ChatMessage {
                    role: openai::ChatRole::Assistant,
                    content: Some(openai::ChatContent::Text("Sorry".into())),
                    name: None,
                    tool_calls: None,
                    tool_call_id: None,
                    refusal: None,
                    reasoning_content: None,
                },
                finish_reason: Some(openai::FinishReason::Unknown),
                logprobs: None,
            }],
            usage: None,
            created: None,
            system_fingerprint: None,
            service_tier: None,
        };
        let resp = openai_to_anthropic_response(&oai_resp, "deepseek-chat");
        assert_eq!(resp.stop_reason, Some(anthropic::StopReason::EndTurn));
    }

    #[test]
    fn is_o_series_model_matches() {
        assert!(is_o_series_model("o1"));
        assert!(is_o_series_model("o3"));
        assert!(is_o_series_model("o4"));
        assert!(is_o_series_model("o1-mini"));
        assert!(is_o_series_model("o1-preview"));
        assert!(is_o_series_model("o3-mini"));
        assert!(is_o_series_model("o4-mini"));
        assert!(is_o_series_model("O1")); // case-insensitive
        assert!(is_o_series_model("O3-Mini"));
    }

    #[test]
    fn is_o_series_model_rejects() {
        assert!(!is_o_series_model("gpt-4o"));
        assert!(!is_o_series_model("gpt-4o-mini"));
        assert!(!is_o_series_model("gpt-4"));
        assert!(!is_o_series_model("claude-3-opus"));
    }

    #[test]
    fn is_o_series_model_future_models() {
        assert!(is_o_series_model("o2"), "o2 must match");
        assert!(is_o_series_model("o5"), "o5 must match");
        assert!(is_o_series_model("o10"), "o10 (multi-digit) must match");
        assert!(is_o_series_model("o2-mini"), "o2-mini must match");
        assert!(
            !is_o_series_model("o-preview"),
            "bare 'o' with no digit must not match"
        );
        assert!(
            !is_o_series_model("openai-o1"),
            "o1 not at start must not match"
        );
    }

    fn make_request(model: &str, system: Option<&str>) -> anthropic::MessageCreateRequest {
        anthropic::MessageCreateRequest {
            model: model.into(),
            max_tokens: 1024,
            messages: vec![],
            system: system.map(|s| anthropic::System::Text(s.into())),
            temperature: None,
            top_p: None,
            top_k: None,
            stop_sequences: None,
            tools: None,
            tool_choice: None,
            metadata: None,
            thinking: None,
            stream: None,
            extra: serde_json::Map::new(),
        }
    }

    #[test]
    fn o_series_model_gets_only_max_completion_tokens() {
        let req = make_request("o1-mini", Some("You are helpful."));
        let oai = anthropic_to_openai_request(&req);
        assert!(
            oai.max_tokens.is_none(),
            "o-series should not set max_tokens"
        );
        assert_eq!(oai.max_completion_tokens, Some(1024));
        // System role should be converted to Developer for o-series.
        assert_eq!(oai.messages[0].role, openai::ChatRole::Developer);
    }

    #[test]
    fn non_o_series_model_gets_both_max_tokens() {
        let req = make_request("gpt-4o", Some("You are helpful."));
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.max_tokens, Some(1024));
        assert_eq!(oai.max_completion_tokens, Some(1024));
        // System role should remain System for non-o-series.
        assert_eq!(oai.messages[0].role, openai::ChatRole::System);
    }

    #[test]
    fn o_series_ga_strips_temperature() {
        // All o-series models (including GA variants like o3-mini) reject temperature.
        let mut req = make_request("o3-mini", None);
        req.temperature = Some(0.7);
        let oai = anthropic_to_openai_request(&req);
        assert!(
            oai.temperature.is_none(),
            "o3-mini should strip temperature (all o-series reject it)"
        );
    }

    #[test]
    fn o_series_preview_strips_temperature() {
        // All o-series models including early previews do not support temperature.
        let mut req = make_request("o1-preview", None);
        req.temperature = Some(0.7);
        let oai = anthropic_to_openai_request(&req);
        assert!(
            oai.temperature.is_none(),
            "o1-preview should strip temperature"
        );
    }

    #[test]
    fn o_series_preview_strips_top_p() {
        let mut req = make_request("o1-preview", None);
        req.top_p = Some(0.9);
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.top_p.is_none(), "o1-preview should strip top_p");
    }

    #[test]
    fn o1_mini_strips_top_p() {
        let mut req = make_request("o1-mini", None);
        req.top_p = Some(0.9);
        let oai = anthropic_to_openai_request(&req);
        assert!(oai.top_p.is_none(), "o1-mini should strip top_p");
    }

    #[test]
    fn non_o_series_preserves_temperature() {
        let mut req = make_request("gpt-4o", None);
        req.temperature = Some(0.7);
        let oai = anthropic_to_openai_request(&req);
        assert_eq!(oai.temperature, Some(0.7));
    }

    // --- compute_request_warnings ---

    #[test]
    fn warnings_empty_for_plain_request() {
        let req = basic_request();
        let w = compute_request_warnings(&req);
        assert!(w.is_empty());
        assert!(w.as_header_value().is_none());
    }

    #[test]
    fn warnings_top_k() {
        let mut req = basic_request();
        req.top_k = Some(40);
        let w = compute_request_warnings(&req);
        assert_eq!(w.as_header_value().unwrap(), "top_k");
    }

    #[test]
    fn warnings_thinking_config() {
        let mut req = basic_request();
        req.thinking = Some(anthropic::ThinkingConfig::Enabled {
            budget_tokens: 5000,
        });
        let w = compute_request_warnings(&req);
        assert_eq!(w.as_header_value().unwrap(), "thinking_config");
    }

    #[test]
    fn warnings_stop_sequences_truncated_at_5() {
        let mut req = basic_request();
        req.stop_sequences = Some(vec![
            "a".to_string(),
            "b".to_string(),
            "c".to_string(),
            "d".to_string(),
            "e".to_string(),
        ]);
        let w = compute_request_warnings(&req);
        assert_eq!(w.as_header_value().unwrap(), "stop_sequences_truncated");
    }

    #[test]
    fn warnings_stop_sequences_4_is_fine() {
        let mut req = basic_request();
        req.stop_sequences = Some(vec![
            "a".to_string(),
            "b".to_string(),
            "c".to_string(),
            "d".to_string(),
        ]);
        let w = compute_request_warnings(&req);
        assert!(w.is_empty());
    }

    #[test]
    fn warnings_cache_control_on_system() {
        let mut req = basic_request();
        req.system = Some(anthropic::System::Blocks(vec![anthropic::SystemBlock {
            block_type: "text".to_string(),
            text: "You are helpful.".to_string(),
            cache_control: Some(anthropic::CacheControl {
                cache_type: "ephemeral".to_string(),
            }),
        }]));
        let w = compute_request_warnings(&req);
        assert_eq!(w.as_header_value().unwrap(), "cache_control");
    }

    #[test]
    fn warnings_document_blocks() {
        let mut req = basic_request();
        req.messages = vec![anthropic::InputMessage {
            role: anthropic::Role::User,
            content: anthropic::Content::Blocks(vec![anthropic::ContentBlock::Document {
                source: anthropic::DocumentSource {
                    source_type: "base64".to_string(),
                    media_type: "application/pdf".to_string(),
                    data: "dGVzdA==".to_string(),
                },
                title: None,
            }]),
        }];
        let w = compute_request_warnings(&req);
        assert_eq!(w.as_header_value().unwrap(), "document_blocks");
    }

    #[test]
    fn warnings_multiple_combined() {
        let mut req = basic_request();
        req.top_k = Some(10);
        req.thinking = Some(anthropic::ThinkingConfig::Enabled {
            budget_tokens: 1000,
        });
        let w = compute_request_warnings(&req);
        let val = w.as_header_value().unwrap();
        assert!(val.contains("top_k"), "missing top_k in: {val}");
        assert!(
            val.contains("thinking_config"),
            "missing thinking_config in: {val}"
        );
    }

    #[test]
    fn forced_tool_choice_enables_strict_mode_in_openai_request() {
        let anthropic_req: anthropic::MessageCreateRequest =
            serde_json::from_value(serde_json::json!({
                "model": "claude-3-5-sonnet-20241022",
                "max_tokens": 100,
                "messages": [{"role": "user", "content": "Extract the data"}],
                "tools": [{
                    "name": "extract_data",
                    "description": "Extract structured data",
                    "input_schema": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"},
                            "value": {"type": "integer"}
                        }
                    }
                }],
                "tool_choice": {"type": "tool", "name": "extract_data"}
            }))
            .unwrap();

        let openai_req = anthropic_to_openai_request(&anthropic_req);

        let tools = openai_req.tools.expect("tools should be present");
        assert_eq!(tools.len(), 1);

        // The tool should have strict: true.
        assert_eq!(tools[0].function.strict, Some(true));

        // The schema should have additionalProperties: false.
        let params = tools[0]
            .function
            .parameters
            .as_ref()
            .expect("parameters should be present");
        assert_eq!(params["additionalProperties"], serde_json::json!(false));

        // required should include both properties.
        let required = params["required"]
            .as_array()
            .expect("required should be present");
        assert!(required.iter().any(|v| v == "name"));
        assert!(required.iter().any(|v| v == "value"));
    }
}