dynamo-llm 1.4.0

Dynamo LLM Library
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
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Converts a stream of chat completion SSE chunks into Responses API SSE events.
//!
//! The event sequence follows the OpenAI Responses API streaming spec:
//! `response.created` -> `response.in_progress` -> `response.output_item.added` ->
//! `response.content_part.added` -> N x `response.output_text.delta` ->
//! `response.output_text.done` -> `response.content_part.done` ->
//! `response.output_item.done` -> `response.completed` -> `[DONE]`

use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

use axum::response::sse::Event;
use dynamo_protocols::types::responses::{
    AssistantRole, FunctionToolCall, IncompleteDetails, InputTokenDetails, Instructions,
    OutputContent, OutputItem, OutputMessage, OutputMessageContent, OutputStatus,
    OutputTextContent, OutputTokenDetails, ReasoningItem, Response, ResponseCompletedEvent,
    ResponseContentPartAddedEvent, ResponseContentPartDoneEvent, ResponseCreatedEvent,
    ResponseFailedEvent, ResponseFunctionCallArgumentsDeltaEvent,
    ResponseFunctionCallArgumentsDoneEvent, ResponseInProgressEvent, ResponseIncompleteEvent,
    ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent,
    ResponseReasoningSummaryPartAddedEvent, ResponseReasoningSummaryPartDoneEvent,
    ResponseReasoningSummaryTextDeltaEvent, ResponseReasoningSummaryTextDoneEvent,
    ResponseStreamEvent, ResponseTextDeltaEvent, ResponseTextDoneEvent, ResponseTextParam,
    ResponseUsage, ServiceTier, Status, SummaryPart, SummaryTextContent,
    TextResponseFormatConfiguration, ToolChoiceOptions, ToolChoiceParam, Truncation,
};
use serde::{
    Serialize,
    ser::{SerializeMap, Serializer},
};
use uuid::Uuid;

use dynamo_protocols::types::{ChatCompletionMessageContent, FinishReason};

use super::ResponseParams;
use crate::protocols::openai::chat_completions::NvCreateChatCompletionStreamResponse;
use crate::protocols::unified::ResponsesContext;

/// State machine that converts a chat completion stream into Responses API events.
pub struct ResponseStreamConverter {
    response_id: String,
    model: String,
    params: ResponseParams,
    /// Preserved Responses API-specific request context for faithful response reconstruction.
    api_context: Option<ResponsesContext>,
    created_at: u64,
    sequence_number: u64,
    // Text message tracking
    message_item_id: String,
    message_started: bool,
    message_output_index: u32,
    accumulated_text: String,
    // Reasoning summary tracking
    reasoning_item_id: String,
    reasoning_started: bool,
    reasoning_done: bool,
    reasoning_output_index: u32,
    reasoning_output_status: Option<OutputStatus>,
    accumulated_reasoning: String,
    // Function call tracking
    function_call_items: Vec<FunctionCallState>,
    // Output index counter
    next_output_index: u32,
    // Usage stats from the backend's final chunk
    usage: Option<ResponseUsage>,
    // The backend exhausted the output budget.
    output_limit_reached: bool,
}

struct FunctionCallState {
    item_id: String,
    call_id: String,
    name: String,
    accumulated_args: String,
    pending_arg_deltas: Vec<String>,
    output_index: Option<u32>,
    started: bool,
    done: bool,
}

impl FunctionCallState {
    fn has_identity(&self) -> bool {
        !self.call_id.is_empty() && !self.name.is_empty()
    }
}

impl ResponseStreamConverter {
    pub fn new(model: String, params: ResponseParams) -> Self {
        let created_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        Self {
            response_id: format!("resp_{}", Uuid::new_v4().simple()),
            model,
            params,
            api_context: None,
            created_at,
            sequence_number: 0,
            message_item_id: format!("msg_{}", Uuid::new_v4().simple()),
            message_started: false,
            message_output_index: 0,
            accumulated_text: String::new(),
            reasoning_item_id: format!("rs_{}", Uuid::new_v4().simple()),
            reasoning_started: false,
            reasoning_done: false,
            reasoning_output_index: 0,
            reasoning_output_status: None,
            accumulated_reasoning: String::new(),
            function_call_items: Vec::new(),
            next_output_index: 0,
            usage: None,
            output_limit_reached: false,
        }
    }

    pub fn with_context(model: String, params: ResponseParams, context: ResponsesContext) -> Self {
        let mut converter = Self::new(model, params);
        converter.api_context = Some(context);
        converter
    }

    fn next_seq(&mut self) -> u64 {
        let seq = self.sequence_number;
        self.sequence_number += 1;
        seq
    }

    fn make_response(&self, status: Status, output: Vec<OutputItem>) -> Response {
        let is_incomplete = status == Status::Incomplete;
        let completed_at = if status == Status::Completed {
            Some(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs(),
            )
        } else {
            None
        };
        Response {
            id: self.response_id.clone(),
            object: "response".to_string(),
            created_at: self.created_at,
            completed_at,
            status,
            model: self.model.clone(),
            output,
            // Echo request params with spec-required defaults for omitted fields
            background: Some(false),
            metadata: Some(HashMap::new()),
            parallel_tool_calls: self.params.parallel_tool_calls.or(Some(true)),
            temperature: self.params.temperature.or(Some(1.0)),
            text: Some(self.params.text.clone().unwrap_or(ResponseTextParam {
                format: TextResponseFormatConfiguration::Text,
                verbosity: None,
            })),
            tool_choice: self
                .params
                .tool_choice
                .clone()
                .or(Some(ToolChoiceParam::Mode(ToolChoiceOptions::Auto))),
            tools: Some(
                self.params
                    .tools
                    .clone()
                    .map(super::normalize_tools)
                    .unwrap_or_default(),
            ),
            top_p: self.params.top_p.or(Some(1.0)),
            truncation: Some(self.params.truncation.unwrap_or(Truncation::Disabled)),
            // Nullable required fields
            billing: None,
            conversation: None,
            error: None,
            incomplete_details: is_incomplete.then(|| IncompleteDetails {
                reason: "max_output_tokens".to_string(),
            }),
            instructions: self.params.instructions.clone().map(Instructions::Text),
            max_output_tokens: self.params.max_output_tokens,
            previous_response_id: self
                .api_context
                .as_ref()
                .and_then(|ctx| ctx.previous_response_id.clone()),
            prompt: None,
            prompt_cache_key: self.params.prompt_cache_key.clone(),
            prompt_cache_retention: self.params.prompt_cache_retention,
            reasoning: self.params.reasoning.clone(),
            safety_identifier: self.params.safety_identifier.clone(),
            service_tier: Some(self.params.service_tier.unwrap_or(ServiceTier::Auto)),
            top_logprobs: Some(0),
            usage: self.usage.clone(),
        }
    }

    /// Emit the initial lifecycle events: created + in_progress.
    pub fn emit_start_events(&mut self) -> Vec<Result<Event, anyhow::Error>> {
        let mut events = Vec::with_capacity(2);
        self.append_start_events(&mut events);
        events
    }

    /// Append the initial lifecycle events: created + in_progress.
    pub fn append_start_events(&mut self, events: &mut Vec<Result<Event, anyhow::Error>>) {
        let created = ResponseStreamEvent::ResponseCreated(ResponseCreatedEvent {
            sequence_number: self.next_seq(),
            response: self.make_response(Status::InProgress, vec![]),
        });
        events.push(self.make_sse_event(&created));

        let in_progress = ResponseStreamEvent::ResponseInProgress(ResponseInProgressEvent {
            sequence_number: self.next_seq(),
            response: self.make_response(Status::InProgress, vec![]),
        });
        events.push(self.make_sse_event(&in_progress));
    }

    /// Process a single chat completion stream chunk and return zero or more SSE events.
    pub fn process_chunk(
        &mut self,
        chunk: &NvCreateChatCompletionStreamResponse,
    ) -> Vec<Result<Event, anyhow::Error>> {
        let mut events = Vec::new();
        self.append_chunk_events(chunk, &mut events);
        events
    }

