dynamo-renderer 5.1.0

Standalone OpenAI chat-template / prompt formatting (HF chat_template via minijinja).
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
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::*;

use crate::{OAIChatLikeRequest, TextInput};
use minijinja::{context, value::Value};
use std::result::Result::Ok;

/// Fix a tool schema that is missing `type`/`properties`. `pub` so consumers
/// can normalize their own `tools` value when implementing
/// [`crate::OAIChatLikeRequest::tools`].
pub fn may_be_fix_tool_schema(tools: serde_json::Value) -> Option<Value> {
    // No need to validate or enforce other schema checks as the basic Named function schema is already validated while creating the request.
    // Empty parameters is allowed by OpenAI at request level. Need to enforce it at template level.
    // Whenever parameters is empty, insert "type": "object" and "properties": {}
    let mut updated_tools = Vec::new();
    if let Some(arr) = tools.as_array() {
        for tool in arr {
            let mut tool = tool.clone();
            if let Some(function) = tool.get_mut("function") {
                // Backfill a missing/null `description`. It's optional in the
                // OpenAI tool schema, but some chat templates (e.g. gpt-oss
                // harmony) concatenate it unconditionally and fail on an
                // `undefined`/null value.
                if let Some(obj) = function.as_object_mut()
                    && !matches!(obj.get("description"), Some(serde_json::Value::String(_)))
                {
                    obj.insert(
                        "description".to_string(),
                        serde_json::Value::String(String::new()),
                    );
                }
            }
            if let Some(function) = tool.get_mut("function")
                && let Some(parameters) = function.get_mut("parameters")
            {
                // Only operate if parameters is an object
                if parameters.is_object() {
                    let mut needs_type = false;
                    let mut needs_properties = false;
                    let is_empty = parameters
                        .as_object()
                        .map(|o| o.is_empty())
                        .unwrap_or(false);

                    // If empty, we need to insert both
                    if is_empty {
                        needs_type = true;
                        needs_properties = true;
                    } else {
                        // If not empty, check if type/properties are missing
                        if let Some(obj) = parameters.as_object() {
                            if !obj.contains_key("type") {
                                needs_type = true;
                            }
                            if !obj.contains_key("properties") {
                                needs_properties = true;
                            }
                        }
                    }

                    if (needs_type || needs_properties)
                        && let Some(obj) = parameters.as_object_mut()
                    {
                        if needs_type {
                            obj.insert(
                                "type".to_string(),
                                serde_json::Value::String("object".to_string()),
                            );
                        }
                        if needs_properties {
                            obj.insert(
                                "properties".to_string(),
                                serde_json::Value::Object(Default::default()),
                            );
                        }
                    }
                }
            }
            updated_tools.push(tool);
        }
    }
    Some(Value::from_serialize(&updated_tools))
}

/// Default media type conversions for multimodal content.
/// Maps source types (e.g., "image_url") to target placeholder types (e.g., "image").
const DEFAULT_MEDIA_TYPE_CONVERSIONS: &[(&str, &str)] = &[
    ("image_url", "image"),
    ("video_url", "video"),
    ("audio_url", "audio"),
];

/// Convert media URL content parts to empty placeholder types.
fn convert_media_url_to_placeholder(
    content_array: &[serde_json::Value],
    conversions: &[(&str, &str)],
) -> Vec<serde_json::Value> {
    content_array
        .iter()
        .map(|part| {
            let part_type = part.get("type").and_then(|t| t.as_str()).unwrap_or("");

            if let Some((_, target_type)) = conversions.iter().find(|(src, _)| *src == part_type) {
                serde_json::json!({"type": target_type})
            } else {
                part.clone()
            }
        })
        .collect()
}

fn may_be_fix_msg_content(
    messages: serde_json::Value,
    preserve_arrays: bool,
    image_placeholder_template: Option<&str>,
) -> Value {
    // preserve_arrays=true: strings → arrays (multimodal)
    // preserve_arrays=false: text-only arrays → strings (standard)
    // image_placeholder_template: when `preserve_arrays=false` and the array
    // mixes text + image parts, this template (e.g. `<|image_{n}|>`) lets us
    // flatten by substituting image parts with model-family placeholders
    // instead of leaving the raw array for the template, which would crash
    // string-content templates like Phi-3-vision's `'+' message.content`.

    let Some(arr) = messages.as_array() else {
        return Value::from_serialize(&messages);
    };

    let updated_messages: Vec<_> = arr
        .iter()
        .map(|msg| {
            match msg.get("content") {
                // Case 1: String to Array (for multimodal templates)
                Some(serde_json::Value::String(text)) if preserve_arrays => {
                    let mut modified_msg = msg.clone();
                    if let Some(msg_object) = modified_msg.as_object_mut() {
                        let content_array = serde_json::json!([{
                            "type": "text",
                            "text": text
                        }]);
                        msg_object.insert("content".to_string(), content_array);
                    }
                    modified_msg
                }
                // Case 2: Array processing
                Some(serde_json::Value::Array(content_array)) => {
                    // First, convert any media URL parts to placeholders (e.g., image_url → image)
                    let content_array = convert_media_url_to_placeholder(
                        content_array,
                        DEFAULT_MEDIA_TYPE_CONVERSIONS,
                    );

                    // Check if it's text-only (after media URL conversion)
                    let is_text_only_array = !content_array.is_empty()
                        && content_array.iter().all(|part| {
                            part.get("type")
                                .and_then(|type_field| type_field.as_str())
                                .map(|type_str| type_str == "text")
                                .unwrap_or(false)
                        });

                    let mut modified_msg = msg.clone();
                    if let Some(msg_object) = modified_msg.as_object_mut() {
                        if is_text_only_array && !preserve_arrays {
                            // Flatten text-only arrays to string for standard templates
                            let text_parts: Vec<&str> = content_array
                                .iter()
                                .filter_map(|part| part.get("text")?.as_str())
                                .collect();
                            let concatenated_text = text_parts.join("\n");
                            msg_object.insert(
                                "content".to_string(),
                                serde_json::Value::String(concatenated_text),
                            );
                        } else if !preserve_arrays
                            && !content_array.is_empty()
                            && let Some(placeholder_tpl) = image_placeholder_template
                        {
                            // Mixed text+image array for a string-content
                            // template — flatten with model-family image
                            // placeholders inlined where the image parts were.
                            // An empty `placeholder_tpl` ("") drops the image
                            // parts entirely while keeping the text — used by
                            // pure pass-through / encoder-decoder templates
                            // (Nemotron-Parse) whose vision encoder consumes the
                            // image out-of-band, so no text token represents it.
                            // The `is_empty` guard preserves a literal `[]`
                            // content (matches pre-PR behavior); flattening
                            // an empty array to `""` would silently change
                            // what the template renders.
                            let flattened = flatten_mixed_content(&content_array, placeholder_tpl);
                            msg_object.insert(
                                "content".to_string(),
                                serde_json::Value::String(flattened),
                            );
                        } else {
                            // Keep as array (with media_url → media placeholder conversion applied)
                            msg_object.insert(
                                "content".to_string(),
                                serde_json::Value::Array(content_array),
                            );
                        }
                    }
                    modified_msg
                }
                _ => msg.clone(), // No conversion needed
            }
        })
        .collect();

    Value::from_serialize(&updated_messages)
}

/// Concatenate a mixed-content array (text parts + image placeholders) into a
/// single string. Text parts contribute their `text` field as-is; non-text
/// parts (image, video, audio after the URL→placeholder conversion in
/// `convert_media_url_to_placeholder`) emit the per-family placeholder with
/// `{n}` substituted by the 1-based index of the image in the message.
///
/// Used in `may_be_fix_msg_content` when `preserve_arrays=false` and the
/// template knows a placeholder convention — currently Phi-3-vision
/// (`<|image_{n}|>`), LLaVA-1.5 (`<image>`), and pure pass-through /
/// encoder-decoder templates (`""`, image emits nothing — Nemotron-Parse).
/// With an empty `placeholder_tpl` the non-text parts contribute no characters,
/// so the result is the concatenated text parts only.
///
/// **Caveat — non-text index slot:** `img_idx` increments for every non-text
/// part, not just images. The current supported families (Phi-3, LLaVA-1.5)
/// are image-only so there's no collision today, but a future image+video
/// family would silently consume an image-index slot for each video/audio
/// part and emit the image placeholder there. When adding a family that
/// mixes modalities in one message, either:
///   1. expand this function with per-modality placeholder strings, or
///   2. assert in `convert_media_url_to_placeholder` that only "image"
///      placeholders reach this path.
fn flatten_mixed_content(parts: &[serde_json::Value], placeholder_tpl: &str) -> String {
    let mut out = String::new();
    let mut img_idx: u32 = 1;
    for part in parts {
        let type_str = part.get("type").and_then(|t| t.as_str()).unwrap_or("");
        if type_str == "text" {
            if let Some(text) = part.get("text").and_then(|t| t.as_str()) {
                out.push_str(text);
            }
        } else if !type_str.is_empty() {
            let placeholder = placeholder_tpl.replace("{n}", &img_idx.to_string());
            out.push_str(&placeholder);
            img_idx += 1;
        }
    }
    out
}

fn normalize_tool_calls_arguments_in_messages(messages: &mut serde_json::Value) {
    // Deserialize `tool_calls[].function.arguments` from JSON strings to
    // objects/arrays before template rendering — avoids double encoding
    // and enables iteration. Skipped for templates whose own `is string`
    // branch wants the raw string verbatim (see render()).
    let Some(msgs) = messages.as_array_mut() else {
        return;
    };

    for msg in msgs.iter_mut() {
        if let Some(tool_calls) = msg.get_mut("tool_calls").and_then(|v| v.as_array_mut()) {
            for tc in tool_calls {
                if let Some(function) = tc.get_mut("function").and_then(|v| v.as_object_mut())
                    && let Some(args) = function.get_mut("arguments")
                    && let Some(s) = args.as_str()
                    && let Ok(parsed) = serde_json::from_str(s)
                {
                    *args = parsed;
                }
            }
        }
    }
}