    /// Process a single chat completion stream chunk and append zero or more SSE events.
    pub fn append_chunk_events(
        &mut self,
        chunk: &NvCreateChatCompletionStreamResponse,
        events: &mut Vec<Result<Event, anyhow::Error>>,
    ) {
        // Capture usage stats from the final chunk (sent when stream_options.include_usage=true)
        if let Some(ref u) = chunk.inner.usage {
            self.usage = Some(ResponseUsage {
                input_tokens: u.prompt_tokens,
                input_tokens_details: InputTokenDetails {
                    cached_tokens: u
                        .prompt_tokens_details
                        .as_ref()
                        .and_then(|d| d.cached_tokens)
                        .unwrap_or(0),
                },
                output_tokens: u.completion_tokens,
                output_tokens_details: OutputTokenDetails {
                    reasoning_tokens: u
                        .completion_tokens_details
                        .as_ref()
                        .and_then(|d| d.reasoning_tokens)
                        .unwrap_or(0),
                },
                total_tokens: u.total_tokens,
            });
        }

        let mut should_finish_function_calls = false;
        for choice in &chunk.inner.choices {
            let delta = &choice.delta;

            if choice.finish_reason == Some(FinishReason::Length) {
                self.output_limit_reached = true;
            }

            if let Some(reasoning) = delta.reasoning_content.as_deref()
                && !reasoning.is_empty()
                && !self.reasoning_done
                && self.params.reasoning_summary_requested()
            {
                self.accumulated_reasoning.push_str(reasoning);
                if !self.reasoning_started {
                    self.reasoning_started = true;
                    self.reasoning_output_index = self.next_output_index;
                    let output_index = self.reasoning_output_index;
                    self.next_output_index += 1;

                    let item_added = ResponseStreamEvent::ResponseOutputItemAdded(
                        ResponseOutputItemAddedEvent {
                            sequence_number: self.next_seq(),
                            output_index,
                            item: OutputItem::Reasoning(ReasoningItem {
                                id: Some(self.reasoning_item_id.clone()),
                                summary: vec![],
                                content: None,
                                encrypted_content: None,
                                status: Some(OutputStatus::InProgress),
                            }),
                        },
                    );
                    events.push(self.make_sse_event(&item_added));

                    let part_added = ResponseStreamEvent::ResponseReasoningSummaryPartAdded(
                        ResponseReasoningSummaryPartAddedEvent {
                            sequence_number: self.next_seq(),
                            item_id: self.reasoning_item_id.clone(),
                            output_index,
                            summary_index: 0,
                            part: SummaryPart::SummaryText(SummaryTextContent {
                                text: String::new(),
                            }),
                        },
                    );
                    events.push(self.make_sse_event(&part_added));
                }

                let reasoning_delta = ResponseStreamEvent::ResponseReasoningSummaryTextDelta(
                    ResponseReasoningSummaryTextDeltaEvent {
                        sequence_number: self.next_seq(),
                        item_id: self.reasoning_item_id.clone(),
                        output_index: self.reasoning_output_index,
                        summary_index: 0,
                        delta: reasoning.to_string(),
                    },
                );
                events.push(self.make_sse_event(&reasoning_delta));
            }

            // Handle text content deltas — extract text from the enum
            let content_text = match &delta.content {
                Some(ChatCompletionMessageContent::Text(text)) => Some(text.as_str()),
                Some(ChatCompletionMessageContent::Parts(_)) => {
                    // Multimodal streaming not yet supported
                    None
                }
                None => None,
            };
            if let Some(content) = content_text
                && !content.is_empty()
            {
                // Starting the answer is an explicit reasoning phase boundary.
                // The reasoning item completed even when this same chunk also
                // reports that the answer exhausted the output budget.
                self.append_reasoning_done_events(events, OutputStatus::Completed);

                // Emit output_item.added + content_part.added on first text
                if !self.message_started {
                    self.message_started = true;
                    self.message_output_index = self.next_output_index;
                    let output_index = self.message_output_index;
                    self.next_output_index += 1;

                    let item_added = ResponseStreamEvent::ResponseOutputItemAdded(
                        ResponseOutputItemAddedEvent {
                            sequence_number: self.next_seq(),
                            output_index,
                            item: OutputItem::Message(OutputMessage {
                                id: self.message_item_id.clone(),
                                content: vec![],
                                role: AssistantRole::Assistant,
                                phase: None,
                                status: OutputStatus::InProgress,
                            }),
                        },
                    );
                    events.push(self.make_sse_event(&item_added));

                    let part_added = ResponseStreamEvent::ResponseContentPartAdded(
                        ResponseContentPartAddedEvent {
                            sequence_number: self.next_seq(),
                            item_id: self.message_item_id.clone(),
                            output_index,
                            content_index: 0,
                            part: OutputContent::OutputText(OutputTextContent {
                                text: String::new(),
                                annotations: vec![],
                                logprobs: Some(vec![]),
                            }),
                        },
                    );
                    events.push(self.make_sse_event(&part_added));
                }

                // Emit text delta
                self.accumulated_text.push_str(content);
                let text_delta =
                    ResponseStreamEvent::ResponseOutputTextDelta(ResponseTextDeltaEvent {
                        sequence_number: self.next_seq(),
                        item_id: self.message_item_id.clone(),
                        output_index: self.message_output_index,
                        content_index: 0,
                        delta: content.to_string(),
                        logprobs: Some(vec![]),
                    });
                events.push(self.make_sse_event(&text_delta));
            }

            // Handle tool call deltas
            if let Some(tool_calls) = &delta.tool_calls {
                if !tool_calls.is_empty() {
                    // Starting a tool call is also an explicit reasoning phase
                    // boundary, independent of this chunk's finish reason.
                    self.append_reasoning_done_events(events, OutputStatus::Completed);
                }
                for tc in tool_calls {
                    let tc_index = tc.index as usize;

                    // Start a new function call if we haven't seen this index
                    while self.function_call_items.len() <= tc_index {
                        self.function_call_items.push(FunctionCallState {
                            item_id: format!("fc_{}", Uuid::new_v4().simple()),
                            call_id: String::new(),
                            name: String::new(),
                            accumulated_args: String::new(),
                            pending_arg_deltas: Vec::new(),
                            output_index: None,
                            started: false,
                            done: false,
                        });
                    }

                    // Update call_id and name if provided
                    if let Some(id) = &tc.id {
                        self.function_call_items[tc_index].call_id = id.clone();
                    }
                    if let Some(func) = &tc.function {
                        if let Some(name) = &func.name {
                            self.function_call_items[tc_index].name = name.clone();
                        }
                        if let Some(args) = &func.arguments {
                            self.function_call_items[tc_index]
                                .accumulated_args
                                .push_str(args);
                            self.function_call_items[tc_index]
                                .pending_arg_deltas
                                .push(args.clone());
                        }
                    }

                    // Within a single call, identity (id/name) and arguments can arrive in
                    // either order — arguments may begin before the identity chunk. Do not
                    // publish an output item with empty required fields; once identity is
                    // complete, publish the item and any argument fragments already received.
                    // Across parallel calls, the in-tree parsers emit one call at a time with
                    // a monotonically increasing index, so indices are not interleaved today;
                    // keying state by `tc_index` would handle interleaving too, but that path
                    // is defensive rather than exercised by any current backend.
                    let should_start = {
                        let state = &self.function_call_items[tc_index];
                        !state.started && state.has_identity()
                    };
                    let new_output_index = should_start.then(|| {
                        let output_index = self.next_output_index;
                        self.next_output_index += 1;
                        output_index
                    });
                    let (item_added, argument_target, argument_deltas) = {
                        let state = &mut self.function_call_items[tc_index];
                        let item_added = if let Some(output_index) = new_output_index {
                            state.started = true;
                            state.output_index = Some(output_index);
                            Some((
                                state.item_id.clone(),
                                state.call_id.clone(),
                                state.name.clone(),
                                output_index,
                            ))
                        } else {
                            None
                        };
                        let argument_deltas = if state.started {
                            std::mem::take(&mut state.pending_arg_deltas)
                        } else {
                            Vec::new()
                        };
                        (
                            item_added,
                            state
                                .output_index
                                .map(|output_index| (state.item_id.clone(), output_index)),
                            argument_deltas,
                        )
                    };

                    if let Some((item_id, call_id, name, output_index)) = item_added {
                        let item_added = ResponseStreamEvent::ResponseOutputItemAdded(
                            ResponseOutputItemAddedEvent {
                                sequence_number: self.next_seq(),
                                output_index,
                                item: OutputItem::FunctionCall(FunctionToolCall {
                                    id: Some(item_id),
                                    call_id,
                                    namespace: None,
                                    name,
                                    arguments: String::new(),
                                    status: Some(OutputStatus::InProgress),
                                }),
                            },
                        );
                        events.push(self.make_sse_event(&item_added));
                    }

                    if let Some((item_id, output_index)) = argument_target {
                        for delta in argument_deltas {
                            let args_delta =
                                ResponseStreamEvent::ResponseFunctionCallArgumentsDelta(
                                    ResponseFunctionCallArgumentsDeltaEvent {
                                        sequence_number: self.next_seq(),
                                        item_id: item_id.clone(),
                                        output_index,
                                        delta,
                                    },
                                );
                            events.push(self.make_sse_event(&args_delta));
                        }
                    }
                }
            }

            // `JailedStream` rewrites `Stop` to `ToolCalls` after emitting
            // tool-call chunks. Interrupted `Length`/`ContentFilter` streams
            // retain their reason and use the EOF fallback in `append_end_events`.
            if choice.finish_reason == Some(FinishReason::ToolCalls)
                || choice.finish_reason == Some(FinishReason::FunctionCall)
            {
                should_finish_function_calls = true;
            }
        }

        if should_finish_function_calls {
            self.append_pending_function_call_done_events(events);
        }
    }