fn normalize_function_call_arguments_in_messages(messages: &mut serde_json::Value) {
    // Legacy (deprecated) OpenAI `function_call.arguments` path. Kept separate
    // from `tool_calls` normalization so the per-template `arguments is string`
    // opt-out — which only refers to `tool_call.arguments` inside the
    // tool_calls loop — does not accidentally suppress this path.
    let Some(msgs) = messages.as_array_mut() else {
        return;
    };

    for msg in msgs.iter_mut() {
        if let Some(function_call) = msg.get_mut("function_call").and_then(|v| v.as_object_mut())
            && let Some(args) = function_call.get_mut("arguments")
            && let Some(s) = args.as_str()
            && let Ok(parsed) = serde_json::from_str(s)
        {
            *args = parsed;
        }
    }
}

/// Inject `reasoning_content` back into the `content` field as `<think>` blocks.
///
/// Chat templates only reference `{{ message.content }}` — they don't know about
/// `reasoning_content`. Without this injection, the model's prior chain-of-thought
/// is silently dropped across turns.
///
/// Uses `<think>`/`</think>` delimiters — the same tags that reasoning models emit
/// and that the reasoning parser strips on output. Reasoning is prepended to content
/// to match the original generation order (`<think>...</think> response`).
///
/// Segments are concatenated rather than interleaved with tool_calls because Jinja
/// templates render `tool_calls` separately from `content`. The model still sees
/// all reasoning text before the template-rendered tool call block.
fn inject_reasoning_content_into_messages(messages: &mut serde_json::Value) {
    let Some(msgs) = messages.as_array_mut() else {
        return;
    };

    for msg in msgs.iter_mut() {
        if msg.get("role").and_then(|r| r.as_str()) != Some("assistant") {
            continue;
        }

        let reasoning = match msg.get("reasoning_content") {
            Some(serde_json::Value::String(s)) if !s.is_empty() => {
                format!("<think>{}</think>", s)
            }
            Some(serde_json::Value::Array(segments)) => {
                let mut result = String::new();
                for seg in segments {
                    if let Some(s) = seg.as_str()
                        && !s.is_empty()
                    {
                        result.push_str("<think>");
                        result.push_str(s);
                        result.push_str("</think>");
                    }
                }
                if result.is_empty() {
                    continue;
                }
                result
            }
            _ => continue,
        };

        match msg.get("content") {
            // Content is a string or null — prepend reasoning as text
            Some(serde_json::Value::String(s)) if !s.is_empty() => {
                msg["content"] = serde_json::Value::String(format!("{}{}", reasoning, s));
            }
            None | Some(serde_json::Value::Null) | Some(serde_json::Value::String(_)) => {
                msg["content"] = serde_json::Value::String(reasoning);
            }
            // Content is an array (multimodal) — prepend as a text part
            Some(serde_json::Value::Array(_)) => {
                let think_part = serde_json::json!({
                    "type": "text",
                    "text": reasoning
                });
                if let Some(arr) = msg.get_mut("content").and_then(|v| v.as_array_mut()) {
                    arr.insert(0, think_part);
                }
            }
            // Other types (number, bool, object) — skip, don't corrupt
            _ => continue,
        }

        // Remove so the template doesn't see both the injected <think> in content
        // and the original reasoning_content field.
        if let Some(obj) = msg.as_object_mut() {
            obj.remove("reasoning_content");
        }
    }
}

/// Default [`OAIChatLikeRequest`] impl for the bare `dynamo-protocols` chat
/// request. Lets any consumer (e.g. a standalone OpenAI frontend over an
/// engine) render HF chat templates directly from the wire type, without
/// defining their own wrapper. Consumers with extra fields (Dynamo's
/// `NvCreateChatCompletionRequest`) provide their own impl.
impl OAIChatLikeRequest for dynamo_protocols::types::CreateChatCompletionRequest {
    fn model(&self) -> String {
        self.model.clone()
    }

    fn messages(&self) -> Value {
        let messages_json = serde_json::to_value(&self.messages).unwrap();
        Value::from_serialize(&messages_json)
    }

    fn typed_messages(&self) -> Option<&[dynamo_protocols::types::ChatCompletionRequestMessage]> {
        Some(self.messages.as_slice())
    }

    fn tools(&self) -> Option<Value> {
        if self.tools.is_none() {
            None
        } else {
            Some(may_be_fix_tool_schema(
                serde_json::to_value(&self.tools).unwrap(),
            )?)
        }
    }

    fn tool_choice(&self) -> Option<Value> {
        if self.tool_choice.is_none() {
            None
        } else {
            Some(Value::from_serialize(&self.tool_choice))
        }
    }

    fn response_format(&self) -> Option<Value> {
        self.response_format.as_ref().map(Value::from_serialize)
    }

    fn reasoning_effort(&self) -> Option<Value> {
        self.reasoning_effort.as_ref().map(Value::from_serialize)
    }

    fn should_add_generation_prompt(&self) -> bool {
        // Using vLLM default behavior
        true
    }

    fn extract_text(&self) -> Option<TextInput> {
        Some(TextInput::Single(String::new()))
    }

    fn mm_processor_kwargs(&self) -> Option<&serde_json::Value> {
        self.mm_processor_kwargs.as_ref()
    }
}

impl OAIPromptFormatter for HfTokenizerConfigJsonFormatter {
    fn supports_add_generation_prompt(&self) -> bool {
        self.supports_add_generation_prompt
    }

    fn render(&self, req: &dyn OAIChatLikeRequest) -> Result<String> {
        let mixins = Value::from_dyn_object(self.mixins.clone());

        let tools = req.tools();
        // Strip tools when tool_choice is "none" and the flag is enabled, so the model
        // doesn't see tool definitions and generate raw XML tool calls in its response.
        let tools = if self.exclude_tools_when_tool_choice_none {
            match req.tool_choice() {
                Some(ref tc) if tc.as_str() == Some("none") => None,
                _ => tools,
            }
        } else {
            tools
        };
        // has_tools should be true if tools is a non-empty array
        let has_tools = tools.as_ref().and_then(|v| v.len()).is_some_and(|l| l > 0);
        let add_generation_prompt = req.should_add_generation_prompt();

        tracing::trace!(
            "Rendering prompt with tools: {:?}, add_generation_prompt: {}",
            has_tools,
            add_generation_prompt
        );

        let messages_canonical = req.messages();
        let mut messages_for_template: serde_json::Value =
            serde_json::to_value(&messages_canonical).unwrap();

        messages_for_template = serde_json::to_value(may_be_fix_msg_content(
            messages_for_template,
            self.requires_content_arrays,
            self.image_placeholder_template,
        ))
        .unwrap();

        // Pick the concrete template first so the normalization opt-out can be
        // template- and field-specific: only the chosen template's
        // `tool_call.arguments is string` flag should suppress normalization,
        // and only for the `tool_calls[].function.arguments` field. Legacy
        // `function_call.arguments` lives outside that branch and is always
        // normalized.
        let (template_name, template_handles_tool_calls_args_string, template_handles_reasoning) =
            if has_tools {
                (
                    "tool_use",
                    self.tool_use_template_handles_tool_calls_arguments_string,
                    self.tool_use_template_handles_reasoning,
                )
            } else {
                (
                    "default",
                    self.default_template_handles_tool_calls_arguments_string,
                    self.default_template_handles_reasoning,
                )
            };

        // Pre-parse JSON-string `arguments` into objects — but only for templates
        // that unconditionally `| tojson` them. Templates that branch on
        // `tool_call.arguments is string` (Qwen3, Hermes) want the raw string
        // verbatim so the rendered bytes match what the model emitted on the
        // prior turn. Re-serializing through minijinja's compact `tojson` here
        // breaks append-only prefix matching across multi-step tool use.
        if !template_handles_tool_calls_args_string {
            normalize_tool_calls_arguments_in_messages(&mut messages_for_template);
        }
        // Legacy `function_call.arguments` is always normalized — the
        // `arguments is string` opt-out only covers the modern `tool_calls`
        // branch.
        normalize_function_call_arguments_in_messages(&mut messages_for_template);

        // Inject reasoning_content as <think> blocks into content — but only if
        // the template doesn't handle it natively. Templates like Nemotron and
        // Qwen3 reference reasoning_content directly in their Jinja logic; injecting
        // would produce duplicate <think> blocks.
        if !template_handles_reasoning {
            inject_reasoning_content_into_messages(&mut messages_for_template);
        }

        let ctx = context! {
            messages => messages_for_template,
            tools => tools,
            bos_token => self.config.bos_tok(),
            eos_token => self.config.eos_tok(),
            unk_token => self.config.unk_tok(),
            add_generation_prompt => add_generation_prompt,
            ..mixins
        };

        // Merge any additional args into the context last so they take precedence
        let ctx = if let Some(args) = req.chat_template_args() {
            let extra = Value::from_serialize(args);
            context! { ..ctx, ..extra }
        } else {
            ctx
        };

        let tmpl: minijinja::Template<'_, '_> = self.env.get_template(template_name)?;
        Ok(tmpl.render(&ctx)?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dynamo_protocols::types::ChatCompletionRequestMessage as Msg;
    // The crate's renderer tests exercise the bare-protocol request type via the
    // default `OAIChatLikeRequest` impl above; Dynamo's `Nv*` wrapper lives in lib/llm.
    use dynamo_protocols::types::CreateChatCompletionRequest as NvCreateChatCompletionRequest;
    use minijinja::{Environment, context};

    /// End-to-end guard for the minijinja stack-overflow fix, exercised through
    /// Dynamo's real chat-template render path. A template that accumulates
    /// messages via `ns.items = ns.items + [m]` and then takes `|length`
    /// previously overflowed the native stack for long conversations (~1500+
    /// turns on a worker thread), core-dumping the frontend. Runs on a 2 MiB
    /// stack — the size of a Dynamo tokio worker thread — so a regression aborts
    /// deterministically instead of depending on the platform default.
    #[test]
    fn test_render_long_conversation_does_not_overflow_stack() {
        let handle = std::thread::Builder::new()
            .stack_size(2 * 1024 * 1024)
            .spawn(|| {
                let template_string = concat!(
                    "{%- set ns = namespace(items=[]) -%}",
                    "{%- for m in messages -%}",
                    "{%- set ns.items = ns.items + [m] -%}",
                    "{%- endfor -%}",
                    "COUNT={{ ns.items | length }}"
                );
                let chat_template: ChatTemplate =
                    serde_json::from_value(serde_json::json!({ "chat_template": template_string }))
                        .unwrap();
                let formatter =
                    HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[]))
                        .unwrap();

                let n = 3000;
                let messages: Vec<serde_json::Value> = (0..n)
                    .map(|i| serde_json::json!({"role": "user", "content": format!("turn {i}")}))
                    .collect();
                let request: NvCreateChatCompletionRequest =
                    serde_json::from_value(serde_json::json!({
                        "model": "test",
                        "messages": messages,
                    }))
                    .unwrap();

                // The crash path: `|length` -> minijinja `Value::len()`.
                let rendered = formatter.render(&request).unwrap();
                assert_eq!(rendered.trim(), format!("COUNT={n}"));
            })
            .unwrap();
        handle.join().unwrap();
    }

    /// Dev utility (ignored by default): dump the prompt Dynamo's renderer
    /// produces for a tool-calling chat request, so it can be diffed against
    /// vLLM's `openai_harmony` rendering — to see whether the gpt-oss Jinja
    /// `chat_template` actually emits the harmony "tool calls go to the
    /// commentary channel" guidance + `functions` namespace.
    ///
    /// Point GPTOSS_CHAT_TEMPLATE at the model's tokenizer_config.json (its
    /// `chat_template` field is extracted) OR a raw chat_template.jinja file:
    ///   GPTOSS_CHAT_TEMPLATE=/path/openai-gpt-oss-120b/tokenizer_config.json \
    ///     cargo test -p dynamo-renderer dump_gptoss_tool_prompt -- --ignored --nocapture
    #[test]
    #[ignore]
    fn dump_gptoss_tool_prompt() {
        use super::tokcfg::ChatTemplate;
        use super::{ContextMixins, HfTokenizerConfigJsonFormatter};

        let path = std::env::var("GPTOSS_CHAT_TEMPLATE").expect(
            "set GPTOSS_CHAT_TEMPLATE to the tokenizer_config.json, chat_template.jinja, or model dir path",
        );
        let input_path = std::path::Path::new(&path);
        let file_path = if input_path.is_dir() {
            // Prefer tokenizer_config.json from model dir if provided
            input_path.join("tokenizer_config.json")
        } else {
            input_path.to_path_buf()
        };
        let raw = std::fs::read_to_string(&file_path).expect("read chat template file");
        // Resolve the actual Jinja template. gpt-oss ships its chat template in a
        // separate `chat_template.jinja` file, NOT inside tokenizer_config.json,
        // so:
        //   * if the file is JSON with a `chat_template` field, use it;
        //   * otherwise, if a sibling `chat_template.jinja` exists, read that;
        //   * otherwise treat the file itself as the template.
        let template_string: String = match serde_json::from_str::<serde_json::Value>(&raw) {
            Ok(v) if v.get("chat_template").is_some() => v["chat_template"]
                .as_str()
                .expect("chat_template field must be a string")
                .to_string(),
            _ => {
                let sibling = std::path::Path::new(&path)
                    .parent()
                    .map(|d| d.join("chat_template.jinja"));
                match sibling {
                    Some(p) if p.exists() => {
                        eprintln!(
                            "[info] {path} had no chat_template field; using {}",
                            p.display()
                        );
                        std::fs::read_to_string(&p).expect("read sibling chat_template.jinja")
                    }
                    _ => raw,
                }
            }
        };

        // Guard against silently echoing a non-template (e.g. a tokenizer_config.json
        // with no chat_template and no sibling .jinja).
        assert!(
            template_string.contains("{%") || template_string.contains("{{"),
            "resolved template has no Jinja tags — GPTOSS_CHAT_TEMPLATE ({path}) is probably \
             tokenizer_config.json with no chat_template field and no sibling chat_template.jinja. \
             Point it at the chat_template.jinja file."
        );

        let chat_template: ChatTemplate =
            serde_json::from_value(serde_json::json!({ "chat_template": template_string }))
                .unwrap();

        let formatter =
            HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap();

        // Declare tools — the tool-channel guidance only renders when tools are present.
        let request: NvCreateChatCompletionRequest = serde_json::from_str(
            r#"{
              "model": "openai/gpt-oss-120b",
              "messages": [{"role":"user","content":"Search the repo for the string \"countHook\"."}],
              "tools": [
                {"type":"function","function":{"name":"grep","description":"search files","parameters":{"type":"object","properties":{"pattern":{"type":"string"},"path":{"type":"string"}},"required":["pattern"]}}},
                {"type":"function","function":{"name":"read","description":"read a file","parameters":{"type":"object","properties":{"filePath":{"type":"string"}},"required":["filePath"]}}}
              ]
            }"#,
        )
        .unwrap();