    fn append_reasoning_done_events(
        &mut self,
        events: &mut Vec<Result<Event, anyhow::Error>>,
        output_status: OutputStatus,
    ) {
        if self.reasoning_done {
            return;
        }
        self.reasoning_done = true;
        if !self.reasoning_started {
            return;
        }
        self.reasoning_output_status = Some(output_status);

        let text_done = ResponseStreamEvent::ResponseReasoningSummaryTextDone(
            ResponseReasoningSummaryTextDoneEvent {
                sequence_number: self.next_seq(),
                item_id: self.reasoning_item_id.clone(),
                output_index: self.reasoning_output_index,
                summary_index: 0,
                text: self.accumulated_reasoning.clone(),
            },
        );
        events.push(self.make_sse_event(&text_done));

        let summary = SummaryPart::SummaryText(SummaryTextContent {
            text: self.accumulated_reasoning.clone(),
        });
        let part_done = ResponseStreamEvent::ResponseReasoningSummaryPartDone(
            ResponseReasoningSummaryPartDoneEvent {
                sequence_number: self.next_seq(),
                item_id: self.reasoning_item_id.clone(),
                output_index: self.reasoning_output_index,
                summary_index: 0,
                part: summary.clone(),
            },
        );
        events.push(self.make_sse_event(&part_done));

        let item_done = ResponseStreamEvent::ResponseOutputItemDone(ResponseOutputItemDoneEvent {
            sequence_number: self.next_seq(),
            output_index: self.reasoning_output_index,
            item: OutputItem::Reasoning(ReasoningItem {
                id: Some(self.reasoning_item_id.clone()),
                summary: vec![summary],
                content: None,
                encrypted_content: None,
                status: Some(output_status),
            }),
        });
        events.push(self.make_sse_event(&item_done));
    }

    fn append_pending_function_call_done_events(
        &mut self,
        events: &mut Vec<Result<Event, anyhow::Error>>,
    ) {
        let output_status = self.output_status();
        // `started` is set only after `has_identity()` observes both required
        // fields, matching Anthropic's `is_emit_ready()` identity requirement.
        let mut pending: Vec<_> = self
            .function_call_items
            .iter_mut()
            .filter(|fc| fc.started && !fc.done)
            .map(|fc| {
                fc.done = true;
                (
                    fc.item_id.clone(),
                    fc.call_id.clone(),
                    fc.name.clone(),
                    fc.output_index
                        .expect("started function call is missing an output index"),
                    fc.accumulated_args.clone(),
                )
            })
            .collect();
        pending.sort_unstable_by_key(|(_, _, _, output_index, _)| *output_index);

        for (item_id, call_id, fc_name, output_index, accumulated_args) in pending {
            let args_done = ResponseStreamEvent::ResponseFunctionCallArgumentsDone(
                ResponseFunctionCallArgumentsDoneEvent {
                    sequence_number: self.next_seq(),
                    item_id: item_id.clone(),
                    output_index,
                    arguments: accumulated_args.clone(),
                    name: Some(fc_name.clone()),
                },
            );
            events.push(self.make_sse_event(&args_done));

            let item_done =
                ResponseStreamEvent::ResponseOutputItemDone(ResponseOutputItemDoneEvent {
                    sequence_number: self.next_seq(),
                    output_index,
                    item: OutputItem::FunctionCall(FunctionToolCall {
                        id: Some(item_id),
                        call_id,
                        namespace: None,
                        name: fc_name,
                        arguments: accumulated_args,
                        status: Some(output_status),
                    }),
                });
            events.push(self.make_sse_event(&item_done));
        }
    }

    fn output_status(&self) -> OutputStatus {
        if self.output_limit_reached {
            OutputStatus::Incomplete
        } else {
            OutputStatus::Completed
        }
    }

    fn terminal_status(&self) -> Status {
        if self.output_limit_reached {
            Status::Incomplete
        } else {
            Status::Completed
        }
    }

    fn completed_output(&self) -> Vec<OutputItem> {
        let output_status = self.output_status();
        let mut output = Vec::new();
        if self.reasoning_started {
            output.push((
                self.reasoning_output_index,
                OutputItem::Reasoning(ReasoningItem {
                    id: Some(self.reasoning_item_id.clone()),
                    summary: vec![SummaryPart::SummaryText(SummaryTextContent {
                        text: self.accumulated_reasoning.clone(),
                    })],
                    content: None,
                    encrypted_content: None,
                    status: Some(self.reasoning_output_status.unwrap_or(output_status)),
                }),
            ));
        }
        if self.message_started {
            output.push((
                self.message_output_index,
                OutputItem::Message(OutputMessage {
                    id: self.message_item_id.clone(),
                    content: vec![OutputMessageContent::OutputText(OutputTextContent {
                        text: self.accumulated_text.clone(),
                        annotations: vec![],
                        logprobs: Some(vec![]),
                    })],
                    role: AssistantRole::Assistant,
                    phase: None,
                    status: output_status,
                }),
            ));
        }
        for function_call in &self.function_call_items {
            if let Some(output_index) = function_call.output_index {
                output.push((
                    output_index,
                    OutputItem::FunctionCall(FunctionToolCall {
                        id: Some(function_call.item_id.clone()),
                        call_id: function_call.call_id.clone(),
                        namespace: None,
                        name: function_call.name.clone(),
                        arguments: function_call.accumulated_args.clone(),
                        status: Some(output_status),
                    }),
                ));
            }
        }
        output.sort_unstable_by_key(|(output_index, _)| *output_index);
        output.into_iter().map(|(_, item)| item).collect()
    }

    /// Emit remaining output completion events and `response.completed` at stream end.
    pub fn emit_end_events(&mut self) -> Vec<Result<Event, anyhow::Error>> {
        let mut events = Vec::new();
        self.append_end_events(&mut events);
        events
    }

    /// Append remaining output completion events and `response.completed` at stream end.
    pub fn append_end_events(&mut self, events: &mut Vec<Result<Event, anyhow::Error>>) {
        let output_status = self.output_status();
        // Without a later output item, the response finish reason determines
        // whether the still-open reasoning item completed or was truncated.
        self.append_reasoning_done_events(events, output_status);

        // Close text message if it was started
        if self.message_started {
            let text_done = ResponseStreamEvent::ResponseOutputTextDone(ResponseTextDoneEvent {
                sequence_number: self.next_seq(),
                item_id: self.message_item_id.clone(),
                output_index: self.message_output_index,
                content_index: 0,
                text: self.accumulated_text.clone(),
                logprobs: Some(vec![]),
            });
            events.push(self.make_sse_event(&text_done));

            let part_done =
                ResponseStreamEvent::ResponseContentPartDone(ResponseContentPartDoneEvent {
                    sequence_number: self.next_seq(),
                    item_id: self.message_item_id.clone(),
                    output_index: self.message_output_index,
                    content_index: 0,
                    part: OutputContent::OutputText(OutputTextContent {
                        text: self.accumulated_text.clone(),
                        annotations: vec![],
                        logprobs: Some(vec![]),
                    }),
                });
            events.push(self.make_sse_event(&part_done));

            let item_done =
                ResponseStreamEvent::ResponseOutputItemDone(ResponseOutputItemDoneEvent {
                    sequence_number: self.next_seq(),
                    output_index: self.message_output_index,
                    item: OutputItem::Message(OutputMessage {
                        id: self.message_item_id.clone(),
                        content: vec![OutputMessageContent::OutputText(OutputTextContent {
                            text: self.accumulated_text.clone(),
                            annotations: vec![],
                            logprobs: Some(vec![]),
                        })],
                        role: AssistantRole::Assistant,
                        phase: None,
                        status: output_status,
                    }),
                });
            events.push(self.make_sse_event(&item_done));
        }

        // Fallback for backends that end the transport without a finish-reason chunk.
        self.append_pending_function_call_done_events(events);

        let terminal_status = self.terminal_status();
        let response = self.make_response(terminal_status.clone(), self.completed_output());
        let terminal = if terminal_status == Status::Incomplete {
            ResponseStreamEvent::ResponseIncomplete(ResponseIncompleteEvent {
                sequence_number: self.next_seq(),
                response,
            })
        } else {
            ResponseStreamEvent::ResponseCompleted(ResponseCompletedEvent {
                sequence_number: self.next_seq(),
                response,
            })
        };
        events.push(self.make_sse_event(&terminal));
    }

    /// Emit error events when the stream ends due to a backend error.
    pub fn emit_error_events(&mut self) -> Vec<Result<Event, anyhow::Error>> {
        let mut events = Vec::new();
        self.append_error_events(&mut events);
        events
    }

    /// Append error events when the stream ends due to a backend error.
    pub fn append_error_events(&mut self, events: &mut Vec<Result<Event, anyhow::Error>>) {
        let failed = ResponseStreamEvent::ResponseFailed(ResponseFailedEvent {
            sequence_number: self.next_seq(),
            response: self.make_response(Status::Failed, vec![]),
        });
        events.push(self.make_sse_event(&failed));
    }
}

impl ResponseStreamConverter {
    /// Serialize a stream event, patching any embedded `response` object to
    /// satisfy the OpenResponses schema. Takes `&self` so spec-required
    /// sampling params can be sourced from the originating request via
    /// `self.params` rather than hardcoded at each emit site.
    fn make_sse_event(&self, event: &ResponseStreamEvent) -> Result<Event, anyhow::Error> {
        let event_type = get_event_type(event);
        let data = self.serialize_event_data(event)?;
        Ok(Event::default().event(event_type).data(data))
    }

    fn serialize_event_data(
        &self,
        event: &ResponseStreamEvent,
    ) -> Result<String, serde_json::Error> {
        let spec = ResponseSpecFields {
            presence_penalty: self.params.presence_penalty.unwrap_or(0.0),
            frequency_penalty: self.params.frequency_penalty.unwrap_or(0.0),
            store: self.params.store.unwrap_or(false),
        };

        match event {
            ResponseStreamEvent::ResponseCreated(event) => {
                serde_json::to_string(&ResponseEventForSpec::new(
                    "response.created",
                    event.sequence_number,
                    &event.response,
                    spec,
                ))
            }
            ResponseStreamEvent::ResponseInProgress(event) => {
                serde_json::to_string(&ResponseEventForSpec::new(
                    "response.in_progress",
                    event.sequence_number,
                    &event.response,
                    spec,
                ))
            }
            ResponseStreamEvent::ResponseCompleted(event) => {
                serde_json::to_string(&ResponseEventForSpec::new(
                    "response.completed",
                    event.sequence_number,
                    &event.response,
                    spec,
                ))
            }
            ResponseStreamEvent::ResponseFailed(event) => {
                serde_json::to_string(&ResponseEventForSpec::new(
                    "response.failed",
                    event.sequence_number,
                    &event.response,
                    spec,
                ))
            }
            ResponseStreamEvent::ResponseIncomplete(event) => {
                serde_json::to_string(&ResponseEventForSpec::new(
                    "response.incomplete",
                    event.sequence_number,
                    &event.response,
                    spec,
                ))
            }
            ResponseStreamEvent::ResponseQueued(event) => {
                serde_json::to_string(&ResponseEventForSpec::new(
                    "response.queued",
                    event.sequence_number,
                    &event.response,
                    spec,
                ))
            }
            _ => serde_json::to_string(event),
        }
    }
}

#[derive(Clone, Copy)]
struct ResponseSpecFields {
    presence_penalty: f32,
    frequency_penalty: f32,
    store: bool,
}

struct ResponseEventForSpec<'a> {
    event_type: &'static str,
    sequence_number: u64,
    response: &'a Response,
    spec: ResponseSpecFields,
}

impl<'a> ResponseEventForSpec<'a> {
    fn new(
        event_type: &'static str,
        sequence_number: u64,
        response: &'a Response,
        spec: ResponseSpecFields,
    ) -> Self {
        Self {
            event_type,
            sequence_number,
            response,
            spec,
        }
    }
}

impl Serialize for ResponseEventForSpec<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(3))?;
        map.serialize_entry("type", self.event_type)?;
        map.serialize_entry("sequence_number", &self.sequence_number)?;
        map.serialize_entry(
            "response",
            &ResponseForSpec {
                response: self.response,
                spec: self.spec,
            },
        )?;
        map.end()
    }
}

struct ResponseForSpec<'a> {
    response: &'a Response,
    spec: ResponseSpecFields,
}

// Mirrors async-openai's `Response` serialization while writing Dynamo's
// OpenResponses spec fields directly, avoiding a per-stream-event Value tree.
impl Serialize for ResponseForSpec<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let response = self.response;
        let mut map = serializer.serialize_map(None)?;

        serialize_optional_entry(&mut map, "background", &response.background)?;
        map.serialize_entry("billing", &response.billing)?;
        map.serialize_entry("conversation", &response.conversation)?;
        map.serialize_entry("created_at", &response.created_at)?;
        map.serialize_entry("completed_at", &response.completed_at)?;
        map.serialize_entry("error", &response.error)?;
        map.serialize_entry("id", &response.id)?;
        map.serialize_entry("incomplete_details", &response.incomplete_details)?;
        map.serialize_entry("instructions", &response.instructions)?;
        map.serialize_entry("max_output_tokens", &response.max_output_tokens)?;
        map.serialize_entry("max_tool_calls", &None::<u32>)?;
        serialize_optional_entry(&mut map, "metadata", &response.metadata)?;
        map.serialize_entry("model", &response.model)?;
        map.serialize_entry("object", &response.object)?;
        map.serialize_entry("output", &response.output)?;
        serialize_optional_entry(
            &mut map,
            "parallel_tool_calls",
            &response.parallel_tool_calls,
        )?;
        map.serialize_entry("previous_response_id", &response.previous_response_id)?;
        map.serialize_entry("prompt", &response.prompt)?;
        map.serialize_entry("prompt_cache_key", &response.prompt_cache_key)?;
        map.serialize_entry("prompt_cache_retention", &response.prompt_cache_retention)?;
        map.serialize_entry("reasoning", &response.reasoning)?;
        map.serialize_entry("safety_identifier", &response.safety_identifier)?;
        serialize_optional_entry(&mut map, "service_tier", &response.service_tier)?;
        map.serialize_entry("status", &response.status)?;
        serialize_optional_entry(&mut map, "temperature", &response.temperature)?;
        serialize_optional_entry(&mut map, "text", &response.text)?;
        serialize_optional_entry(&mut map, "tool_choice", &response.tool_choice)?;
        serialize_optional_entry(&mut map, "tools", &response.tools)?;
        serialize_optional_entry(&mut map, "top_logprobs", &response.top_logprobs)?;
        serialize_optional_entry(&mut map, "top_p", &response.top_p)?;
        serialize_optional_entry(&mut map, "truncation", &response.truncation)?;
        map.serialize_entry("usage", &response.usage)?;
        map.serialize_entry("presence_penalty", &self.spec.presence_penalty)?;
        map.serialize_entry("frequency_penalty", &self.spec.frequency_penalty)?;
        map.serialize_entry("store", &self.spec.store)?;

        map.end()
    }
}

fn serialize_optional_entry<S, T>(
    map: &mut S,
    key: &'static str,
    value: &Option<T>,
) -> Result<(), S::Error>
where
    S: SerializeMap,
    T: Serialize,
{
    if let Some(value) = value {
        map.serialize_entry(key, value)?;
    }
    Ok(())
}