        let rendered = formatter.render(&request).unwrap();
        eprintln!("================ RENDERED gpt-oss PROMPT (tools declared) ================");
        eprintln!("{rendered}");
        eprintln!("================ END RENDERED PROMPT ================");
        eprintln!("[diagnostics] does the rendered prompt contain…");
        for needle in [
            "commentary",
            "Calls to these tools",
            "functions",
            "# Tools",
            "<|channel|>",
            "constrain",
            "analysis",
        ] {
            eprintln!(
                "  {:>22}: {}",
                format!("{needle:?}"),
                rendered.contains(needle)
            );
        }
    }

    /// Tests that media URL content parts are converted to empty placeholders.
    #[test]
    fn test_convert_media_url_to_placeholder_single_type() {
        let content_array = vec![
            serde_json::json!({"type": "text", "text": "Check this image:"}),
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}),
            serde_json::json!({"type": "text", "text": "What do you see?"}),
        ];

        let conversions = &[("image_url", "image")];
        let result = convert_media_url_to_placeholder(&content_array, conversions);

        assert_eq!(result.len(), 3);
        // Text parts should be unchanged
        assert_eq!(result[0]["type"], "text");
        assert_eq!(result[0]["text"], "Check this image:");
        // image_url should be converted to image placeholder
        assert_eq!(result[1]["type"], "image");
        assert!(result[1].get("image_url").is_none());
        // Text parts should be unchanged
        assert_eq!(result[2]["type"], "text");
        assert_eq!(result[2]["text"], "What do you see?");
    }

    /// Tests that multiple media URL parts of the same type are all converted.
    #[test]
    fn test_convert_media_url_to_placeholder_multiple_same_type() {
        let content_array = vec![
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image1.jpg"}}),
            serde_json::json!({"type": "text", "text": "vs"}),
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image2.jpg"}}),
        ];

        let conversions = &[("image_url", "image")];
        let result = convert_media_url_to_placeholder(&content_array, conversions);

        assert_eq!(result.len(), 3);
        assert_eq!(result[0]["type"], "image");
        assert_eq!(result[1]["type"], "text");
        assert_eq!(result[2]["type"], "image");
    }

    /// Tests that only specified media types are converted, others preserved.
    #[test]
    fn test_convert_media_url_to_placeholder_selective_conversion() {
        let content_array = vec![
            serde_json::json!({"type": "audio_url", "audio_url": {"url": "https://example.com/audio.mp3"}}),
            serde_json::json!({"type": "video_url", "video_url": {"url": "https://example.com/video.mp4"}}),
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}),
        ];

        // Only convert image_url
        let conversions = &[("image_url", "image")];
        let result = convert_media_url_to_placeholder(&content_array, conversions);

        assert_eq!(result.len(), 3);
        // audio_url and video_url should be preserved as-is
        assert_eq!(result[0]["type"], "audio_url");
        assert!(result[0].get("audio_url").is_some());
        assert_eq!(result[1]["type"], "video_url");
        assert!(result[1].get("video_url").is_some());
        // Only image_url should be converted
        assert_eq!(result[2]["type"], "image");
        assert!(result[2].get("image_url").is_none());
    }

    /// Tests converting multiple different media types at once.
    #[test]
    fn test_convert_media_url_to_placeholder_multiple_types() {
        let content_array = vec![
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}),
            serde_json::json!({"type": "text", "text": "and listen to"}),
            serde_json::json!({"type": "audio_url", "audio_url": {"url": "https://example.com/audio.mp3"}}),
            serde_json::json!({"type": "text", "text": "and watch"}),
            serde_json::json!({"type": "video_url", "video_url": {"url": "https://example.com/video.mp4"}}),
        ];

        // Convert all media types
        let conversions = &[
            ("image_url", "image"),
            ("audio_url", "audio"),
            ("video_url", "video"),
        ];
        let result = convert_media_url_to_placeholder(&content_array, conversions);

        assert_eq!(result.len(), 5);
        assert_eq!(result[0]["type"], "image");
        assert!(result[0].get("image_url").is_none());
        assert_eq!(result[1]["type"], "text");
        assert_eq!(result[2]["type"], "audio");
        assert!(result[2].get("audio_url").is_none());
        assert_eq!(result[3]["type"], "text");
        assert_eq!(result[4]["type"], "video");
        assert!(result[4].get("video_url").is_none());
    }

    /// Tests that empty conversions list preserves all content.
    #[test]
    fn test_convert_media_url_to_placeholder_no_conversions() {
        let content_array = vec![
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}),
            serde_json::json!({"type": "text", "text": "hello"}),
        ];

        let conversions: &[(&str, &str)] = &[];
        let result = convert_media_url_to_placeholder(&content_array, conversions);

        assert_eq!(result.len(), 2);
        // Everything should be preserved as-is
        assert_eq!(result[0]["type"], "image_url");
        assert!(result[0].get("image_url").is_some());
        assert_eq!(result[1]["type"], "text");
    }

    /// Tests that DEFAULT_MEDIA_TYPE_CONVERSIONS only converts image_url,
    /// and preserves other media types like video_url and audio_url.
    #[test]
    fn test_default_media_type_conversions_only_converts_image_url() {
        let content_array = vec![
            serde_json::json!({"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}),
            serde_json::json!({"type": "video_url", "video_url": {"url": "https://example.com/video.mp4"}}),
            serde_json::json!({"type": "audio_url", "audio_url": {"url": "https://example.com/audio.mp3"}}),
            serde_json::json!({"type": "text", "text": "hello"}),
        ];

        // Use the actual DEFAULT_MEDIA_TYPE_CONVERSIONS
        let result =
            convert_media_url_to_placeholder(&content_array, DEFAULT_MEDIA_TYPE_CONVERSIONS);

        assert_eq!(result.len(), 4);

        // image_url SHOULD be converted to image (it's in the default map)
        assert_eq!(result[0]["type"], "image");
        assert!(result[0].get("image_url").is_none());

        // video_url should NOT be converted (not in the default map)
        assert_eq!(result[1]["type"], "video");
        assert!(result[1].get("video_url").is_none());

        // audio_url should NOT be converted (not in the default map)
        assert_eq!(result[2]["type"], "audio");
        assert!(result[2].get("audio_url").is_none());

        // text should be unchanged
        assert_eq!(result[3]["type"], "text");
        assert_eq!(result[3]["text"], "hello");
    }

    #[test]
    fn test_may_be_fix_tool_schema_missing_type_and_properties() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get the current weather in a given location",
                        "parameters": {},
                        "strict": null
                    }
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let tools = serde_json::to_value(request.tools()).unwrap();

        assert!(tools[0]["function"]["parameters"]["type"] == "object");
        assert!(
            tools[0]["function"]["parameters"]["properties"]
                == serde_json::Value::Object(Default::default())
        );
    }

    #[test]
    fn test_may_be_fix_tool_schema_missing_type() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get the current weather in a given location",
                        "parameters": {
                            "properties": {
                                "location": {
                                    "type": "string",
                                    "description": "City and state, e.g., 'San Francisco, CA'"
                                }
                            }
                        },
                        "strict": null
                    }
                }
            ]
        }"#;
        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();

        let tools = serde_json::to_value(request.tools()).unwrap();

        assert_eq!(tools[0]["function"]["parameters"]["type"], "object");

        let mut expected_properties = serde_json::Map::new();
        let mut location = serde_json::Map::new();
        location.insert(
            "type".to_string(),
            serde_json::Value::String("string".to_string()),
        );
        location.insert(
            "description".to_string(),
            serde_json::Value::String("City and state, e.g., 'San Francisco, CA'".to_string()),
        );
        expected_properties.insert("location".to_string(), serde_json::Value::Object(location));

        assert_eq!(
            tools[0]["function"]["parameters"]["properties"],
            serde_json::Value::Object(expected_properties)
        );
    }

    #[test]
    fn test_may_be_fix_tool_schema_missing_properties() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get the current weather in a given location",
                        "parameters": {"type": "object"},
                        "strict": null
                    }
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let tools = serde_json::to_value(request.tools()).unwrap();

        assert_eq!(
            tools[0]["function"]["parameters"]["properties"],
            serde_json::Value::Object(Default::default())
        );
        assert_eq!(tools[0]["function"]["parameters"]["type"], "object");
    }

    #[test]
    fn test_may_be_fix_tool_schema_missing_description() {
        // `description` is optional in the OpenAI tool schema, but some chat
        // templates (e.g. gpt-oss harmony) concatenate it unconditionally and
        // fail on an `undefined`/null value. It must be backfilled to "".
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "noop",
                        "parameters": {
                            "type": "object",
                            "properties": { "x": { "type": "string" } },
                            "required": ["x"],
                            "additionalProperties": false
                        },
                        "strict": null
                    }
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let tools = serde_json::to_value(request.tools()).unwrap();

        assert_eq!(
            tools[0]["function"]["description"],
            serde_json::Value::String(String::new())
        );
    }

    #[test]
    fn test_may_be_fix_tool_schema_null_description() {
        // An explicit null `description` must also be normalized to "".
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "noop",
                        "description": null,
                        "parameters": {"type": "object", "properties": {}},
                        "strict": null
                    }
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let tools = serde_json::to_value(request.tools()).unwrap();

        assert_eq!(
            tools[0]["function"]["description"],
            serde_json::Value::String(String::new())
        );
    }

    #[test]
    fn test_may_be_fix_tool_schema_preserves_description() {
        // A present `description` must be left untouched.
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [],
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "description": "Get the current weather in a given location",
                        "parameters": {"type": "object", "properties": {}},
                        "strict": null
                    }
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let tools = serde_json::to_value(request.tools()).unwrap();

        assert_eq!(
            tools[0]["function"]["description"],
            "Get the current weather in a given location"
        );
    }

    /// Tests that content arrays (containing only text parts) are correctly concatenated.
    #[test]
    fn test_may_be_fix_msg_content_user_multipart() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "part 1"},
                        {"type": "text", "text": "part 2"}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Test array → string normalization (preserve_arrays=false for standard templates)
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Verify: text-only array is concatenated into a single string
        assert_eq!(
            messages[0]["content"],
            serde_json::Value::String("part 1\npart 2".to_string())
        );
    }

    /// Tests that the function correctly handles a conversation
    /// with multiple roles and mixed message types:
    #[test]
    fn test_may_be_fix_msg_content_mixed_messages() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "system",
                    "content": "You are a helpful assistant"
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Hello"},
                        {"type": "text", "text": "World"}
                    ]
                },
                {
                    "role": "assistant",
                    "content": "Hi there!"
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Another"},
                        {"type": "text", "text": "multi-part"},
                        {"type": "text", "text": "message"}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Test array → string normalization (preserve_arrays=false for standard templates)
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Verify: System message with string content remains unchanged
        assert_eq!(
            messages[0]["content"],
            serde_json::Value::String("You are a helpful assistant".to_string())
        );

        // Verify: User message with text-only array is concatenated
        assert_eq!(
            messages[1]["content"],
            serde_json::Value::String("Hello\nWorld".to_string())
        );

        // Verify: Assistant message with string content remains unchanged
        assert_eq!(
            messages[2]["content"],
            serde_json::Value::String("Hi there!".to_string())
        );

        // Verify: Second user message with text-only array is concatenated
        assert_eq!(
            messages[3]["content"],
            serde_json::Value::String("Another\nmulti-part\nmessage".to_string())
        );
    }

    /// Tests that empty content arrays remain unchanged.
    #[test]
    fn test_may_be_fix_msg_content_empty_array() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": []
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Empty arrays should be preserved regardless of preserve_arrays setting
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Verify: Empty arrays are preserved as-is
        assert!(messages[0]["content"].is_array());
        assert_eq!(messages[0]["content"].as_array().unwrap().len(), 0);
    }

    /// Empty arrays must stay as `[]` even when a flatten-time placeholder
    /// template is provided (Phi-3 / LLaVA-1.5 path). Without the
    /// `!content_array.is_empty()` guard in `may_be_fix_msg_content`,
    /// an empty content array would silently flatten to `""` and the
    /// chat template would render an entirely empty message instead of
    /// failing or being preserved.
    #[test]
    fn test_may_be_fix_msg_content_empty_array_with_placeholder_template() {
        let json_str = r#"{
            "model": "phi-3-vision",
            "messages": [
                {
                    "role": "user",
                    "content": []
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // preserve_arrays=false + image_placeholder_template=Some(...) is
        // the combination that previously flattened `[]` to `""`.
        let messages = serde_json::to_value(may_be_fix_msg_content(
            messages_raw,
            false,
            Some("<|image_{n}|>"),
        ))
        .unwrap();

        assert!(
            messages[0]["content"].is_array(),
            "empty array should be preserved as `[]`, not flattened to `\"\"`"
        );
        assert_eq!(messages[0]["content"].as_array().unwrap().len(), 0);
    }

    /// Tests that messages with simple string content remain unchanged.
    #[test]
    fn test_may_be_fix_msg_content_single_text() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": "Simple text message"
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Test with preserve_arrays=false (standard templates)
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Verify: String content is not modified
        assert_eq!(
            messages[0]["content"],
            serde_json::Value::String("Simple text message".to_string())
        );
    }

    /// Tests that content arrays with mixed types (text + non-text) remain as arrays,
    /// and that image_url is converted to image placeholder.
    #[test]
    fn test_may_be_fix_msg_content_mixed_types() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Check this image:"},
                        {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}},
                        {"type": "text", "text": "What do you see?"}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Mixed content should be preserved regardless of preserve_arrays setting
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Verify: Mixed content types are preserved as array for template handling
        // image_url should be converted to image placeholder
        assert!(messages[0]["content"].is_array());
        let content_array = messages[0]["content"].as_array().unwrap();
        assert_eq!(content_array.len(), 3);
        assert_eq!(content_array[0]["type"], "text");
        assert_eq!(content_array[1]["type"], "image");
        assert!(content_array[1].get("image_url").is_none());
        assert_eq!(content_array[2]["type"], "text");
    }

    /// Mixed text+image array with a string-content template and an
    /// `<|image_{n}|>`-style placeholder (Phi-3-vision) — content must be
    /// flattened to a single string with numbered image markers in place of
    /// the image parts. The previous default (leave as array) would crash
    /// the Phi-3 template's `'+' message.content` concatenation.
    #[test]
    fn test_may_be_fix_msg_content_flattens_phi3_style() {
        let json_str = r#"{
            "model": "phi-3-vision",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "First "},
                        {"type": "image_url", "image_url": {"url": "https://example.com/a.jpg"}},
                        {"type": "text", "text": " then "},
                        {"type": "image_url", "image_url": {"url": "https://example.com/b.jpg"}},
                        {"type": "text", "text": "?"}
                    ]
                }
            ]
        }"#;
        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        let messages = serde_json::to_value(may_be_fix_msg_content(
            messages_raw,
            false,
            Some("<|image_{n}|>"),
        ))
        .unwrap();

        let content = messages[0]["content"].as_str().expect("content flattened");
        assert_eq!(content, "First <|image_1|> then <|image_2|>?");
    }

    /// Same flattening with a static placeholder (LLaVA-1.5 `<image>`).
    #[test]
    fn test_may_be_fix_msg_content_flattens_llava_style() {
        let json_str = r#"{
            "model": "llava-1.5-7b-hf",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Describe: "},
                        {"type": "image_url", "image_url": {"url": "https://example.com/x.jpg"}}
                    ]
                }
            ]
        }"#;
        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, Some("<image>")))
                .unwrap();

        let content = messages[0]["content"].as_str().expect("content flattened");
        assert_eq!(content, "Describe: <image>");
    }

    /// Nemotron-Parse pass-through path: a mixed text+image array with an
    /// empty placeholder (`""`) flattens to the text parts only — the image
    /// contributes nothing because the vision encoder consumes it out-of-band.
    /// Without this, `{{ message.content }}` would JSON-serialize the array
    /// into the prompt (the gibberish failure mode).
    #[test]
    fn test_may_be_fix_msg_content_flattens_empty_placeholder() {
        let json_str = r#"{
            "model": "nvidia/NVIDIA-Nemotron-Parse-v1.2",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "</s><s><predict_bbox><predict_classes><output_markdown><predict_no_text_in_pic>"},
                        {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}
                    ]
                }
            ]
        }"#;
        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, Some(""))).unwrap();

        let content = messages[0]["content"].as_str().expect("content flattened");
        assert_eq!(
            content,
            "</s><s><predict_bbox><predict_classes><output_markdown><predict_no_text_in_pic>"
        );
    }

    /// End-to-end render through the Nemotron-Parse pass-through chat template:
    /// a text+image chat request must produce exactly the control-token prompt,
    /// with the image dropped from the rendered text. The renderer is agnostic
    /// to the control tokens themselves (they are just the text part, passed
    /// through verbatim), so both `predict_no_text_in_pic` and
    /// `predict_text_in_pic` prompts round-trip identically.
    #[test]
    fn test_render_nemotron_parse_passthrough() {
        use super::super::tokcfg::ChatTemplate;
        use super::{ContextMixins, HfTokenizerConfigJsonFormatter};

        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": "{% for message in messages %}{{ message['content'] }}{% endfor %}"
        }))
        .unwrap();
        let formatter =
            HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap();

        for prompt in [
            "</s><s><predict_bbox><predict_classes><output_markdown><predict_no_text_in_pic>",
            "</s><s><predict_bbox><predict_classes><output_markdown><predict_text_in_pic>",
        ] {
            let request: NvCreateChatCompletionRequest =
                serde_json::from_value(serde_json::json!({
                    "model": "nvidia/NVIDIA-Nemotron-Parse-v1.2",
                    "messages": [{
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}
                        ]
                    }]
                }))
                .unwrap();

            let rendered = formatter.render(&request).unwrap();
            assert_eq!(
                rendered, prompt,
                "rendered prompt must be the control tokens only, with no JSON-serialized image array"
            );
        }
    }

    /// Tests that content arrays containing only non-text types remain as arrays,
    /// and image_url types are converted to image placeholders.
    #[test]
    fn test_may_be_fix_msg_content_non_text_only() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "image_url", "image_url": {"url": "https://example.com/image1.jpg"}},
                        {"type": "image_url", "image_url": {"url": "https://example.com/image2.jpg"}}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Non-text arrays should be preserved regardless of preserve_arrays setting
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Verify: Non-text content arrays are preserved, with image_url converted to image
        assert!(messages[0]["content"].is_array());
        let content_array = messages[0]["content"].as_array().unwrap();
        assert_eq!(content_array.len(), 2);
        assert_eq!(content_array[0]["type"], "image");
        assert_eq!(content_array[1]["type"], "image");
    }

    #[test]
    fn test_none_tools_safe_for_all_templates() {
        use super::tokcfg::ChatTemplate;
        use super::{ContextMixins, HfTokenizerConfigJsonFormatter};

        // Due to minijinja limitations the expressions in conditional statements may not be short-circuited
        // This checks that our custom length filter works to avoid errors in this scenario
        // length should return 0 if tools is None and 'if tools is iterable and tools | length > 0' should evaluate to false
        let length_template = r#"
{%- if tools is iterable and tools | length > 0 %}
Tools available: {{ tools | length }}
{%- else %}
No tools
{%- endif %}
"#;

        // Because we return None for tools when there are no tools this scenario should also be evaluate to false
        // This is similar to the default jinja template behavior seen with llama models which check if tools is not none to activate tool mode
        let no_tool_template = r#"
{%- if tools is not none %}
TOOL MODE
{%- else %}
NORMAL MODE
{%- endif %}
"#;

        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": [
                {"safe_length": length_template},
                {"no_tool": no_tool_template}
            ]
        }))
        .unwrap();

        let formatter =
            HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap();

        let ctx = context! { tools => Option::<Value>::None };

        let result1 = formatter
            .env
            .get_template("safe_length")
            .unwrap()
            .render(&ctx);
        println!("Safe length template with no tools => None: {:?}", result1);
        assert!(
            result1.is_ok(),
            "Jinja template with and conditional and length filter should handle None: {:?}",
            result1
        );
        assert!(
            result1.unwrap().contains("No tools"),
            "Should show 'No tools'"
        );

        let result2 = formatter.env.get_template("no_tool").unwrap().render(&ctx);
        println!("Default template with no tools => None: {:?}", result2);
        assert!(
            result2.is_ok(),
            "Jinja template with if tools is not none conditional should handle None: {:?}",
            result2
        );
        assert!(result2.unwrap().contains("NORMAL MODE"));
    }

    /// Tests mixed content type scenarios.
    #[test]
    fn test_may_be_fix_msg_content_multiple_content_types() {
        // Scenario 1: Multiple different content types (text + image + audio)
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Listen to this:"},
                        {"type": "audio_url", "audio_url": {"url": "https://example.com/audio.mp3"}},
                        {"type": "text", "text": "And look at:"},
                        {"type": "image_url", "image_url": {"url": "https://example.com/img.jpg"}},
                        {"type": "text", "text": "What do you think?"}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Mixed types should preserve array structure, with image_url converted to image
        assert!(messages[0]["content"].is_array());
        let content_array = messages[0]["content"].as_array().unwrap();
        assert_eq!(content_array.len(), 5);
        assert_eq!(content_array[0]["type"], "text");
        assert_eq!(content_array[1]["type"], "audio");
        assert_eq!(content_array[2]["type"], "text");
        assert_eq!(content_array[3]["type"], "image");
        assert_eq!(content_array[4]["type"], "text");

        // Scenario 2: Unknown/future content types mixed with text
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Check this:"},
                        {"type": "video_url", "video_url": {"url": "https://example.com/vid.mp4"}},
                        {"type": "text", "text": "Interesting?"}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        // Unknown types mixed with text should preserve array
        assert!(messages[0]["content"].is_array());
        assert_eq!(messages[0]["content"].as_array().unwrap().len(), 3);
    }

    #[test]
    fn test_normalize_tool_arguments_tojson() {
        let tmpl = r#"{{ messages[0].tool_calls[0].function.arguments | tojson }}"#;

        // Message with tool_calls containing JSON string arguments
        let mut messages = serde_json::Value::Array(vec![serde_json::json!({
            "role": "assistant",
            "tool_calls": [{
                "type": "function",
                "function": {
                    "name": "get_current_weather",
                    "arguments": "{\"format\":\"celsius\",\"location\":\"San Francisco, CA\"}"
                }
            }]
        })]);

        normalize_tool_calls_arguments_in_messages(&mut messages);

        let mut env = Environment::new();
        env.add_filter("tojson", super::super::tokcfg::tojson);
        env.add_template("t", tmpl).unwrap();
        let out = env
            .get_template("t")
            .unwrap()
            .render(context! { messages => messages.as_array().unwrap() })
            .unwrap();

        // Should produce clean JSON without double-encoding, with Python
        // json.dumps separators (what transformers' tojson emits).
        assert_eq!(
            out,
            r#"{"format": "celsius", "location": "San Francisco, CA"}"#
        );
    }

    #[test]
    fn test_normalize_tool_arguments_items_loop() {
        let tmpl = r#"{% for k, v in messages[0].tool_calls[0].function.arguments|items %}{{k}}={{v}};{% endfor %}"#;

        let mut messages = serde_json::Value::Array(vec![serde_json::json!({
            "role": "assistant",
            "tool_calls": [{
                "type": "function",
                "function": {
                    "name": "f",
                    "arguments": "{\"a\":1,\"b\":\"x\"}"
                }
            }]
        })]);

        normalize_tool_calls_arguments_in_messages(&mut messages);

        let mut env = Environment::new();
        env.add_template("t", tmpl).unwrap();
        let out = env
            .get_template("t")
            .unwrap()
            .render(context! { messages => messages.as_array().unwrap() })
            .unwrap();

        assert!(out == "a=1;b=x;" || out == "b=x;a=1;");
    }

    #[test]
    fn test_normalize_tool_arguments_legacy_function_call() {
        // Test deprecated function_call format (OpenAI compat)
        let mut messages = serde_json::Value::Array(vec![serde_json::json!({
            "role": "assistant",
            "function_call": {
                "name": "get_weather",
                "arguments": "{\"location\":\"NYC\"}"
            }
        })]);

        normalize_function_call_arguments_in_messages(&mut messages);

        assert_eq!(
            messages[0]["function_call"]["arguments"],
            serde_json::json!({"location": "NYC"})
        );
    }

    #[test]
    fn test_normalize_tool_arguments_malformed_json_passthrough() {
        // Malformed JSON should be left as a string
        let mut messages = serde_json::Value::Array(vec![serde_json::json!({
            "role": "assistant",
            "tool_calls": [{
                "type": "function",
                "function": {
                    "name": "f",
                    "arguments": "not valid json at all"
                }
            }]
        })]);

        normalize_tool_calls_arguments_in_messages(&mut messages);

        assert_eq!(
            messages[0]["tool_calls"][0]["function"]["arguments"],
            serde_json::Value::String("not valid json at all".to_string())
        );
    }

    #[test]
    fn test_normalize_tool_arguments_with_multimodal_content() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Check this:"},
                        {"type": "video_url", "video_url": {"url": "https://example.com/vid.mp4"}},
                        {"type": "text", "text": "Interesting?"}
                    ]
                },
                {
                    "role": "assistant",
                    "tool_calls": [{
                        "id": "call_123",
                        "type": "function",
                        "function": {
                            "name": "analyze_video",
                            "arguments": "{\"url\":\"https://example.com/vid.mp4\",\"format\":\"mp4\"}"
                        }
                    }]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Apply content normalization with preserve_arrays=false (standard templates)
        let mut messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, false, None)).unwrap();

        normalize_tool_calls_arguments_in_messages(&mut messages);

        // Multimodal content preserved as array (mixed types not flattened)
        assert!(messages[0]["content"].is_array());
        assert_eq!(messages[0]["content"].as_array().unwrap().len(), 3);

        // Tool arguments deserialized to object
        assert!(messages[1]["tool_calls"][0]["function"]["arguments"].is_object());
        assert_eq!(
            messages[1]["tool_calls"][0]["function"]["arguments"]["url"],
            "https://example.com/vid.mp4"
        );
    }

    /// Tests string → array normalization for multimodal templates
    #[test]
    fn test_may_be_fix_msg_content_string_to_array() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": "Hello, how are you?"
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Test with preserve_arrays=true (multimodal templates)
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, true, None)).unwrap();

        // Verify: String is converted to array format
        assert!(messages[0]["content"].is_array());
        let content_array = messages[0]["content"].as_array().unwrap();
        assert_eq!(content_array.len(), 1);
        assert_eq!(content_array[0]["type"], "text");
        assert_eq!(content_array[0]["text"], "Hello, how are you?");
    }

    /// Tests that arrays are preserved when preserve_arrays=true
    #[test]
    fn test_may_be_fix_msg_content_array_preserved_with_multimodal() {
        let json_str = r#"{
            "model": "gpt-4o",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "part 1"},
                        {"type": "text", "text": "part 2"}
                    ]
                }
            ]
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json_str).unwrap();
        let messages_raw = serde_json::to_value(request.messages()).unwrap();

        // Test with preserve_arrays=true (multimodal templates)
        let messages =
            serde_json::to_value(may_be_fix_msg_content(messages_raw, true, None)).unwrap();

        // Verify: Array is preserved as-is
        assert!(messages[0]["content"].is_array());
        let content_array = messages[0]["content"].as_array().unwrap();
        assert_eq!(content_array.len(), 2);
        assert_eq!(content_array[0]["text"], "part 1");
        assert_eq!(content_array[1]["text"], "part 2");
    }

    fn user() -> Msg {
        Msg::User(Default::default())
    }
    fn tool() -> Msg {
        Msg::Tool(Default::default())
    }

    fn dummy_state(messages: Vec<Msg>) -> NvCreateChatCompletionRequest {
        let json = serde_json::json!({
            "model": "test-model",
            "messages": messages
        });
        serde_json::from_value(json).unwrap()
    }

    #[test]
    fn add_after_user() {
        let s = dummy_state(vec![user()]);
        assert!(s.should_add_generation_prompt());
    }

    #[test]
    fn add_after_tool() {
        let s = dummy_state(vec![tool()]);
        assert!(s.should_add_generation_prompt());
    }

    #[test]
    fn add_when_empty() {
        let s = dummy_state(vec![]);
        assert!(s.should_add_generation_prompt());
    }

    /// Helper to build a formatter with a simple tool-aware template.
    fn tool_aware_formatter(
        exclude_tools_when_tool_choice_none: bool,
    ) -> HfTokenizerConfigJsonFormatter {
        let template = r#"
{%- if tools is iterable and tools | length > 0 %}
TOOL_MODE tools={{ tools | length }}
{%- else %}
NORMAL_MODE
{%- endif %}
{{ messages[0].content }}"#;

        let chat_template: super::tokcfg::ChatTemplate =
            serde_json::from_value(serde_json::json!({ "chat_template": template })).unwrap();

        HfTokenizerConfigJsonFormatter::with_options(
            chat_template,
            ContextMixins::new(&[]),
            exclude_tools_when_tool_choice_none,
        )
        .unwrap()
    }

    fn gemma4_tool_template_for_tests() -> &'static str {
        r#"
{{ bos_token }}
{%- set loop_messages = messages -%}
{%- set ns_turn = namespace(last_user_idx=-1) -%}
{%- for i in range(loop_messages | length) -%}
    {%- if loop_messages[i]['role'] == 'user' -%}
        {%- set ns_turn.last_user_idx = i -%}
    {%- endif -%}
{%- endfor -%}
{%- for message in loop_messages -%}
    {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
    {{- '<|turn>' + role + '\n' }}

    {%- if message.get('reasoning') and loop.index0 > ns_turn.last_user_idx and message.get('tool_calls') -%}
        {{- '<|channel>thought\n' + message['reasoning'] + '\n<channel|>'}}
    {%- endif -%}

            {%- if message['tool_calls'] -%}
                {%- for tool_call in message['tool_calls'] -%}
                    {%- set function = tool_call['function'] -%}
                    {{- '<|tool_call>call:' + function['name'] + '{' -}}
                    {%- if function['arguments'] is mapping -%}
                        {%- set ns_args = namespace(found_first=false) -%}
                        {%- for key, value in function['arguments'] | dictsort -%}
                            {%- if ns_args.found_first %},{% endif -%}
                            {%- set ns_args.found_first = true -%}
                            {{- key -}}:{{- value -}}
                        {%- endfor -%}
                    {%- elif function['arguments'] is string -%}
                        {{- function['arguments'] -}}
                    {%- endif -%}
                    {{- '}<tool_call|>' -}}
                {%- endfor -%}
            {%- endif -%}

            {%- if message['content'] is string -%}
                {{- message['content'] -}}
            {%- endif -%}
    {{- '<turn|>\n' -}}
{%- endfor -%}
"#
    }

    fn make_gemma4_tool_formatter_for_tests() -> HfTokenizerConfigJsonFormatter {
        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": gemma4_tool_template_for_tests()
        }))
        .unwrap();
        HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap()
    }

    /// Helper to build a request with tools and optional tool_choice.
    fn request_with_tool_choice(tool_choice: &str) -> NvCreateChatCompletionRequest {
        serde_json::from_value(serde_json::json!({
            "model": "test",
            "messages": [{"role": "user", "content": "hello"}],
            "tools": [{
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get weather",
                    "parameters": {"type": "object", "properties": {"location": {"type": "string"}}}
                }
            }],
            "tool_choice": tool_choice
        }))
        .unwrap()
    }

    #[test]
    fn test_exclude_tools_strips_when_tool_choice_none() {
        let formatter = tool_aware_formatter(true);
        let request = request_with_tool_choice("none");
        let result = formatter.render(&request).unwrap();
        assert!(
            result.contains("NORMAL_MODE"),
            "With exclude_tools=true and tool_choice=none, tools should be stripped. Got: {}",
            result
        );
    }

    #[test]
    fn test_exclude_tools_keeps_when_tool_choice_auto() {
        let formatter = tool_aware_formatter(true);
        let request = request_with_tool_choice("auto");
        let result = formatter.render(&request).unwrap();
        assert!(
            result.contains("TOOL_MODE"),
            "With tool_choice=auto, tools should be included. Got: {}",
            result
        );
    }

    #[test]
    fn test_no_exclude_tools_keeps_when_tool_choice_none() {
        let formatter = tool_aware_formatter(false);
        let request = request_with_tool_choice("none");
        let result = formatter.render(&request).unwrap();
        assert!(
            result.contains("TOOL_MODE"),
            "With exclude_tools=false and tool_choice=none, tools should NOT be stripped. Got: {}",
            result
        );
    }

    #[test]
    fn test_inject_reasoning_content_segments_with_tool_calls() {
        // Assistant message with reasoning_content segments and tool_calls
        let mut messages = serde_json::json!([
            {
                "role": "user",
                "content": "What is sqrt(144) and sqrt(256)?"
            },
            {
                "role": "assistant",
                "content": "Let me calculate those.",
                "reasoning_content": ["I need to compute sqrt(144)", "Now sqrt(256)", ""],
                "tool_calls": [
                    {
                        "id": "call_0",
                        "type": "function",
                        "function": {
                            "name": "calculator",
                            "arguments": "{\"expr\": \"sqrt(144)\"}"
                        }
                    },
                    {
                        "id": "call_1",
                        "type": "function",
                        "function": {
                            "name": "calculator",
                            "arguments": "{\"expr\": \"sqrt(256)\"}"
                        }
                    }
                ]
            }
        ]);

        inject_reasoning_content_into_messages(&mut messages);

        let assistant = &messages[1];

        // reasoning_content should be removed
        assert!(
            assistant.get("reasoning_content").is_none(),
            "reasoning_content should be removed after injection"
        );

        // content should have <think> blocks prepended (empty segment skipped)
        let content = assistant["content"].as_str().unwrap();
        assert!(
            content.starts_with("<think>I need to compute sqrt(144)</think>"),
            "content should start with first reasoning segment, got: {}",
            content
        );
        assert!(
            content.contains("<think>Now sqrt(256)</think>"),
            "content should contain second reasoning segment"
        );
        // Empty third segment should NOT produce <think></think>
        assert!(
            !content.contains("<think></think>"),
            "empty segments should be skipped"
        );
        // Original content should be preserved at the end
        assert!(
            content.ends_with("Let me calculate those."),
            "original content should be at the end, got: {}",
            content
        );

        // tool_calls should be untouched
        assert!(assistant.get("tool_calls").is_some());
        assert_eq!(assistant["tool_calls"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_gemma4_template_renders_reasoning_content_segments_around_tool_calls() {
        let formatter = make_gemma4_tool_formatter_for_tests();
        assert!(
            formatter.tool_use_template_handles_reasoning,
            "Gemma4 template adaptation should make reasoning_content native"
        );

        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "gemma4-test",
            "messages": [
                {"role": "user", "content": "inspect two things"},
                {
                    "role": "assistant",
                    "content": null,
                    "reasoning_content": [
                        "Think before the first call.",
                        "Think before the second call.",
                        "Think after both calls."
                    ],
                    "tool_calls": [
                        {
                            "id": "call_0",
                            "type": "function",
                            "function": {
                                "name": "first_tool",
                                "arguments": "{\"path\":\".\"}"
                            }
                        },
                        {
                            "id": "call_1",
                            "type": "function",
                            "function": {
                                "name": "second_tool",
                                "arguments": "{\"path\":\"/tmp\"}"
                            }
                        }
                    ]
                }
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();

        let expected = concat!(
            "<|channel>thought\nThink before the first call.\n<channel|>",
            "<|tool_call>call:first_tool{path:.}<tool_call|>",
            "<|channel>thought\nThink before the second call.\n<channel|>",
            "<|tool_call>call:second_tool{path:/tmp}<tool_call|>",
            "<|channel>thought\nThink after both calls.\n<channel|>"
        );
        assert!(
            rendered.contains(expected),
            "Gemma4 reasoning segments should stay adjacent to their tool calls, got: {rendered}"
        );
        assert!(!rendered.contains("<think>"));
        assert!(!rendered.contains("reasoning_content"));
    }

    #[test]
    fn test_gemma4_template_renders_reasoning_content_without_tool_calls() {
        let formatter = make_gemma4_tool_formatter_for_tests();
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "gemma4-test",
            "messages": [
                {"role": "user", "content": "answer directly"},
                {
                    "role": "assistant",
                    "content": "Direct answer.",
                    "reasoning_content": "Private thought."
                }
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();

        assert!(
            rendered.contains("<|channel>thought\nPrivate thought.\n<channel|>Direct answer."),
            "Gemma4 reasoning_content should render in the thought channel, got: {rendered}"
        );
        assert!(!rendered.contains("<think>"));
        assert!(!rendered.contains("reasoning_content"));
    }

    /// Regression: when a config ships a separate non-tool `default` template
    /// (dict form), adapting only the `tool_use` template to read
    /// `reasoning_content` must NOT suppress `<think>` injection on the
    /// `default` path. A global `any()` flag would flip true off the adapted
    /// `tool_use` template and silently drop reasoning on no-tool renders.
    #[test]
    fn test_reasoning_flag_is_per_template_not_global() {
        // Plain default template: renders content, never mentions reasoning_content
        // and lacks the Gemma4 fingerprint, so it is left untouched.
        const PLAIN_DEFAULT: &str = "{{ bos_token }}{%- for message in messages -%}\
            {{ message['role'] }}: {{ message['content'] }}\n{%- endfor -%}";

        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": [
                {"default": PLAIN_DEFAULT},
                {"tool_use": gemma4_tool_template_for_tests()},
            ]
        }))
        .unwrap();
        let formatter =
            HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap();

        // The adapted Gemma4 tool_use template handles reasoning natively; the
        // untouched plain default template does not. The flag must reflect that
        // per-template split, not a global OR across both.
        assert!(
            formatter.tool_use_template_handles_reasoning,
            "adapted gemma4 tool_use template should handle reasoning natively"
        );
        assert!(
            !formatter.default_template_handles_reasoning,
            "plain default template does not reference reasoning_content"
        );

        // A no-tools request routes to `default`. Reasoning must still be injected
        // as a <think> block — not silently dropped by the tool_use template's flag.
        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "gemma4-test",
            "messages": [
                {"role": "user", "content": "answer directly"},
                {
                    "role": "assistant",
                    "content": "Direct answer.",
                    "reasoning_content": "Private thought."
                }
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();
        assert!(
            rendered.contains("<think>Private thought.</think>Direct answer."),
            "reasoning must be injected on the no-tool default path, got: {rendered}"
        );
    }

    #[test]
    fn test_inject_reasoning_content_text_variant() {
        let mut messages = serde_json::json!([
            {
                "role": "assistant",
                "content": "The answer is 42.",
                "reasoning_content": "Let me think about this carefully."
            }
        ]);

        inject_reasoning_content_into_messages(&mut messages);

        let assistant = &messages[0];
        assert!(assistant.get("reasoning_content").is_none());
        let content = assistant["content"].as_str().unwrap();
        assert_eq!(
            content,
            "<think>Let me think about this carefully.</think>The answer is 42."
        );
    }

    #[test]
    fn test_inject_reasoning_content_null_content() {
        // reasoning_content present but content is null
        let mut messages = serde_json::json!([
            {
                "role": "assistant",
                "content": null,
                "reasoning_content": "Thinking...",
                "tool_calls": [{"id": "call_0", "type": "function", "function": {"name": "f", "arguments": "{}"}}]
            }
        ]);

        inject_reasoning_content_into_messages(&mut messages);

        let content = messages[0]["content"].as_str().unwrap();
        assert_eq!(content, "<think>Thinking...</think>");
        assert!(messages[0].get("reasoning_content").is_none());
    }

    #[test]
    fn test_inject_reasoning_content_skips_non_assistant() {
        let mut messages = serde_json::json!([
            {
                "role": "user",
                "content": "hello",
                "reasoning_content": "should not be touched"
            }
        ]);

        inject_reasoning_content_into_messages(&mut messages);

        // User message should be untouched
        assert!(messages[0].get("reasoning_content").is_some());
    }

    // Helper: create a formatter with a minimal chat template for render tests
    fn make_test_formatter() -> HfTokenizerConfigJsonFormatter {
        use super::tokcfg::ChatTemplate;
        use super::{ContextMixins, HfTokenizerConfigJsonFormatter};

        // Minimal template that renders content verbatim — enough to verify
        // that reasoning_content injection works through the full pipeline.
        let template = r#"{%- for message in messages %}{{ message.role }}: {{ message.content }}
{%- endfor %}
{%- if add_generation_prompt %}assistant:{%- endif %}"#;

        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": template
        }))
        .unwrap();

        HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap()
    }

    // Verify reasoning_content (Text variant) from a prior assistant turn
    // appears as a <think> block in the rendered prompt.
    #[test]
    fn test_reasoning_content_text_roundtrip_render() {
        use super::OAIPromptFormatter;
        let formatter = make_test_formatter();

        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "What is sqrt(144)?"},
                {
                    "role": "assistant",
                    "content": "The answer is 12.",
                    "reasoning_content": "I need to compute the square root of 144."
                },
                {"role": "user", "content": "Are you sure?"}
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();

        assert!(
            rendered.contains("<think>I need to compute the square root of 144.</think>"),
            "reasoning_content must appear as <think> block, got: {}",
            rendered
        );
        assert!(
            rendered.contains("The answer is 12."),
            "original content must be preserved"
        );
        assert!(
            !rendered.contains("reasoning_content"),
            "raw reasoning_content field should not leak into prompt"
        );
    }

    // Verify a full agentic flow: assistant reasons, calls a tool, gets a
    // result, then reasons again before answering. Both reasoning turns must
    // survive into the rendered prompt.
    #[test]
    fn test_reasoning_content_agentic_tool_call_roundtrip_render() {
        use super::OAIPromptFormatter;
        let formatter = make_test_formatter();

        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "What is sqrt(144) + sqrt(256)?"},
                {
                    "role": "assistant",
                    "content": null,
                    "reasoning_content": "I need to compute both square roots. Let me start with sqrt(144).",
                    "tool_calls": [{
                        "id": "call_0",
                        "type": "function",
                        "function": {
                            "name": "calculator",
                            "arguments": "{\"expr\": \"sqrt(144)\"}"
                        }
                    }]
                },
                {
                    "role": "tool",
                    "tool_call_id": "call_0",
                    "content": "12"
                },
                {
                    "role": "assistant",
                    "content": "sqrt(144) = 12 and sqrt(256) = 16, so the answer is 28.",
                    "reasoning_content": "Got 12 for sqrt(144). Now sqrt(256) = 16. Sum is 28."
                },
                {"role": "user", "content": "Thanks!"}
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();

        // First assistant turn: reasoning with tool call, null content
        assert!(
            rendered.contains("<think>I need to compute both square roots"),
            "first turn reasoning must be in prompt, got: {}",
            rendered
        );
        // Second assistant turn: reasoning with final answer
        assert!(
            rendered.contains("<think>Got 12 for sqrt(144)"),
            "second turn reasoning must be in prompt"
        );
        assert!(
            rendered.contains("the answer is 28"),
            "final answer content must be preserved"
        );
        // No raw reasoning_content in output
        assert!(
            !rendered.contains("reasoning_content"),
            "raw reasoning_content field should not leak into prompt"
        );
    }

    // Template that does NOT reference reasoning_content — injection should happen.
    #[test]
    fn test_reasoning_injected_when_template_ignores_it() {
        use super::OAIPromptFormatter;
        let formatter = make_test_formatter();

        // Formatter uses a simple template that doesn't reference reasoning_content
        assert!(!formatter.default_template_handles_reasoning);
        assert!(!formatter.tool_use_template_handles_reasoning);

        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "Hello"},
                {
                    "role": "assistant",
                    "content": "Hi.",
                    "reasoning_content": "The user said hello."
                },
                {"role": "user", "content": "Bye"}
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();
        assert!(
            rendered.contains("<think>The user said hello.</think>"),
            "injection must happen when template ignores reasoning_content, got: {}",
            rendered
        );
    }

    // Template that DOES reference reasoning_content — injection must be skipped.
    #[test]
    fn test_reasoning_not_injected_when_template_handles_it() {
        use super::tokcfg::ChatTemplate;
        use super::{ContextMixins, HfTokenizerConfigJsonFormatter, OAIPromptFormatter};

        // Template that natively renders reasoning_content (like Nemotron/Qwen3)
        let template = r#"{%- for message in messages %}{%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content %}<think>{{ message.reasoning_content }}</think>
{%- endif %}{{ message.role }}: {{ message.content }}
{%- endfor %}
{%- if add_generation_prompt %}assistant:{%- endif %}"#;

        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": template
        }))
        .unwrap();

        let formatter =
            HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap();

        // Verify detection worked
        assert!(formatter.default_template_handles_reasoning);
        assert!(formatter.tool_use_template_handles_reasoning);

        let request: NvCreateChatCompletionRequest = serde_json::from_value(serde_json::json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "Hello"},
                {
                    "role": "assistant",
                    "content": "Hi.",
                    "reasoning_content": "The user said hello."
                },
                {"role": "user", "content": "Bye"}
            ]
        }))
        .unwrap();

        let rendered = formatter.render(&request).unwrap();

        // Template renders reasoning natively — no duplicate injection
        assert!(
            rendered.contains("<think>The user said hello.</think>"),
            "template must render reasoning_content natively, got: {}",
            rendered
        );
        // Must NOT have double <think> blocks
        let think_count = rendered.matches("<think>").count();
        assert_eq!(
            think_count, 1,
            "must have exactly one <think> block (from template), got {} in: {}",
            think_count, rendered
        );
    }

    /// Real Qwen3-4B-Thinking-2507 chat template (verbatim from
    /// `Qwen/Qwen3-4B-Thinking-2507/tokenizer_config.json`). Used to
    /// regression-test append-only rendering across multi-step tool use.
    const QWEN3_THINKING_TEMPLATE: &str = r##"{%- if tools %}
    {{- '<|im_start|>system\n' }}
    {%- if messages[0].role == 'system' %}
        {{- messages[0].content + '\n\n' }}
    {%- endif %}
    {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
    {%- for tool in tools %}
        {{- "\n" }}
        {{- tool | tojson }}
    {%- endfor %}
    {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
{%- else %}
    {%- if messages[0].role == 'system' %}
        {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
    {%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
    {%- set index = (messages|length - 1) - loop.index0 %}
    {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
        {%- set ns.multi_step_tool = false %}
        {%- set ns.last_query_index = index %}
    {%- endif %}
{%- endfor %}
{%- for message in messages %}
    {%- if message.content is string %}
        {%- set content = message.content %}
    {%- else %}
        {%- set content = '' %}
    {%- endif %}
    {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
        {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
    {%- elif message.role == "assistant" %}
        {%- set reasoning_content = '' %}
        {%- if message.reasoning_content is string %}
            {%- set reasoning_content = message.reasoning_content %}
        {%- else %}
            {%- if '</think>' in content %}
                {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
                {%- set content = content.split('</think>')[-1].lstrip('\n') %}
            {%- endif %}
        {%- endif %}
        {%- if loop.index0 > ns.last_query_index %}
            {%- if loop.last or (not loop.last and reasoning_content) %}
                {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
            {%- else %}
                {{- '<|im_start|>' + message.role + '\n' + content }}
            {%- endif %}
        {%- else %}
            {{- '<|im_start|>' + message.role + '\n' + content }}
        {%- endif %}
        {%- if message.tool_calls %}
            {%- for tool_call in message.tool_calls %}
                {%- if (loop.first and content) or (not loop.first) %}
                    {{- '\n' }}
                {%- endif %}
                {%- if tool_call.function %}
                    {%- set tool_call = tool_call.function %}
                {%- endif %}
                {{- '<tool_call>\n{"name": "' }}
                {{- tool_call.name }}
                {{- '", "arguments": ' }}
                {%- if tool_call.arguments is string %}
                    {{- tool_call.arguments }}
                {%- else %}
                    {{- tool_call.arguments | tojson }}
                {%- endif %}
                {{- '}\n</tool_call>' }}
            {%- endfor %}
        {%- endif %}
        {{- '<|im_end|>\n' }}
    {%- elif message.role == "tool" %}
        {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
            {{- '<|im_start|>user' }}
        {%- endif %}
        {{- '\n<tool_response>\n' }}
        {{- content }}
        {{- '\n</tool_response>' }}
        {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
            {{- '<|im_end|>\n' }}
        {%- endif %}
    {%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
    {{- '<|im_start|>assistant\n<think>\n' }}
{%- endif %}"##;

    fn qwen3_thinking_formatter() -> HfTokenizerConfigJsonFormatter {
        let chat_template: ChatTemplate = serde_json::from_value(serde_json::json!({
            "chat_template": QWEN3_THINKING_TEMPLATE,
        }))
        .unwrap();
        HfTokenizerConfigJsonFormatter::new(chat_template, ContextMixins::new(&[])).unwrap()
    }

    #[test]
    fn test_qwen3_thinking_template_flags_detected() {
        let formatter = qwen3_thinking_formatter();
        assert!(
            formatter.tool_use_template_handles_reasoning,
            "template references reasoning_content directly"
        );
        // The Qwen3-Thinking template is registered as both `default` and
        // `tool_use` (single-string HF chat template), so both flags must fire.
        assert!(
            formatter.default_template_handles_tool_calls_arguments_string,
            "default template branches on `arguments is string`"
        );
        assert!(
            formatter.tool_use_template_handles_tool_calls_arguments_string,
            "tool_use template branches on `arguments is string`"
        );
    }

    /// Across a multi-step tool-use turn, the rendered prompt for turn N+1
    /// must be a strict prefix-extension of [turn-N prompt + bytes the model
    /// emitted on turn N]. Otherwise KV-cache prefix matching falls off a
    /// cliff every time a tool result comes back.
    ///
    /// The Qwen3-Thinking template's `is string` branch (template lines 63-67)
    /// renders `tool_call.arguments` verbatim from the OpenAI-canonical JSON
    /// string. Pre-parsing that string into an object forces the `else` branch
    /// and re-emits with minijinja's compact `tojson`, breaking append-only.
    #[test]
    fn test_qwen3_thinking_append_only_across_tool_use_turn() {
        let formatter = qwen3_thinking_formatter();

        let tools = serde_json::json!([{
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get the current weather for a location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string"},
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                    },
                    "required": ["location"]
                }
            }
        }]);

        // Turn 1: server is asked to produce the first assistant turn.
        let turn1_request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "qwen3-thinking",
                "messages": [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "What's the weather in San Francisco?"},
                ],
                "tools": tools,
            }))
            .unwrap();
        let p1 = formatter.render(&turn1_request).unwrap();

        // Bytes the model emits next. Spacing matches the Qwen3 training
        // distribution (Python jinja2 / json.dumps defaults: `, ` and `: `).
        // Empty content + reasoning + a tool call.
        let model_emitted = "I'll call get_weather for SF.\n\
            </think>\n\n\
            <tool_call>\n\
            {\"name\": \"get_weather\", \"arguments\": {\"location\": \"San Francisco\", \"unit\": \"celsius\"}}\n\
            </tool_call><|im_end|>\n";
        let wire_after_t1 = format!("{p1}{model_emitted}");

        // Turn 2: client sends the prior assistant turn back in OpenAI canonical
        // form (arguments as a JSON STRING with spaces) plus the tool result.
        let turn2_request: NvCreateChatCompletionRequest =
            serde_json::from_value(serde_json::json!({
                "model": "qwen3-thinking",
                "messages": [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "What's the weather in San Francisco?"},
                    {
                        "role": "assistant",
                        "content": "",
                        "reasoning_content": "I'll call get_weather for SF.",
                        "tool_calls": [{
                            "id": "call_sf",
                            "type": "function",
                            "function": {
                                "name": "get_weather",
                                "arguments": "{\"location\": \"San Francisco\", \"unit\": \"celsius\"}"
                            }
                        }]
                    },
                    {
                        "role": "tool",
                        "tool_call_id": "call_sf",
                        "content": "{\"temp\": 18, \"conditions\": \"Foggy\"}"
                    }
                ],
                "tools": tools,
            }))
            .unwrap();
        let p2 = formatter.render(&turn2_request).unwrap();

        if !p2.starts_with(&wire_after_t1) {
            // Find first divergence and report it for easy debugging.
            let div = wire_after_t1
                .as_bytes()
                .iter()
                .zip(p2.as_bytes())
                .position(|(a, b)| a != b)
                .unwrap_or_else(|| wire_after_t1.len().min(p2.len()));
            let lo = div.saturating_sub(40);
            panic!(
                "turn-2 prompt is NOT a prefix-extension of [turn-1 + model bytes]\n  \
                 diverges at byte {div}\n  \
                 wire ends: ...{}|{}\n  \
                 t2 has:    ...{}|{}",
                String::from_utf8_lossy(&wire_after_t1.as_bytes()[lo..div]),
                String::from_utf8_lossy(
                    &wire_after_t1.as_bytes()[div..(div + 60).min(wire_after_t1.len())]
                ),
                String::from_utf8_lossy(&p2.as_bytes()[lo..div]),
                String::from_utf8_lossy(&p2.as_bytes()[div..(div + 60).min(p2.len())]),
            );
        }

        // The only new bytes in P2 should be the tool response and the next
        // generation prompt — nothing in the prior conversation should change.
        let suffix = &p2[wire_after_t1.len()..];
        assert!(
            suffix.contains("<tool_response>"),
            "appended bytes must include the tool response, got: {suffix}"
        );
        assert!(
            suffix.ends_with("<|im_start|>assistant\n<think>\n"),
            "appended bytes must end with the next generation prompt, got: {suffix}"
        );
    }
}