fn get_event_type(event: &ResponseStreamEvent) -> &'static str {
    match event {
        ResponseStreamEvent::ResponseCreated(_) => "response.created",
        ResponseStreamEvent::ResponseInProgress(_) => "response.in_progress",
        ResponseStreamEvent::ResponseCompleted(_) => "response.completed",
        ResponseStreamEvent::ResponseFailed(_) => "response.failed",
        ResponseStreamEvent::ResponseIncomplete(_) => "response.incomplete",
        ResponseStreamEvent::ResponseQueued(_) => "response.queued",
        ResponseStreamEvent::ResponseOutputItemAdded(_) => "response.output_item.added",
        ResponseStreamEvent::ResponseOutputItemDone(_) => "response.output_item.done",
        ResponseStreamEvent::ResponseContentPartAdded(_) => "response.content_part.added",
        ResponseStreamEvent::ResponseContentPartDone(_) => "response.content_part.done",
        ResponseStreamEvent::ResponseOutputTextDelta(_) => "response.output_text.delta",
        ResponseStreamEvent::ResponseOutputTextDone(_) => "response.output_text.done",
        ResponseStreamEvent::ResponseRefusalDelta(_) => "response.refusal.delta",
        ResponseStreamEvent::ResponseRefusalDone(_) => "response.refusal.done",
        ResponseStreamEvent::ResponseFunctionCallArgumentsDelta(_) => {
            "response.function_call_arguments.delta"
        }
        ResponseStreamEvent::ResponseFunctionCallArgumentsDone(_) => {
            "response.function_call_arguments.done"
        }
        ResponseStreamEvent::ResponseFileSearchCallInProgress(_) => {
            "response.file_search_call.in_progress"
        }
        ResponseStreamEvent::ResponseFileSearchCallSearching(_) => {
            "response.file_search_call.searching"
        }
        ResponseStreamEvent::ResponseFileSearchCallCompleted(_) => {
            "response.file_search_call.completed"
        }
        ResponseStreamEvent::ResponseWebSearchCallInProgress(_) => {
            "response.web_search_call.in_progress"
        }
        ResponseStreamEvent::ResponseWebSearchCallSearching(_) => {
            "response.web_search_call.searching"
        }
        ResponseStreamEvent::ResponseWebSearchCallCompleted(_) => {
            "response.web_search_call.completed"
        }
        ResponseStreamEvent::ResponseReasoningSummaryPartAdded(_) => {
            "response.reasoning_summary_part.added"
        }
        ResponseStreamEvent::ResponseReasoningSummaryPartDone(_) => {
            "response.reasoning_summary_part.done"
        }
        ResponseStreamEvent::ResponseReasoningSummaryTextDelta(_) => {
            "response.reasoning_summary_text.delta"
        }
        ResponseStreamEvent::ResponseReasoningSummaryTextDone(_) => {
            "response.reasoning_summary_text.done"
        }
        ResponseStreamEvent::ResponseReasoningTextDelta(_) => "response.reasoning_text.delta",
        ResponseStreamEvent::ResponseReasoningTextDone(_) => "response.reasoning_text.done",
        ResponseStreamEvent::ResponseImageGenerationCallCompleted(_) => {
            "response.image_generation_call.completed"
        }
        ResponseStreamEvent::ResponseImageGenerationCallGenerating(_) => {
            "response.image_generation_call.generating"
        }
        ResponseStreamEvent::ResponseImageGenerationCallInProgress(_) => {
            "response.image_generation_call.in_progress"
        }
        ResponseStreamEvent::ResponseImageGenerationCallPartialImage(_) => {
            "response.image_generation_call.partial_image"
        }
        ResponseStreamEvent::ResponseMCPCallArgumentsDelta(_) => {
            "response.mcp_call_arguments.delta"
        }
        ResponseStreamEvent::ResponseMCPCallArgumentsDone(_) => "response.mcp_call_arguments.done",
        ResponseStreamEvent::ResponseMCPCallCompleted(_) => "response.mcp_call.completed",
        ResponseStreamEvent::ResponseMCPCallFailed(_) => "response.mcp_call.failed",
        ResponseStreamEvent::ResponseMCPCallInProgress(_) => "response.mcp_call.in_progress",
        ResponseStreamEvent::ResponseMCPListToolsCompleted(_) => {
            "response.mcp_list_tools.completed"
        }
        ResponseStreamEvent::ResponseMCPListToolsFailed(_) => "response.mcp_list_tools.failed",
        ResponseStreamEvent::ResponseMCPListToolsInProgress(_) => {
            "response.mcp_list_tools.in_progress"
        }
        ResponseStreamEvent::ResponseCodeInterpreterCallInProgress(_) => {
            "response.code_interpreter_call.in_progress"
        }
        ResponseStreamEvent::ResponseCodeInterpreterCallInterpreting(_) => {
            "response.code_interpreter_call.interpreting"
        }
        ResponseStreamEvent::ResponseCodeInterpreterCallCompleted(_) => {
            "response.code_interpreter_call.completed"
        }
        ResponseStreamEvent::ResponseCodeInterpreterCallCodeDelta(_) => {
            "response.code_interpreter_call_code.delta"
        }
        ResponseStreamEvent::ResponseCodeInterpreterCallCodeDone(_) => {
            "response.code_interpreter_call_code.done"
        }
        ResponseStreamEvent::ResponseOutputTextAnnotationAdded(_) => {
            "response.output_text.annotation.added"
        }
        ResponseStreamEvent::ResponseCustomToolCallInputDelta(_) => {
            "response.custom_tool_call_input.delta"
        }
        ResponseStreamEvent::ResponseCustomToolCallInputDone(_) => {
            "response.custom_tool_call_input.done"
        }
        ResponseStreamEvent::ResponseError(_) => "error",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocols::unified::ResponsesContext;
    use dynamo_protocols::types::{
        ChatChoiceStream, ChatCompletionMessageContent, ChatCompletionMessageToolCallChunk,
        ChatCompletionStreamResponseDelta, FunctionCallStream, FunctionType,
    };

    fn default_params() -> ResponseParams {
        ResponseParams::default()
    }

    fn tool_call_chunk(
        tc_index: u32,
        id: Option<&str>,
        name: Option<&str>,
        args: Option<&str>,
    ) -> NvCreateChatCompletionStreamResponse {
        #[allow(deprecated)]
        NvCreateChatCompletionStreamResponse {
            inner: dynamo_protocols::types::CreateChatCompletionStreamResponse {
                id: "chat-1".into(),
                choices: vec![ChatChoiceStream {
                    index: 0,
                    delta: ChatCompletionStreamResponseDelta {
                        content: None,
                        function_call: None,
                        tool_calls: Some(vec![ChatCompletionMessageToolCallChunk {
                            index: tc_index,
                            id: id.map(String::from),
                            r#type: Some(FunctionType::Function),
                            function: Some(FunctionCallStream {
                                name: name.map(String::from),
                                arguments: args.map(String::from),
                            }),
                        }]),
                        role: None,
                        refusal: None,
                        reasoning_content: None,
                    },
                    finish_reason: None,
                    logprobs: None,
                }],
                created: 0,
                model: "test".into(),
                service_tier: None,
                system_fingerprint: None,
                object: "chat.completion.chunk".into(),
                usage: None,
            },
            nvext: None,
            llm_metrics: None,
        }
    }

    fn finish_chunk(reason: FinishReason) -> NvCreateChatCompletionStreamResponse {
        #[allow(deprecated)]
        NvCreateChatCompletionStreamResponse {
            inner: dynamo_protocols::types::CreateChatCompletionStreamResponse {
                id: "chat-1".into(),
                choices: vec![ChatChoiceStream {
                    index: 0,
                    delta: ChatCompletionStreamResponseDelta {
                        content: None,
                        function_call: None,
                        tool_calls: None,
                        role: None,
                        refusal: None,
                        reasoning_content: None,
                    },
                    finish_reason: Some(reason),
                    logprobs: None,
                }],
                created: 0,
                model: "test".into(),
                service_tier: None,
                system_fingerprint: None,
                object: "chat.completion.chunk".into(),
                usage: None,
            },
            nvext: None,
            llm_metrics: None,
        }
    }

    fn text_chunk(text: &str) -> NvCreateChatCompletionStreamResponse {
        #[allow(deprecated)]
        NvCreateChatCompletionStreamResponse {
            inner: dynamo_protocols::types::CreateChatCompletionStreamResponse {
                id: "chat-1".into(),
                choices: vec![ChatChoiceStream {
                    index: 0,
                    delta: ChatCompletionStreamResponseDelta {
                        content: Some(ChatCompletionMessageContent::Text(text.into())),
                        function_call: None,
                        tool_calls: None,
                        role: None,
                        refusal: None,
                        reasoning_content: None,
                    },
                    finish_reason: None,
                    logprobs: None,
                }],
                created: 0,
                model: "test".into(),
                service_tier: None,
                system_fingerprint: None,
                object: "chat.completion.chunk".into(),
                usage: None,
            },
            nvext: None,
            llm_metrics: None,
        }
    }

    fn reasoning_chunk(text: &str) -> NvCreateChatCompletionStreamResponse {
        #[allow(deprecated)]
        NvCreateChatCompletionStreamResponse {
            inner: dynamo_protocols::types::CreateChatCompletionStreamResponse {
                id: "chat-1".into(),
                choices: vec![ChatChoiceStream {
                    index: 0,
                    delta: ChatCompletionStreamResponseDelta {
                        content: None,
                        function_call: None,
                        tool_calls: None,
                        role: None,
                        refusal: None,
                        reasoning_content: Some(text.into()),
                    },
                    finish_reason: None,
                    logprobs: None,
                }],
                created: 0,
                model: "test".into(),
                service_tier: None,
                system_fingerprint: None,
                object: "chat.completion.chunk".into(),
                usage: None,
            },
            nvext: None,
            llm_metrics: None,
        }
    }

    fn with_finish_reason(
        mut chunk: NvCreateChatCompletionStreamResponse,
        reason: FinishReason,
    ) -> NvCreateChatCompletionStreamResponse {
        chunk.inner.choices[0].finish_reason = Some(reason);
        chunk
    }

    /// Extract the SSE event type from a Result<Event, _>.
    fn event_type(event: &Result<Event, anyhow::Error>) -> String {
        let debug = format!("{:?}", event.as_ref().unwrap());
        // Event debug format: Event { ... event: "response.xxx" ... }
        // Parse the event type from the serialized SSE data
        if let Some(start) = debug.find("event: ") {
            let rest = &debug[start + 7..];
            if let Some(end) = rest.find("\\n") {
                return rest[..end].to_string();
            }
        }
        "unknown".to_string()
    }

    fn event_types(events: &[Result<Event, anyhow::Error>]) -> Vec<String> {
        events.iter().map(event_type).collect()
    }

    fn legacy_event_json(
        event: &ResponseStreamEvent,
        params: &ResponseParams,
    ) -> serde_json::Value {
        let mut value = serde_json::to_value(event).unwrap();
        if let serde_json::Value::Object(ref mut obj) = value
            && let Some(serde_json::Value::Object(inner)) = obj.get_mut("response")
        {
            super::super::patch_response_for_spec(
                inner,
                params.presence_penalty.unwrap_or(0.0),
                params.frequency_penalty.unwrap_or(0.0),
                params.store.unwrap_or(false),
            );
        }
        value
    }

    fn optimized_event_json(
        converter: &ResponseStreamConverter,
        event: &ResponseStreamEvent,
    ) -> serde_json::Value {
        serde_json::from_str(&converter.serialize_event_data(event).unwrap()).unwrap()
    }

    /// Parseable arguments remain open until an explicit tool-call finish reason.
    #[test]
    fn test_complete_tool_call_closes_on_finish_reason() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events(); // consume start events

        let events = conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_weather"),
            Some("{\"city\":\"SF\"}"),
        ));

        let types = event_types(&events);
        assert!(
            types.contains(&"response.output_item.added".to_string()),
            "should emit output_item.added: {types:?}"
        );
        assert!(
            types.contains(&"response.function_call_arguments.delta".to_string()),
            "should emit args delta: {types:?}"
        );
        assert!(!types.contains(&"response.function_call_arguments.done".to_string()));
        assert!(!types.contains(&"response.output_item.done".to_string()));

        let finish_types = event_types(&conv.process_chunk(&finish_chunk(FinishReason::ToolCalls)));
        assert_eq!(
            finish_types,
            vec![
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
            ]
        );

        let end_types = event_types(&conv.emit_end_events());
        assert!(!end_types.contains(&"response.function_call_arguments.done".to_string()));
        assert!(!end_types.contains(&"response.output_item.done".to_string()));
        assert!(end_types.contains(&"response.completed".to_string()));

        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        assert_eq!(response.status, Status::Completed);
        let OutputItem::FunctionCall(call) = &response.output[0] else {
            panic!("expected function call output");
        };
        assert_eq!(call.status, Some(OutputStatus::Completed));
    }

    #[test]
    fn test_function_call_finish_reason_closes_tool_call() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let _ = conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_weather"),
            Some("{\"city\":\"SF\"}"),
        ));

        let finish_types =
            event_types(&conv.process_chunk(&finish_chunk(FinishReason::FunctionCall)));
        assert_eq!(
            finish_types,
            vec![
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
            ]
        );
    }

    #[test]
    fn test_length_finish_reason_marks_open_tool_call_incomplete() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_weather"),
            Some("{\"city\":\"SF"),
        ));
        let finish_events = conv.process_chunk(&finish_chunk(FinishReason::Length));
        assert!(finish_events.is_empty());

        let end_events = conv.emit_end_events();
        assert_eq!(
            event_types(&end_events),
            vec![
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
                "response.incomplete".to_string(),
            ]
        );

        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        assert_eq!(response.status, Status::Incomplete);
        assert_eq!(
            response
                .incomplete_details
                .as_ref()
                .map(|details| details.reason.as_str()),
            Some("max_output_tokens")
        );
        let OutputItem::FunctionCall(call) = &response.output[0] else {
            panic!("expected function call output");
        };
        assert_eq!(call.status, Some(OutputStatus::Incomplete));
    }

    #[test]
    fn test_length_finish_reason_emits_incomplete_terminal_response() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.process_chunk(&text_chunk("partial"));
        let _ = conv.process_chunk(&finish_chunk(FinishReason::Length));

        let end_events = conv.emit_end_events();
        assert_eq!(
            event_types(&end_events).last().map(String::as_str),
            Some("response.incomplete")
        );

        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        assert_eq!(response.status, Status::Incomplete);
        assert_eq!(
            response
                .incomplete_details
                .as_ref()
                .map(|details| details.reason.as_str()),
            Some("max_output_tokens")
        );
        assert_eq!(response.completed_at, None);
        let OutputItem::Message(message) = &response.output[0] else {
            panic!("expected message output");
        };
        assert_eq!(message.status, OutputStatus::Incomplete);
    }

    #[test]
    fn test_length_finish_reason_marks_reasoning_item_incomplete() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);
        let _ = conv.process_chunk(&reasoning_chunk("partial"));
        let _ = conv.process_chunk(&finish_chunk(FinishReason::Length));
        let _ = conv.emit_end_events();

        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        let OutputItem::Reasoning(reasoning) = &response.output[0] else {
            panic!("expected reasoning output");
        };
        assert_eq!(reasoning.status, Some(OutputStatus::Incomplete));
    }

    #[test]
    fn test_completed_reasoning_stays_complete_when_text_is_truncated() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);
        let _ = conv.process_chunk(&reasoning_chunk("complete reasoning"));
        let _ = conv.process_chunk(&text_chunk("partial answer"));
        let _ = conv.process_chunk(&finish_chunk(FinishReason::Length));
        let _ = conv.emit_end_events();

        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        assert_eq!(response.status, Status::Incomplete);
        let OutputItem::Reasoning(reasoning) = &response.output[0] else {
            panic!("expected reasoning output");
        };
        assert_eq!(reasoning.status, Some(OutputStatus::Completed));
        let OutputItem::Message(message) = &response.output[1] else {
            panic!("expected message output");
        };
        assert_eq!(message.status, OutputStatus::Incomplete);
    }

    #[test]
    fn test_same_chunk_text_and_length_complete_reasoning_only() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);
        let _ = conv.process_chunk(&reasoning_chunk("complete reasoning"));

        let events = conv.process_chunk(&with_finish_reason(
            text_chunk("partial answer"),
            FinishReason::Length,
        ));

        assert_eq!(
            event_types(&events),
            vec![
                "response.reasoning_summary_text.done".to_string(),
                "response.reasoning_summary_part.done".to_string(),
                "response.output_item.done".to_string(),
                "response.output_item.added".to_string(),
                "response.content_part.added".to_string(),
                "response.output_text.delta".to_string(),
            ]
        );
        assert_eq!(conv.reasoning_output_status, Some(OutputStatus::Completed));

        let _ = conv.emit_end_events();
        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        assert_eq!(response.status, Status::Incomplete);
        let OutputItem::Reasoning(reasoning) = &response.output[0] else {
            panic!("expected reasoning output");
        };
        assert_eq!(reasoning.status, Some(OutputStatus::Completed));
        let OutputItem::Message(message) = &response.output[1] else {
            panic!("expected message output");
        };
        assert_eq!(message.status, OutputStatus::Incomplete);
    }

    #[test]
    fn test_same_chunk_tool_call_and_length_complete_reasoning_only() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);
        let _ = conv.process_chunk(&reasoning_chunk("complete reasoning"));

        let _ = conv.process_chunk(&with_finish_reason(
            tool_call_chunk(
                0,
                Some("call-1"),
                Some("get_weather"),
                Some("{\"city\":\"SF"),
            ),
            FinishReason::Length,
        ));

        assert_eq!(conv.reasoning_output_status, Some(OutputStatus::Completed));
        let _ = conv.emit_end_events();
        let response = conv.make_response(conv.terminal_status(), conv.completed_output());
        assert_eq!(response.status, Status::Incomplete);
        let OutputItem::Reasoning(reasoning) = &response.output[0] else {
            panic!("expected reasoning output");
        };
        assert_eq!(reasoning.status, Some(OutputStatus::Completed));
        let OutputItem::FunctionCall(function_call) = &response.output[1] else {
            panic!("expected function call output");
        };
        assert_eq!(function_call.status, Some(OutputStatus::Incomplete));
    }

    #[test]
    fn test_requested_reasoning_summary_streams_complete_event_sequence() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);

        let reasoning_events = conv.process_chunk(&reasoning_chunk("thinking"));
        assert_eq!(
            event_types(&reasoning_events),
            vec![
                "response.output_item.added".to_string(),
                "response.reasoning_summary_part.added".to_string(),
                "response.reasoning_summary_text.delta".to_string(),
            ]
        );

        let text_events = conv.process_chunk(&text_chunk("answer"));
        assert_eq!(
            event_types(&text_events),
            vec![
                "response.reasoning_summary_text.done".to_string(),
                "response.reasoning_summary_part.done".to_string(),
                "response.output_item.done".to_string(),
                "response.output_item.added".to_string(),
                "response.content_part.added".to_string(),
                "response.output_text.delta".to_string(),
            ]
        );

        let response = conv.make_response(Status::Completed, conv.completed_output());
        assert_eq!(response.output.len(), 2);
        let OutputItem::Reasoning(reasoning) = &response.output[0] else {
            panic!("expected reasoning output before message");
        };
        assert_eq!(
            reasoning.summary,
            vec![SummaryPart::SummaryText(SummaryTextContent {
                text: "thinking".to_string(),
            })]
        );
        assert!(matches!(response.output[1], OutputItem::Message(_)));
    }

    #[test]
    fn test_reasoning_without_requested_summary_emits_no_events() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());

        let events = conv.process_chunk(&reasoning_chunk("private reasoning"));

        assert!(events.is_empty());
        assert!(conv.completed_output().is_empty());
    }

    #[test]
    fn test_reasoning_summary_ignores_updates_after_completion() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);

        let _ = conv.process_chunk(&reasoning_chunk("summary"));
        let _ = conv.process_chunk(&text_chunk("answer"));
        let late_events = conv.process_chunk(&reasoning_chunk(" must not be appended"));

        assert!(late_events.is_empty());
        let output = conv.completed_output();
        let OutputItem::Reasoning(reasoning) = &output[0] else {
            panic!("expected reasoning output");
        };
        assert_eq!(
            reasoning.summary,
            vec![SummaryPart::SummaryText(SummaryTextContent {
                text: "summary".to_string(),
            })]
        );
    }

    #[test]
    fn test_reasoning_summary_finishes_before_tool_call() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);

        let _ = conv.process_chunk(&reasoning_chunk("summary"));
        let tool_events =
            conv.process_chunk(&tool_call_chunk(0, Some("call-1"), Some("get_time"), None));
        assert_eq!(
            event_types(&tool_events),
            vec![
                "response.reasoning_summary_text.done".to_string(),
                "response.reasoning_summary_part.done".to_string(),
                "response.output_item.done".to_string(),
                "response.output_item.added".to_string(),
            ]
        );

        let late_events = conv.process_chunk(&reasoning_chunk(" must not be appended"));
        assert!(late_events.is_empty());
    }

    #[test]
    fn test_reasoning_summary_does_not_start_after_visible_output() {
        use dynamo_protocols::types::responses::{Reasoning, ReasoningSummary};

        let params = ResponseParams {
            reasoning: Some(Reasoning {
                effort: None,
                summary: Some(ReasoningSummary::Auto),
            }),
            ..default_params()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params);

        let _ = conv.process_chunk(&text_chunk("answer"));
        let late_events = conv.process_chunk(&reasoning_chunk("out of order"));

        assert!(late_events.is_empty());
        assert!(
            conv.completed_output()
                .iter()
                .all(|item| !matches!(item, OutputItem::Reasoning(_)))
        );
    }

    #[test]
    fn test_identity_only_tool_call_is_emitted_and_finished() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let start_types = event_types(&conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_time"),
            None,
        )));
        assert_eq!(start_types, vec!["response.output_item.added".to_string()]);

        let finish_types = event_types(&conv.process_chunk(&finish_chunk(FinishReason::ToolCalls)));
        assert_eq!(
            finish_types,
            vec![
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
            ]
        );
        assert_eq!(conv.function_call_items[0].accumulated_args, "");
    }

    #[test]
    fn test_arguments_wait_for_identity_before_events_are_published() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let argument_types =
            event_types(&conv.process_chunk(&tool_call_chunk(0, None, None, Some("{}"))));
        assert!(argument_types.is_empty());

        let identity_types = event_types(&conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_time"),
            None,
        )));
        assert_eq!(
            identity_types,
            vec![
                "response.output_item.added".to_string(),
                "response.function_call_arguments.delta".to_string(),
            ]
        );
        assert_eq!(conv.function_call_items[0].call_id, "call-1");
        assert_eq!(conv.function_call_items[0].name, "get_time");
        assert_eq!(conv.function_call_items[0].accumulated_args, "{}");
    }

    #[test]
    fn test_out_of_order_identity_preserves_assigned_output_order() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let incomplete = event_types(&conv.process_chunk(&tool_call_chunk(
            0,
            Some("incomplete"),
            None,
            Some("{}"),
        )));
        assert!(incomplete.is_empty());
        assert_eq!(conv.function_call_items[0].output_index, None);

        let valid = event_types(&conv.process_chunk(&tool_call_chunk(
            1,
            Some("call-1"),
            Some("get_time"),
            Some("{}"),
        )));
        assert_eq!(
            valid,
            vec![
                "response.output_item.added".to_string(),
                "response.function_call_arguments.delta".to_string(),
            ]
        );
        assert_eq!(conv.function_call_items[1].output_index, Some(0));

        let late_identity =
            event_types(&conv.process_chunk(&tool_call_chunk(0, None, Some("late_call"), None)));
        assert_eq!(
            late_identity,
            vec![
                "response.output_item.added".to_string(),
                "response.function_call_arguments.delta".to_string(),
            ]
        );
        assert_eq!(conv.function_call_items[0].output_index, Some(1));

        let finish = event_types(&conv.process_chunk(&finish_chunk(FinishReason::ToolCalls)));
        assert_eq!(
            finish,
            vec![
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
            ]
        );

        let names: Vec<_> = conv
            .completed_output()
            .into_iter()
            .map(|item| match item {
                OutputItem::FunctionCall(call) => call.name,
                other => panic!("expected function call, got {other:?}"),
            })
            .collect();
        assert_eq!(names, vec!["get_time", "late_call"]);
    }

    #[test]
    fn test_empty_initial_arguments_do_not_finish_function_call_early() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let first = event_types(&conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("read_file"),
            Some(""),
        )));
        assert_eq!(
            first,
            vec![
                "response.output_item.added".to_string(),
                "response.function_call_arguments.delta".to_string(),
            ]
        );

        let middle = event_types(&conv.process_chunk(&tool_call_chunk(
            0,
            None,
            None,
            Some("{\"path\":\"/tmp"),
        )));
        assert_eq!(
            middle,
            vec!["response.function_call_arguments.delta".to_string()]
        );

        let last = event_types(&conv.process_chunk(&tool_call_chunk(0, None, None, Some("\"}"))));
        assert_eq!(
            last,
            vec!["response.function_call_arguments.delta".to_string()]
        );

        let finish = event_types(&conv.process_chunk(&finish_chunk(FinishReason::ToolCalls)));
        assert_eq!(
            finish,
            vec![
                "response.function_call_arguments.done".to_string(),
                "response.output_item.done".to_string(),
            ]
        );

        let end = event_types(&conv.emit_end_events());
        assert!(!end.contains(&"response.function_call_arguments.done".to_string()));
        assert!(!end.contains(&"response.output_item.done".to_string()));
    }

    /// A tool-call finish reason closes every pending parallel call exactly once.
    #[test]
    fn test_multiple_tool_calls_each_close_on_finish_reason() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let events1 = conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_weather"),
            Some("{\"city\":\"SF\"}"),
        ));
        let types1 = event_types(&events1);
        assert!(!types1.contains(&"response.function_call_arguments.done".to_string()));

        let events2 = conv.process_chunk(&tool_call_chunk(
            1,
            Some("call-2"),
            Some("get_time"),
            Some("{\"tz\":\"PST\"}"),
        ));
        let types2 = event_types(&events2);
        assert!(!types2.contains(&"response.function_call_arguments.done".to_string()));

        let finish_types = event_types(&conv.process_chunk(&finish_chunk(FinishReason::ToolCalls)));
        let fc_done_count = finish_types
            .iter()
            .filter(|t| *t == "response.function_call_arguments.done")
            .count();
        let item_done_count = finish_types
            .iter()
            .filter(|t| *t == "response.output_item.done")
            .count();
        assert_eq!(fc_done_count, 2);
        assert_eq!(item_done_count, 2);

        let end_types = event_types(&conv.emit_end_events());
        assert_eq!(
            end_types
                .iter()
                .filter(|t| *t == "response.function_call_arguments.done")
                .count(),
            0,
            "finish-reason completion must not repeat at EOF: {end_types:?}"
        );
        assert_eq!(
            end_types
                .iter()
                .filter(|t| *t == "response.output_item.done")
                .count(),
            0,
            "finish-reason item completion must not repeat at EOF: {end_types:?}"
        );
    }

    #[test]
    fn test_tool_call_without_finish_reason_closes_at_stream_end() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let chunk_types = event_types(&conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("get_weather"),
            Some("{\"city\":\"SF\"}"),
        )));
        assert!(!chunk_types.contains(&"response.function_call_arguments.done".to_string()));

        let end_types = event_types(&conv.emit_end_events());
        assert_eq!(
            end_types
                .iter()
                .filter(|t| *t == "response.function_call_arguments.done")
                .count(),
            1
        );
        assert_eq!(
            end_types
                .iter()
                .filter(|t| *t == "response.output_item.done")
                .count(),
            1
        );
    }

    /// Text-only response: no tool-related events at all.
    #[test]
    fn test_text_only_response_no_tool_events() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let events = conv.process_chunk(&text_chunk("Hello world"));
        let types = event_types(&events);
        assert!(
            !types.contains(&"response.function_call_arguments.done".to_string()),
            "no tool events in text-only: {types:?}"
        );

        let end_events = conv.emit_end_events();
        let end_types = event_types(&end_events);
        assert!(
            end_types.contains(&"response.output_text.done".to_string()),
            "text done in end events: {end_types:?}"
        );
        assert!(
            end_types.contains(&"response.completed".to_string()),
            "completed in end events: {end_types:?}"
        );
    }

    /// Text followed by tool call: both handled correctly.
    #[test]
    fn test_text_then_tool_call() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();

        let text_events = conv.process_chunk(&text_chunk("Let me check that."));
        let text_types = event_types(&text_events);
        assert!(
            text_types.contains(&"response.output_item.added".to_string()),
            "text message started: {text_types:?}"
        );

        let tool_events = conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("search"),
            Some("{\"q\":\"rust\"}"),
        ));
        let tool_types = event_types(&tool_events);
        assert!(!tool_types.contains(&"response.function_call_arguments.done".to_string()));
        assert!(!tool_types.contains(&"response.output_item.done".to_string()));

        let end_types = event_types(&conv.emit_end_events());
        assert!(end_types.contains(&"response.function_call_arguments.done".to_string()));
        assert!(end_types.contains(&"response.output_item.done".to_string()));
    }

    #[test]
    fn test_completed_output_keeps_tool_before_later_text() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let _ = conv.emit_start_events();
        let _ = conv.process_chunk(&tool_call_chunk(
            0,
            Some("call-1"),
            Some("search"),
            Some("{}"),
        ));
        let _ = conv.process_chunk(&text_chunk("Searching."));

        let output = conv.completed_output();
        assert!(matches!(output[0], OutputItem::FunctionCall(_)));
        assert!(matches!(output[1], OutputItem::Message(_)));
    }

    /// Verify that `with_context` populates `previous_response_id`
    /// in the generated Response objects.
    #[test]
    fn test_with_context_enriches_response() {
        let ctx = ResponsesContext {
            previous_response_id: Some("resp_prev_123".to_string()),
            store: true,
            ..Default::default()
        };
        let params = ResponseParams::default();
        let mut conv = ResponseStreamConverter::with_context("test-model".into(), params, ctx);

        // Process one text chunk so there's output
        let _ = conv.emit_start_events();
        let _ = conv.process_chunk(&text_chunk("Hello"));
        let _end_events = conv.emit_end_events();

        let response = conv.make_response(Status::Completed, vec![]);
        assert_eq!(
            response.previous_response_id.as_deref(),
            Some("resp_prev_123")
        );
    }

    /// Without context, previous_response_id is None.
    #[test]
    fn test_without_context_defaults() {
        let params = ResponseParams::default();
        let conv = ResponseStreamConverter::new("test-model".into(), params);

        let response = conv.make_response(Status::Completed, vec![]);
        assert_eq!(response.previous_response_id, None);
    }

    #[test]
    fn test_stream_response_echoes_parallel_tool_calls() {
        let params = ResponseParams {
            parallel_tool_calls: Some(false),
            ..Default::default()
        };
        let conv = ResponseStreamConverter::new("test-model".into(), params);

        let response = conv.make_response(Status::Completed, vec![]);
        assert_eq!(response.parallel_tool_calls, Some(false));
    }

    #[test]
    fn test_append_chunk_events_preserves_order() {
        let mut conv = ResponseStreamConverter::new("test-model".into(), default_params());
        let mut events = Vec::with_capacity(4);

        conv.append_chunk_events(&text_chunk("Hello"), &mut events);

        assert_eq!(
            event_types(&events),
            vec![
                "response.output_item.added".to_string(),
                "response.content_part.added".to_string(),
                "response.output_text.delta".to_string(),
            ]
        );

        events.clear();
        conv.append_chunk_events(
            &tool_call_chunk(0, Some("call-1"), Some("lookup"), Some("{\"q\":\"x\"}")),
            &mut events,
        );

        assert_eq!(
            event_types(&events),
            vec![
                "response.output_item.added".to_string(),
                "response.function_call_arguments.delta".to_string(),
            ]
        );
    }

    #[test]
    fn test_optimized_stream_event_serializer_matches_patched_json() {
        let params = ResponseParams {
            presence_penalty: Some(0.25),
            frequency_penalty: Some(0.5),
            store: Some(true),
            ..Default::default()
        };
        let mut conv = ResponseStreamConverter::new("test-model".into(), params.clone());

        let response_event = ResponseStreamEvent::ResponseCreated(ResponseCreatedEvent {
            sequence_number: conv.next_seq(),
            response: conv.make_response(Status::InProgress, vec![]),
        });
        let text_event = ResponseStreamEvent::ResponseOutputTextDelta(ResponseTextDeltaEvent {
            sequence_number: conv.next_seq(),
            item_id: "msg_1".to_string(),
            output_index: 0,
            content_index: 0,
            delta: "line\nquote\"slash\\ cjk 漢字 emoji 🚀".to_string(),
            logprobs: Some(vec![]),
        });
        let tool_event = ResponseStreamEvent::ResponseFunctionCallArgumentsDone(
            ResponseFunctionCallArgumentsDoneEvent {
                name: Some("lookup".to_string()),
                sequence_number: conv.next_seq(),
                item_id: "fc_1".to_string(),
                output_index: 1,
                arguments: "{\"q\":\"x\"}".to_string(),
            },
        );
        let completed_event = ResponseStreamEvent::ResponseCompleted(ResponseCompletedEvent {
            sequence_number: conv.next_seq(),
            response: conv.make_response(Status::Completed, vec![]),
        });

        for event in [&response_event, &text_event, &tool_event, &completed_event] {
            assert_eq!(
                optimized_event_json(&conv, event),
                legacy_event_json(event, &params)
            );
        }

        let response_json = optimized_event_json(&conv, &response_event);
        assert_eq!(response_json["response"]["presence_penalty"], 0.25);
        assert_eq!(response_json["response"]["frequency_penalty"], 0.5);
        assert_eq!(response_json["response"]["store"], true);
        assert!(response_json["response"]["max_tool_calls"].is_null());
    }
}