adk-model 3.0.0

LLM model integrations for Rust Agent Development Kit (ADK-Rust) (Gemini, OpenAI, Claude, DeepSeek, etc.)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
//! Agent-facing `Llm` adapter and extension-bag helpers for OpenRouter.
#![allow(missing_docs)]

use super::OPENROUTER_EXTENSION_NAMESPACE;
use super::chat::{
    OpenRouterChatMessageContent, OpenRouterChatRequest, OpenRouterChatResponse,
    OpenRouterChatToolCall, OpenRouterFunctionDescription, OpenRouterImageConfig, OpenRouterPlugin,
    OpenRouterProviderPreferences, OpenRouterReasoningConfig, OpenRouterResponseFormat,
    OpenRouterTool, OpenRouterToolChoice,
};
use super::client::OpenRouterClient;
use super::config::OpenRouterApiMode;
use super::convert_chat::{
    adk_contents_to_chat_messages, augment_chat_plugins_for_contents,
    chat_message_reasoning_to_parts,
};
use super::convert_responses::{
    adk_contents_to_response_input, responses_reasoning_items_to_parts,
};
use super::metadata::{
    chat_response_citation_metadata, chat_response_provider_metadata, chat_usage_to_metadata,
    responses_citation_metadata, responses_provider_metadata, responses_usage_to_metadata,
};
use super::responses::{
    OpenRouterResponse, OpenRouterResponseOutputItem, OpenRouterResponseTextConfig,
    OpenRouterResponseTool, OpenRouterResponsesRequest,
};
use crate::retry::{execute_with_retry, is_retryable_model_error};
use adk_core::{
    AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, GenerateContentConfig, Llm,
    LlmRequest, LlmResponse, LlmResponseStream, Part, Result,
};
use async_stream::try_stream;
use async_trait::async_trait;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use std::collections::BTreeMap;

/// Agent-facing OpenRouter options serialized into `GenerateContentConfig::extensions["openrouter"]`.
///
/// These options let callers select the native OpenRouter API mode and pass
/// OpenRouter-specific request parameters through the generic ADK request layer
/// without losing them during serialization.
///
/// # Example
///
/// ```rust
/// use adk_core::GenerateContentConfig;
/// use adk_model::openrouter::{OpenRouterApiMode, OpenRouterRequestOptions};
///
/// let mut config = GenerateContentConfig::default();
/// OpenRouterRequestOptions::default()
///     .with_api_mode(OpenRouterApiMode::Responses)
///     .with_route("fallback")
///     .insert_into_config(&mut config)
///     .expect("options should serialize");
///
/// assert!(config.extensions.contains_key("openrouter"));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct OpenRouterRequestOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_mode: Option<OpenRouterApiMode>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub models: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugins: Option<Vec<OpenRouterPlugin>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response_tools: Option<Vec<OpenRouterResponseTool>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<OpenRouterProviderPreferences>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<OpenRouterReasoningConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_details: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_cache_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modalities: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image_config: Option<OpenRouterImageConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trace: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<OpenRouterToolChoice>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parallel_tool_calls: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response_text: Option<OpenRouterResponseTextConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response_format: Option<OpenRouterResponseFormat>,
    #[serde(default, flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl OpenRouterRequestOptions {
    /// Set the native OpenRouter API mode used by the adapter.
    #[must_use]
    pub fn with_api_mode(mut self, api_mode: OpenRouterApiMode) -> Self {
        self.api_mode = Some(api_mode);
        self
    }

    /// Set fallback models for OpenRouter routing.
    #[must_use]
    pub fn with_models(mut self, models: Vec<String>) -> Self {
        self.models = Some(models);
        self
    }

    /// Set OpenRouter route selection.
    #[must_use]
    pub fn with_route(mut self, route: impl Into<String>) -> Self {
        self.route = Some(route.into());
        self
    }

    /// Append one chat plugin.
    #[must_use]
    pub fn with_plugin(mut self, plugin: OpenRouterPlugin) -> Self {
        self.plugins.get_or_insert_with(Vec::new).push(plugin);
        self
    }

    /// Append one Responses API server tool.
    #[must_use]
    pub fn with_response_tool(mut self, tool: OpenRouterResponseTool) -> Self {
        self.response_tools.get_or_insert_with(Vec::new).push(tool);
        self
    }

    /// Set OpenRouter provider preferences.
    #[must_use]
    pub fn with_provider_preferences(mut self, provider: OpenRouterProviderPreferences) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Set OpenRouter reasoning configuration.
    #[must_use]
    pub fn with_reasoning(mut self, reasoning: OpenRouterReasoningConfig) -> Self {
        self.reasoning = Some(reasoning);
        self
    }

    /// Set a previous response ID for Responses API chaining.
    #[must_use]
    pub fn with_previous_response_id(mut self, previous_response_id: impl Into<String>) -> Self {
        self.previous_response_id = Some(previous_response_id.into());
        self
    }

    /// Set a prompt cache key for the Responses API.
    #[must_use]
    pub fn with_prompt_cache_key(mut self, prompt_cache_key: impl Into<String>) -> Self {
        self.prompt_cache_key = Some(prompt_cache_key.into());
        self
    }

    /// Set requested response modalities.
    #[must_use]
    pub fn with_modalities(mut self, modalities: Vec<String>) -> Self {
        self.modalities = Some(modalities);
        self
    }

    /// Set Responses API include fields.
    #[must_use]
    pub fn with_include(mut self, include: Vec<String>) -> Self {
        self.include = Some(include);
        self
    }

    /// Serialize the options into a JSON extension value.
    pub fn to_extension_value(&self) -> Result<Value> {
        serde_json::to_value(self).map_err(|err| {
            AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::Internal,
                "model.openrouter.request_options_serialize_failed",
                "Failed to serialize OpenRouter request options",
            )
            .with_provider("openrouter")
            .with_source(err)
        })
    }

    /// Deserialize the options from a JSON extension value.
    pub fn from_extension_value(value: &Value) -> Result<Self> {
        serde_json::from_value(value.clone()).map_err(|err| {
            AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.openrouter.invalid_request_options",
                "OpenRouter extension options are not valid JSON for OpenRouterRequestOptions",
            )
            .with_provider("openrouter")
            .with_source(err)
        })
    }

    /// Extract OpenRouter request options from `GenerateContentConfig`.
    pub fn from_generate_config(config: Option<&GenerateContentConfig>) -> Result<Option<Self>> {
        config
            .and_then(|config| config.extensions.get(OPENROUTER_EXTENSION_NAMESPACE))
            .map(Self::from_extension_value)
            .transpose()
    }

    /// Insert the serialized options into `GenerateContentConfig::extensions`.
    pub fn insert_into_config(&self, config: &mut GenerateContentConfig) -> Result<()> {
        config
            .extensions
            .insert(OPENROUTER_EXTENSION_NAMESPACE.to_string(), self.to_extension_value()?);
        Ok(())
    }
}

#[async_trait]
impl Llm for OpenRouterClient {
    fn name(&self) -> &str {
        self.model()
    }

    // OpenRouter routes on to the upstream it picks; the request leaves for OpenRouter.
    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
        vec![adk_core::DataDestination::of_url("openrouter", self.config().effective_base_url())]
    }

    #[tracing::instrument(
        name = "model.generate_content",
        skip_all,
        fields(
            model.name = %self.name(),
            stream = %stream,
            request.contents_count = %request.contents.len(),
            request.tools_count = %request.tools.len()
        )
    )]
    async fn generate_content(
        &self,
        mut request: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream> {
        let request_options =
            OpenRouterRequestOptions::from_generate_config(request.config.as_ref())?
                .unwrap_or_default();
        let model_name = effective_model_name(self, &request);
        // Native items reach this provider only from the turns its own origin marks.
        adk_core::history::retain_replayable(
            &mut request.contents,
            &adk_core::history::ProviderOrigin::new("openrouter", &model_name),
        );
        let api_mode = request_options.api_mode.unwrap_or(self.config().default_api_mode);
        let usage_span =
            crate::telemetry::inference_span("openrouter", &model_name, stream, &request);

        let response_stream = match api_mode {
            OpenRouterApiMode::ChatCompletions => {
                build_chat_llm_stream(self, request, &request_options, stream).await?
            }
            OpenRouterApiMode::Responses => {
                build_responses_llm_stream(self, request, &request_options, stream).await?
            }
        };

        Ok(crate::usage_tracking::with_priced_usage_tracking(
            response_stream,
            usage_span,
            "openrouter",
            model_name,
        ))
    }
}

async fn build_chat_llm_stream(
    client: &OpenRouterClient,
    request: LlmRequest,
    request_options: &OpenRouterRequestOptions,
    stream: bool,
) -> Result<LlmResponseStream> {
    let native_request = build_chat_request(client, &request, request_options, stream)?;

    if stream {
        let native_request_for_retry = native_request.clone();
        let native_stream =
            execute_with_retry(client.retry_config(), is_retryable_model_error, || {
                let native_request = native_request_for_retry.clone();
                async move { client.send_chat_stream(native_request).await }
            })
            .await?;

        let response_stream = try_stream! {
            let mut native_stream = native_stream;
            let mut state = ChatStreamState::default();
            let mut final_parts = Vec::new();
            let mut final_finish_reason = None;
            let mut final_usage_metadata = None;
            // Each chunk carries the log probabilities of its own tokens.
            let mut logprobs = Vec::new();
            // A finish reason or `[DONE]` marks a complete response; without one the
            // answer or a tool call may be truncated.
            let mut finished = false;
            // The model declined in `delta.refusal`.
            let mut refused = false;

            while let Some(item) = native_stream.next().await {
                match item? {
                    super::stream::OpenRouterChatStreamItem::Chunk(chunk) => {
                        if let Some(usage_metadata) = chunk.usage.as_ref().map(chat_usage_to_metadata) {
                            final_usage_metadata = Some(usage_metadata);
                        }

                        if let Some(choice) = chunk.choices.first() {
                            logprobs.extend(
                                choice
                                    .logprobs
                                    .as_ref()
                                    .and_then(|logprobs| logprobs.get("content"))
                                    .and_then(Value::as_array)
                                    .into_iter()
                                    .flatten()
                                    .cloned(),
                            );
                            if let Some(delta) = choice.delta.as_ref() {
                                let (reasoning_parts, reasoning_metadata) =
                                    chat_message_reasoning_to_parts(delta);
                                if let Some(response) = llm_stream_response(
                                    reasoning_parts,
                                    None,
                                    None,
                                    reasoning_metadata,
                                    true,
                                    false,
                                ) {
                                    yield response;
                                }

                                let mut text_parts = chat_content_to_parts(delta.content.as_ref());
                                if let Some(refusal) = delta.refusal.as_ref().filter(|r| !r.is_empty()) {
                                    refused = true;
                                    text_parts.push(Part::Text { text: refusal.clone() });
                                }
                                if let Some(response) = llm_stream_response(
                                    text_parts,
                                    None,
                                    None,
                                    None,
                                    true,
                                    false,
                                ) {
                                    yield response;
                                }

                                if let Some(tool_calls) = delta.tool_calls.as_ref() {
                                    state.capture_chat_tool_calls(tool_calls);
                                }
                            }

                            if let Some(finish_reason) = choice.finish_reason.as_deref() {
                                if finish_reason == "error" {
                                    Err(crate::stream_error::reported(
                                        "openrouter",
                                        "model.openrouter.stream_error",
                                        &Value::Null,
                                    ))?;
                                }
                                final_parts.extend(state.drain_chat_tool_calls()?);
                                final_finish_reason =
                                    Some(chat_finish_reason(choice, finish_reason, refused));
                                finished = true;
                            }
                        }
                    }
                    super::stream::OpenRouterChatStreamItem::Done => {
                        if state.has_pending_tool_calls() {
                            Err(chat_stream_incomplete("its tool calls finished"))?;
                        }
                        finished = true;
                        if let Some(response) = llm_stream_response(
                            std::mem::take(&mut final_parts),
                            final_usage_metadata.take(),
                            final_finish_reason.take(),
                            logprobs_metadata(std::mem::take(&mut logprobs)),
                            false,
                            true,
                        ) {
                            yield response;
                        }
                    }
                    super::stream::OpenRouterChatStreamItem::Error(_) => unreachable!(),
                }
            }

            if !finished {
                Err(chat_stream_incomplete(if state.has_pending_tool_calls() {
                    "its tool calls finished"
                } else {
                    "the response finished"
                }))?;
            }

            if let Some(response) = llm_stream_response(
                final_parts,
                final_usage_metadata,
                final_finish_reason,
                logprobs_metadata(logprobs),
                false,
                true,
            ) {
                yield response;
            }
        };

        Ok(Box::pin(response_stream))
    } else {
        let native_request_for_retry = native_request.clone();
        let response = execute_with_retry(client.retry_config(), is_retryable_model_error, || {
            let native_request = native_request_for_retry.clone();
            async move { client.send_chat(native_request).await }
        })
        .await?;
        let mapped = chat_response_to_llm_response(&response);
        let response_stream = try_stream! {
            yield mapped;
        };

        Ok(Box::pin(response_stream))
    }
}

fn chat_stream_incomplete(unfinished: &str) -> AdkError {
    crate::stream_error::incomplete(
        "OpenRouter chat",
        "model.openrouter.chat_stream_incomplete",
        unfinished,
    )
    .with_provider("openrouter")
}

async fn build_responses_llm_stream(
    client: &OpenRouterClient,
    request: LlmRequest,
    request_options: &OpenRouterRequestOptions,
    stream: bool,
) -> Result<LlmResponseStream> {
    let native_request = build_responses_request(client, &request, request_options, stream)?;

    if stream {
        let native_request_for_retry = native_request.clone();
        let native_stream =
            execute_with_retry(client.retry_config(), is_retryable_model_error, || {
                let native_request = native_request_for_retry.clone();
                async move { client.create_response_stream(native_request).await }
            })
            .await?;

        // Text and reasoning stream as partial deltas. Tool calls and the complete content
        // come only with the terminal event, so a stream that ends without one never
        // yields a tool call, and the terminal content replaces the deltas instead of
        // repeating them.
        let response_stream = try_stream! {
            let mut native_stream = native_stream;

            while let Some(item) = native_stream.next().await {
                match item? {
                    super::stream::OpenRouterResponsesStreamItem::Event(event) => {
                        match event.kind.as_str() {
                            "response.output_text.delta" => {
                                if let Some(delta) = event.delta.as_deref()
                                    && let Some(response) = llm_stream_response(
                                        vec![Part::Text { text: delta.to_string() }],
                                        None,
                                        None,
                                        None,
                                        true,
                                        false,
                                    ) {
                                        yield response;
                                    }
                            }
                            "response.reasoning.delta"
                            | "response.reasoning_text.delta"
                            | "response.reasoning_summary_text.delta" => {
                                if let Some(delta) = event.delta.as_deref().or(event.text.as_deref())
                                    && let Some(response) = llm_stream_response(
                                        vec![Part::Thinking {
                                            thinking: delta.to_string(),
                                            signature: None,
                                        }],
                                        None,
                                        None,
                                        None,
                                        true,
                                        false,
                                    ) {
                                        yield response;
                                    }
                            }
                            "response.failed" => {
                                Err(super::error::response_failed_to_adk_error(
                                    event.response.as_ref().and_then(|response| response.error.as_ref()),
                                ))?;
                            }
                            "response.completed" | "response.incomplete" => {
                                let response = event.response.as_ref().ok_or_else(|| {
                                    AdkError::new(
                                        ErrorComponent::Model,
                                        ErrorCategory::Internal,
                                        "model.openrouter.responses_stream_invalid_event",
                                        "OpenRouter responses stream ended with a terminal event that carries no response",
                                    )
                                    .with_provider("openrouter")
                                })?;
                                if let Some(mut mapped) = responses_terminal_to_llm_response(response)? {
                                    mapped
                                        .provider_metadata
                                        .get_or_insert_with(|| json!({}))["content_complete"] = json!(true);
                                    yield mapped;
                                }
                                return;
                            }
                            _ => {}
                        }
                    }
                    // `[DONE]` follows the terminal event; on its own it finishes nothing.
                    super::stream::OpenRouterResponsesStreamItem::Done => {}
                    super::stream::OpenRouterResponsesStreamItem::Error(_) => unreachable!(),
                }
            }

            Err(crate::stream_error::incomplete(
                "OpenRouter responses",
                "model.openrouter.responses_stream_incomplete",
                "the response finished",
            )
            .with_provider("openrouter"))?;
        };

        Ok(Box::pin(response_stream))
    } else {
        let native_request_for_retry = native_request.clone();
        let response = execute_with_retry(client.retry_config(), is_retryable_model_error, || {
            let native_request = native_request_for_retry.clone();
            async move { client.create_response(native_request).await }
        })
        .await?;
        let mapped = responses_terminal_to_llm_response(&response)?;
        let response_stream = try_stream! {
            if let Some(mapped) = mapped {
                yield mapped;
            }
        };

        Ok(Box::pin(response_stream))
    }
}

/// Maps a finished Responses API payload, failing for a status that is not a finished
/// answer: `failed`, `cancelled`, or `incomplete` for a reason other than the output limit
/// or a content filter.
fn responses_terminal_to_llm_response(
    response: &OpenRouterResponse,
) -> Result<Option<LlmResponse>> {
    let failure = |category: ErrorCategory, code: &'static str, message: &'static str| {
        AdkError::new(ErrorComponent::Model, category, code, message).with_provider("openrouter")
    };
    match response.status.as_deref() {
        Some("failed") => {
            return Err(super::error::response_failed_to_adk_error(response.error.as_ref()));
        }
        Some("cancelled") => {
            return Err(failure(
                ErrorCategory::Cancelled,
                "model.openrouter.response_cancelled",
                "OpenRouter response was cancelled",
            ));
        }
        Some("incomplete")
            if !matches!(
                response
                    .incomplete_details
                    .as_ref()
                    .and_then(|details| details.get("reason"))
                    .and_then(Value::as_str),
                Some("max_output_tokens" | "content_filter")
            ) =>
        {
            return Err(failure(
                ErrorCategory::Internal,
                "model.openrouter.response_incomplete",
                "OpenRouter response is incomplete",
            ));
        }
        _ => {}
    }
    responses_response_to_llm_response(response)
}

fn build_chat_request(
    client: &OpenRouterClient,
    request: &LlmRequest,
    request_options: &OpenRouterRequestOptions,
    stream: bool,
) -> Result<OpenRouterChatRequest> {
    crate::generation_config::reject_unsupported(
        "openrouter",
        request.config.as_ref(),
        crate::generation_config::Supports {
            stop_sequences: true,
            seed: true,
            penalties: true,
            top_logprobs: true,
        },
    )?;
    let mut chat_request = OpenRouterChatRequest {
        model: effective_model_name(client, request),
        messages: adk_contents_to_chat_messages(&request.contents)?,
        tools: chat_tools_from_llm_request(&request.tools),
        tool_choice: request_options.tool_choice.clone(),
        parallel_tool_calls: request_options.parallel_tool_calls,
        plugins: chat_plugins_for_request(&request.contents, request_options),
        provider: request_options.provider.clone(),
        models: request_options.models.clone(),
        route: request_options.route.clone(),
        reasoning: request_options.reasoning.clone(),
        reasoning_content: request_options.reasoning_content.clone(),
        reasoning_details: request_options.reasoning_details.clone(),
        response_format: request_options.response_format.clone(),
        modalities: request_options.modalities.clone(),
        image_config: request_options.image_config.clone(),
        metadata: request_options.metadata.clone(),
        session_id: request_options.session_id.clone(),
        trace: request_options.trace.clone(),
        stream: stream.then_some(true),
        stream_options: stream.then_some(json!({ "include_usage": true })),
        user: request_options.user.clone(),
        extra: request_options.extra.clone(),
        ..Default::default()
    };

    if let Some(config) = request.config.as_ref() {
        apply_generate_config_to_chat_request(&mut chat_request, config, &request.model);
    }

    Ok(chat_request)
}

fn build_responses_request(
    client: &OpenRouterClient,
    request: &LlmRequest,
    request_options: &OpenRouterRequestOptions,
    stream: bool,
) -> Result<OpenRouterResponsesRequest> {
    let mut responses_request = OpenRouterResponsesRequest {
        input: Some(adk_contents_to_response_input(&request.contents)?),
        instructions: request_options.instructions.clone(),
        metadata: request_options.metadata.clone(),
        tools: responses_tools_from_llm_request(&request.tools, request_options),
        tool_choice: request_options.tool_choice.clone(),
        parallel_tool_calls: request_options.parallel_tool_calls,
        model: Some(effective_model_name(client, request)),
        models: request_options.models.clone(),
        text: request_options.response_text.clone(),
        reasoning: request_options.reasoning.clone(),
        reasoning_content: request_options.reasoning_content.clone(),
        reasoning_details: request_options.reasoning_details.clone(),
        image_config: request_options.image_config.clone(),
        modalities: request_options.modalities.clone(),
        prompt_cache_key: request_options.prompt_cache_key.clone(),
        previous_response_id: request_options.previous_response_id.clone(),
        include: request_options.include.clone(),
        stream: stream.then_some(true),
        provider: request_options.provider.clone(),
        route: request_options.route.clone(),
        session_id: request_options.session_id.clone(),
        trace: request_options.trace.clone(),
        user: request_options.user.clone(),
        plugins: request_options.plugins.clone(),
        extra: request_options.extra.clone(),
        ..Default::default()
    };

    if let Some(config) = request.config.as_ref() {
        // OpenRouter's Responses API has no `seed`.
        crate::generation_config::reject_unsupported(
            "OpenRouter Responses",
            Some(config),
            crate::generation_config::Supports {
                stop_sequences: true,
                seed: false,
                penalties: true,
                top_logprobs: true,
            },
        )
        .map_err(|error| error.with_provider("openrouter"))?;
        apply_generate_config_to_responses_request(&mut responses_request, config, &request.model);
    }

    Ok(responses_request)
}

fn effective_model_name(client: &OpenRouterClient, request: &LlmRequest) -> String {
    if request.model.trim().is_empty() { client.model().to_string() } else { request.model.clone() }
}

fn chat_tools_from_llm_request(tools: &adk_core::ToolDeclarations) -> Option<Vec<OpenRouterTool>> {
    (!tools.is_empty()).then_some(
        tools
            .iter()
            .map(|(name, declaration)| OpenRouterTool {
                kind: "function".to_string(),
                function: Some(OpenRouterFunctionDescription {
                    name: name.clone(),
                    description: declaration
                        .get("description")
                        .and_then(Value::as_str)
                        .map(ToString::to_string),
                    parameters: declaration.get("parameters").cloned(),
                    ..Default::default()
                }),
                ..Default::default()
            })
            .collect(),
    )
}

fn responses_tools_from_llm_request(
    tools: &adk_core::ToolDeclarations,
    request_options: &OpenRouterRequestOptions,
) -> Option<Vec<OpenRouterResponseTool>> {
    let mut response_tools = tools
        .iter()
        .map(|(name, declaration)| OpenRouterResponseTool {
            kind: "function".to_string(),
            name: Some(name.clone()),
            description: declaration
                .get("description")
                .and_then(Value::as_str)
                .map(ToString::to_string),
            parameters: declaration.get("parameters").cloned(),
            strict: declaration.get("strict").and_then(Value::as_bool),
            ..Default::default()
        })
        .collect::<Vec<_>>();

    if let Some(extra_tools) = request_options.response_tools.as_ref() {
        response_tools.extend(extra_tools.clone());
    }

    (!response_tools.is_empty()).then_some(response_tools)
}

fn chat_plugins_for_request(
    contents: &[Content],
    request_options: &OpenRouterRequestOptions,
) -> Option<Vec<OpenRouterPlugin>> {
    let plugins = augment_chat_plugins_for_contents(
        contents,
        request_options.plugins.clone().unwrap_or_default(),
    );
    (!plugins.is_empty()).then_some(plugins)
}

/// The reasoning of one request (spec 3.1 §7.23, §10 C4): the request's `effort` becomes
/// `reasoning.effort` unless the `openrouter` options already choose an effort, a token
/// budget, or no reasoning, which are provider-specific and win.
fn request_reasoning(
    options: Option<OpenRouterReasoningConfig>,
    config: &GenerateContentConfig,
) -> Option<OpenRouterReasoningConfig> {
    let Some(level) = config.effort else {
        return options;
    };
    let mut reasoning = options.unwrap_or_default();
    if reasoning.effort.is_some()
        || reasoning.max_tokens.is_some()
        || reasoning.enabled == Some(false)
    {
        tracing::debug!(
            effort = %level,
            "openrouter reasoning options choose the reasoning; the request's effort is ignored"
        );
        return Some(reasoning);
    }
    reasoning.effort = Some(level.as_str().to_string());
    Some(reasoning)
}

fn apply_generate_config_to_chat_request(
    request: &mut OpenRouterChatRequest,
    config: &GenerateContentConfig,
    model_name: &str,
) {
    request.reasoning = request_reasoning(request.reasoning.take(), config);
    request.temperature = config.temperature;
    request.top_p = config.top_p;
    request.max_completion_tokens = config.max_output_tokens;
    request.frequency_penalty = config.frequency_penalty;
    request.presence_penalty = config.presence_penalty;
    request.seed = config.seed;
    request.top_logprobs = config.top_logprobs;

    if !config.stop_sequences.is_empty() {
        request.stop =
            Some(Value::Array(config.stop_sequences.iter().cloned().map(Value::String).collect()));
    }

    if request.response_format.is_none() {
        request.response_format =
            config.response_schema.as_ref().map(|schema| OpenRouterResponseFormat {
                kind: "json_schema".to_string(),
                json_schema: Some(json!({
                    "name": sanitized_schema_name(model_name),
                    "schema": schema,
                    "strict": true
                })),
                ..Default::default()
            });
    }
}

fn apply_generate_config_to_responses_request(
    request: &mut OpenRouterResponsesRequest,
    config: &GenerateContentConfig,
    model_name: &str,
) {
    request.reasoning = request_reasoning(request.reasoning.take(), config);
    request.temperature = config.temperature;
    request.top_p = config.top_p;
    request.top_k = config.top_k;
    request.max_output_tokens = config.max_output_tokens;
    request.frequency_penalty = config.frequency_penalty;
    request.presence_penalty = config.presence_penalty;
    request.top_logprobs = config.top_logprobs;

    if !config.stop_sequences.is_empty() {
        request.extra.insert(
            "stop".to_string(),
            Value::Array(config.stop_sequences.iter().cloned().map(Value::String).collect()),
        );
    }

    if let Some(schema) = config.response_schema.as_ref() {
        let mut text_config = request.text.clone().unwrap_or_default();
        if text_config.format.is_none() {
            text_config.format = Some(json!({
                "type": "json_schema",
                "name": sanitized_schema_name(model_name),
                "schema": schema,
                "strict": true
            }));
        }
        request.text = Some(text_config);
    }
}

fn sanitized_schema_name(model_name: &str) -> String {
    model_name.replace(['-', '.', '/'], "_")
}

fn chat_response_to_llm_response(response: &OpenRouterChatResponse) -> LlmResponse {
    let mut parts = Vec::new();
    let mut provider_metadata = Map::new();

    if let Some(choice) = response.choices.first() {
        if let Some(message) = choice.message.as_ref() {
            let (reasoning_parts, reasoning_metadata) = chat_message_reasoning_to_parts(message);
            parts.extend(reasoning_parts);
            parts.extend(chat_content_to_parts(message.content.as_ref()));
            if let Some(refusal) = message.refusal.as_ref().filter(|r| !r.is_empty()) {
                parts.push(Part::Text { text: refusal.clone() });
            }
            parts.extend(chat_tool_calls_to_parts(message.tool_calls.as_ref()));
            merge_metadata_object(&mut provider_metadata, reasoning_metadata);
        }

        if let Some(logprobs) = choice.logprobs.clone() {
            provider_metadata.insert("logprobs".to_string(), logprobs);
        }
        if !choice.extra.is_empty() {
            provider_metadata.insert("choice_extra".to_string(), json!(choice.extra));
        }
    }

    merge_metadata_object(&mut provider_metadata, chat_response_provider_metadata(response));

    if let Some(system_fingerprint) = response.system_fingerprint.as_ref() {
        provider_metadata
            .insert("system_fingerprint".to_string(), Value::String(system_fingerprint.clone()));
    }
    if !response.extra.is_empty() {
        provider_metadata.insert("response_extra".to_string(), json!(response.extra));
    }

    LlmResponse {
        content: (!parts.is_empty()).then_some(Content { role: "model".to_string(), parts }),
        usage_metadata: response.usage.as_ref().map(chat_usage_to_metadata),
        finish_reason: response.choices.first().and_then(|choice| {
            let refused = choice
                .message
                .as_ref()
                .and_then(|message| message.refusal.as_ref())
                .is_some_and(|refusal| !refusal.is_empty());
            choice
                .finish_reason
                .as_deref()
                .map(|finish_reason| chat_finish_reason(choice, finish_reason, refused))
        }),
        citation_metadata: chat_response_citation_metadata(response),
        partial: false,
        turn_complete: true,
        interrupted: false,
        error_code: None,
        error_message: None,
        provider_metadata: (!provider_metadata.is_empty())
            .then_some(Value::Object(provider_metadata)),
        interaction_id: None,
        model: None,
        provider: None,
    }
}

fn responses_response_to_llm_response(
    response: &OpenRouterResponse,
) -> Result<Option<LlmResponse>> {
    let mut parts = Vec::new();
    let mut provider_metadata = Map::new();

    let (reasoning_parts, reasoning_metadata) =
        responses_reasoning_items_to_parts(&response.output);
    parts.extend(reasoning_parts);
    merge_metadata_object(&mut provider_metadata, reasoning_metadata);

    for item in &response.output {
        match item.kind.as_str() {
            "message" => parts.extend(response_message_item_to_parts(item)),
            "function_call" => parts.push(response_function_call_part(item)?),
            _ => {}
        }
    }

    merge_metadata_object(&mut provider_metadata, responses_provider_metadata(response));
    // Requested through `top_logprobs`; the tokens of every `output_text` part, in order.
    let logprobs: Vec<Value> = response
        .output
        .iter()
        .filter(|item| item.kind == "message")
        .filter_map(|item| item.content.as_ref().and_then(Value::as_array))
        .flatten()
        .filter_map(|part| part.get("logprobs").and_then(Value::as_array))
        .flatten()
        .cloned()
        .collect();
    merge_metadata_object(&mut provider_metadata, logprobs_metadata(logprobs));

    if let Some(previous_response_id) = response.previous_response_id.as_ref() {
        provider_metadata.insert(
            "previous_response_id".to_string(),
            Value::String(previous_response_id.clone()),
        );
    }
    if let Some(incomplete_details) = response.incomplete_details.clone() {
        provider_metadata.insert("incomplete_details".to_string(), incomplete_details);
    }
    if let Some(error) = response.error.clone() {
        provider_metadata.insert("error".to_string(), error);
    }
    if !response.extra.is_empty() {
        provider_metadata.insert("response_extra".to_string(), json!(response.extra));
    }

    let usage_metadata = response.usage.as_ref().map(responses_usage_to_metadata);
    let finish_reason = responses_finish_reason(response);
    let citation_metadata = responses_citation_metadata(response);
    let content = (!parts.is_empty()).then_some(Content { role: "model".to_string(), parts });

    if content.is_none()
        && usage_metadata.is_none()
        && finish_reason.is_none()
        && citation_metadata.is_none()
        && provider_metadata.is_empty()
    {
        return Ok(None);
    }

    Ok(Some(LlmResponse {
        content,
        usage_metadata,
        finish_reason,
        citation_metadata,
        partial: false,
        turn_complete: true,
        interrupted: false,
        error_code: None,
        error_message: None,
        provider_metadata: (!provider_metadata.is_empty())
            .then_some(Value::Object(provider_metadata)),
        interaction_id: None,
        model: None,
        provider: None,
    }))
}

fn chat_content_to_parts(content: Option<&OpenRouterChatMessageContent>) -> Vec<Part> {
    match content {
        Some(OpenRouterChatMessageContent::Text(text)) if !text.is_empty() => {
            vec![Part::Text { text: text.clone() }]
        }
        Some(OpenRouterChatMessageContent::Parts(parts)) => parts
            .iter()
            .filter_map(|part| {
                (part.kind == "text")
                    .then_some(part.text.as_ref())
                    .flatten()
                    .filter(|text| !text.is_empty())
                    .map(|text| Part::Text { text: text.clone() })
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn chat_tool_calls_to_parts(tool_calls: Option<&Vec<OpenRouterChatToolCall>>) -> Vec<Part> {
    tool_calls.into_iter().flatten().filter_map(chat_tool_call_to_part).collect()
}

fn chat_tool_call_to_part(tool_call: &OpenRouterChatToolCall) -> Option<Part> {
    let function = tool_call.function.as_ref()?;
    let name = function.name.clone()?;
    // Undecodable arguments keep the call, marked invalid, so the agent answers it with an
    // error instead of the turn ending as if the model had never made it.
    let args = crate::tool_args::streamed_tool_arguments(
        "openrouter",
        &name,
        function.arguments.as_deref().unwrap_or_default(),
    );

    Some(Part::FunctionCall { name, args, id: tool_call.id.clone(), thought_signature: None })
}

fn response_message_item_to_parts(item: &OpenRouterResponseOutputItem) -> Vec<Part> {
    item.content
        .as_ref()
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|part| {
            let field = match part.get("type").and_then(Value::as_str) {
                Some("output_text") => "text",
                Some("refusal") => "refusal",
                _ => return None,
            };
            part.get(field)
                .and_then(Value::as_str)
                .filter(|text| !text.is_empty())
                .map(|text| Part::Text { text: text.to_string() })
        })
        .collect()
}

/// Maps a `function_call` output item. An unfinished or unnamed call fails the turn instead
/// of being dropped; arguments that are not a JSON object are marked with
/// [`adk_core::invalid_tool_arguments`], so the agent answers the call with an error.
fn response_function_call_part(item: &OpenRouterResponseOutputItem) -> Result<Part> {
    let invalid = |message: &'static str| {
        AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::Internal,
            "model.openrouter.invalid_tool_call",
            message,
        )
        .with_provider("openrouter")
    };
    let name = item
        .name
        .clone()
        .ok_or_else(|| invalid("OpenRouter returned a tool call without a name"))?;
    if item.status.as_deref().is_some_and(|status| status != "completed") {
        return Err(invalid("OpenRouter returned an unfinished tool call"));
    }
    let args = crate::tool_args::streamed_tool_arguments(
        "openrouter",
        &name,
        item.arguments.as_deref().unwrap_or_default(),
    );

    Ok(Part::FunctionCall {
        name,
        args,
        id: item.call_id.clone().or_else(|| item.id.clone()),
        thought_signature: None,
    })
}

/// The finish reason of a chat choice.
///
/// OpenRouter normalizes `finish_reason` and keeps the provider's own value in
/// `native_finish_reason` (<https://openrouter.ai/docs/api-reference/overview#finish-reason>),
/// which is where a refusal or a malformed tool call shows: Anthropic's `refusal`, Gemini's
/// `MALFORMED_FUNCTION_CALL` and `UNEXPECTED_TOOL_CALL`, Bedrock's `malformed_tool_use`.
fn chat_finish_reason(
    choice: &super::chat::OpenRouterChatChoice,
    finish_reason: &str,
    refused: bool,
) -> FinishReason {
    let native = choice.extra.get("native_finish_reason").and_then(Value::as_str);
    match (finish_reason, native) {
        _ if refused => FinishReason::Refusal,
        (_, Some("refusal")) => FinishReason::Refusal,
        (_, Some("MALFORMED_FUNCTION_CALL" | "UNEXPECTED_TOOL_CALL" | "malformed_tool_use")) => {
            FinishReason::MalformedToolCall
        }
        ("stop" | "tool_calls" | "function_call", _) => FinishReason::Stop,
        ("length" | "max_tokens", _) => FinishReason::MaxTokens,
        ("content_filter" | "safety", _) => FinishReason::Safety,
        ("recitation", _) => FinishReason::Recitation,
        _ => FinishReason::Other,
    }
}

fn responses_finish_reason(response: &OpenRouterResponse) -> Option<FinishReason> {
    let refused = response
        .output
        .iter()
        .filter(|item| item.kind == "message")
        .filter_map(|item| item.content.as_ref().and_then(Value::as_array))
        .flatten()
        .any(|part| {
            part.get("type").and_then(Value::as_str) == Some("refusal")
                && part.get("refusal").and_then(Value::as_str).is_some_and(|r| !r.is_empty())
        });
    match response.status.as_deref() {
        Some("completed") if refused => Some(FinishReason::Refusal),
        Some("completed") => Some(FinishReason::Stop),
        Some("incomplete") => match response
            .incomplete_details
            .as_ref()
            .and_then(|details| details.get("reason"))
            .and_then(Value::as_str)
        {
            Some("max_output_tokens") => Some(FinishReason::MaxTokens),
            Some("content_filter") => Some(FinishReason::Safety),
            Some(_) | None => Some(FinishReason::Other),
        },
        Some("failed" | "cancelled") => Some(FinishReason::Other),
        _ => None,
    }
}

/// `{"logprobs": {"content": [...]}}`, the shape a complete chat response carries, or `None`
/// when no token has one.
fn logprobs_metadata(logprobs: Vec<Value>) -> Option<Value> {
    (!logprobs.is_empty()).then(|| json!({"logprobs": {"content": logprobs}}))
}

fn merge_metadata_object(target: &mut Map<String, Value>, value: Option<Value>) {
    if let Some(Value::Object(object)) = value {
        target.extend(object);
    }
}

fn llm_stream_response(
    parts: Vec<Part>,
    usage_metadata: Option<adk_core::UsageMetadata>,
    finish_reason: Option<FinishReason>,
    provider_metadata: Option<Value>,
    partial: bool,
    turn_complete: bool,
) -> Option<LlmResponse> {
    if parts.is_empty()
        && usage_metadata.is_none()
        && finish_reason.is_none()
        && provider_metadata.is_none()
    {
        return None;
    }

    Some(LlmResponse {
        content: (!parts.is_empty()).then_some(Content { role: "model".to_string(), parts }),
        usage_metadata,
        finish_reason,
        citation_metadata: None,
        partial,
        turn_complete,
        interrupted: false,
        error_code: None,
        error_message: None,
        provider_metadata,
        interaction_id: None,
        model: None,
        provider: None,
    })
}

#[derive(Debug, Default)]
struct ChatStreamState {
    pending_tool_calls: BTreeMap<usize, PendingChatToolCall>,
}

#[derive(Debug, Default)]
struct PendingChatToolCall {
    id: Option<String>,
    name: Option<String>,
    arguments: String,
}

impl ChatStreamState {
    fn capture_chat_tool_calls(&mut self, tool_calls: &[OpenRouterChatToolCall]) {
        for (pos, tool_call) in tool_calls.iter().enumerate() {
            // Key by the protocol `index` so fragments of distinct parallel tool
            // calls land in distinct buckets; fall back to stream position for
            // payloads that omit it (e.g. non-streaming, single-call deltas).
            let key = tool_call.index.unwrap_or(pos);
            let pending = self.pending_tool_calls.entry(key).or_default();
            if let Some(id) = tool_call.id.as_ref() {
                pending.id = Some(id.clone());
            }
            if let Some(function) = tool_call.function.as_ref() {
                if let Some(name) = function.name.as_ref() {
                    pending.name = Some(name.clone());
                }
                if let Some(arguments) = function.arguments.as_ref() {
                    pending.arguments.push_str(arguments);
                }
            }
        }
    }

    fn has_pending_tool_calls(&self) -> bool {
        !self.pending_tool_calls.is_empty()
    }

    /// Takes the accumulated tool calls. A call without a name fails the turn instead of
    /// being dropped; arguments that are not a JSON object are marked with
    /// [`adk_core::invalid_tool_arguments`].
    fn drain_chat_tool_calls(&mut self) -> Result<Vec<Part>> {
        std::mem::take(&mut self.pending_tool_calls)
            .into_values()
            .map(|pending| {
                let name = pending.name.ok_or_else(|| {
                    AdkError::new(
                        ErrorComponent::Model,
                        ErrorCategory::Internal,
                        "model.openrouter.invalid_tool_call",
                        "OpenRouter returned a tool call without a name",
                    )
                    .with_provider("openrouter")
                })?;
                let args = crate::tool_args::streamed_tool_arguments(
                    "openrouter",
                    &name,
                    &pending.arguments,
                );
                Ok(Part::FunctionCall { name, args, id: pending.id, thought_signature: None })
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::OpenRouterRequestOptions;
    use crate::openrouter::chat::{
        OpenRouterPlugin, OpenRouterProviderPreferences, OpenRouterReasoningConfig,
    };
    use crate::openrouter::responses::OpenRouterResponseTool;
    use crate::openrouter::{OpenRouterApiMode, OpenRouterClient, OpenRouterConfig};
    use adk_core::{GenerateContentConfig, Llm, LlmRequest, Part};
    use futures::StreamExt;
    use serde_json::json;
    use wiremock::matchers::{body_json, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn request_options_round_trip_through_extension_bag() {
        let options = OpenRouterRequestOptions::default()
            .with_api_mode(OpenRouterApiMode::Responses)
            .with_models(vec!["openai/gpt-5.2".to_string(), "openai/gpt-5-mini".to_string()])
            .with_route("fallback")
            .with_plugin(OpenRouterPlugin {
                id: "web".to_string(),
                enabled: Some(true),
                ..Default::default()
            })
            .with_response_tool(OpenRouterResponseTool {
                kind: "web_search".to_string(),
                ..Default::default()
            })
            .with_provider_preferences(OpenRouterProviderPreferences {
                zdr: Some(true),
                ..Default::default()
            })
            .with_reasoning(OpenRouterReasoningConfig {
                effort: Some("high".to_string()),
                ..Default::default()
            })
            .with_previous_response_id("resp_previous")
            .with_prompt_cache_key("cache-key")
            .with_modalities(vec!["text".to_string(), "image".to_string()])
            .with_include(vec!["reasoning.encrypted_content".to_string()]);

        let mut config = GenerateContentConfig::default();
        options.insert_into_config(&mut config).expect("options should insert into config");

        let request = LlmRequest::new("openai/gpt-5.2", vec![]).with_config(config);
        let round_trip_request: LlmRequest = serde_json::from_value(
            serde_json::to_value(&request).expect("request should serialize"),
        )
        .expect("request should deserialize");
        let round_trip =
            OpenRouterRequestOptions::from_generate_config(round_trip_request.config.as_ref())
                .expect("options should parse")
                .expect("openrouter options should exist");

        assert_eq!(round_trip, options);
    }

    #[tokio::test]
    async fn generate_content_chat_mode_maps_reasoning_and_function_calls() {
        let server = MockServer::start().await;
        let expected_body = json!({
            "model": "openai/gpt-5.2",
            "messages": [
                {
                    "role": "user",
                    "content": "hello"
                }
            ],
            "plugins": [
                {
                    "id": "web",
                    "enabled": true
                }
            ],
            "provider": {
                "zdr": true
            }
        });

        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .and(body_json(&expected_body))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "id": "chatcmpl-1",
                "model": "openai/gpt-5.2",
                "choices": [
                    {
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "reasoning": "Need to call the weather tool.",
                            "content": "",
                            "tool_calls": [
                                {
                                    "id": "call_weather",
                                    "type": "function",
                                    "function": {
                                        "name": "lookup_weather",
                                        "arguments": "{\"city\":\"Nairobi\"}"
                                    }
                                }
                            ]
                        },
                        "finish_reason": "tool_calls"
                    }
                ]
            })))
            .mount(&server)
            .await;

        let client = OpenRouterClient::new(
            OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
        )
        .expect("client should build");

        let mut config = GenerateContentConfig::default();
        OpenRouterRequestOptions::default()
            .with_plugin(OpenRouterPlugin {
                id: "web".to_string(),
                enabled: Some(true),
                ..Default::default()
            })
            .with_provider_preferences(OpenRouterProviderPreferences {
                zdr: Some(true),
                ..Default::default()
            })
            .insert_into_config(&mut config)
            .expect("options should insert");

        let mut stream = client
            .generate_content(
                LlmRequest::new(
                    "openai/gpt-5.2",
                    vec![adk_core::Content::new("user").with_text("hello")],
                )
                .with_config(config),
                false,
            )
            .await
            .expect("generation should start");

        let response = stream.next().await.expect("response").expect("response should succeed");
        let content = response.content.expect("content should exist");

        assert_eq!(response.finish_reason, Some(adk_core::FinishReason::Stop));
        assert!(
            matches!(&content.parts[0], Part::Thinking { thinking, .. } if thinking == "Need to call the weather tool.")
        );
        assert!(
            matches!(&content.parts[1], Part::FunctionCall { name, id, .. } if name == "lookup_weather" && id.as_deref() == Some("call_weather"))
        );
    }

    #[tokio::test]
    async fn generate_content_chat_stream_emits_one_final_chunk_when_usage_arrives_after_finish() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/chat/completions"))
            .respond_with(ResponseTemplate::new(200).set_body_string(
                "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"openai/gpt-5.2\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"hello\"}}]}\n\n\
                 data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"openai/gpt-5.2\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n\
                 data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"openai/gpt-5.2\",\"choices\":[{\"index\":0,\"delta\":{}}],\"usage\":{\"prompt_tokens\":4,\"completion_tokens\":2,\"total_tokens\":6}}\n\n\
                 data: [DONE]\n\n",
            ))
            .mount(&server)
            .await;

        let client = OpenRouterClient::new(
            OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
        )
        .expect("client should build");

        let mut stream = client
            .generate_content(
                LlmRequest::new(
                    "openai/gpt-5.2",
                    vec![adk_core::Content::new("user").with_text("hello")],
                ),
                true,
            )
            .await
            .expect("generation should start");

        let mut responses = Vec::new();
        while let Some(item) = stream.next().await {
            responses.push(item.expect("chunk should succeed"));
        }

        assert_eq!(responses.len(), 2);
        assert!(responses[0].partial);
        assert!(!responses[0].turn_complete);
        assert_eq!(
            responses[0]
                .content
                .as_ref()
                .and_then(|content| content.parts.first())
                .and_then(Part::text),
            Some("hello")
        );

        assert!(!responses[1].partial);
        assert!(responses[1].turn_complete);
        assert_eq!(responses[1].finish_reason, Some(adk_core::FinishReason::Stop));
        assert_eq!(
            responses[1].usage_metadata.as_ref().map(|usage| usage.total_token_count),
            Some(6)
        );
    }

    #[tokio::test]
    async fn generate_content_responses_mode_uses_extension_options_after_request_round_trip() {
        let server = MockServer::start().await;
        let expected_body = json!({
            "model": "openai/gpt-5.2",
            "input": [
                {
                    "type": "message",
                    "role": "user",
                    "content": "hello"
                }
            ],
            "tools": [
                {
                    "type": "web_search"
                }
            ],
            "reasoning": {
                "effort": "medium"
            },
            "previous_response_id": "resp_previous",
            "prompt_cache_key": "cache-key",
            "include": ["reasoning.encrypted_content"],
            "route": "fallback",
            "models": ["openai/gpt-5.2", "openai/gpt-5-mini"]
        });

        Mock::given(method("POST"))
            .and(path("/responses"))
            .and(body_json(&expected_body))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "id": "resp-1",
                "model": "openai/gpt-5.2",
                "status": "completed",
                "output": [
                    {
                        "type": "message",
                        "id": "msg-1",
                        "role": "assistant",
                        "status": "completed",
                        "content": [
                            {
                                "type": "output_text",
                                "text": "hello back",
                                "annotations": []
                            }
                        ]
                    }
                ],
                "usage": {
                    "input_tokens": 10,
                    "input_tokens_details": { "cached_tokens": 1 },
                    "output_tokens": 6,
                    "output_tokens_details": { "reasoning_tokens": 2 },
                    "total_tokens": 16,
                    "cost": 0.001
                }
            })))
            .mount(&server)
            .await;

        let client = OpenRouterClient::new(
            OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
        )
        .expect("client should build");

        let mut config = GenerateContentConfig::default();
        OpenRouterRequestOptions::default()
            .with_api_mode(OpenRouterApiMode::Responses)
            .with_response_tool(OpenRouterResponseTool {
                kind: "web_search".to_string(),
                ..Default::default()
            })
            .with_reasoning(OpenRouterReasoningConfig {
                effort: Some("medium".to_string()),
                ..Default::default()
            })
            .with_previous_response_id("resp_previous")
            .with_prompt_cache_key("cache-key")
            .with_include(vec!["reasoning.encrypted_content".to_string()])
            .with_route("fallback")
            .with_models(vec!["openai/gpt-5.2".to_string(), "openai/gpt-5-mini".to_string()])
            .insert_into_config(&mut config)
            .expect("options should insert");

        let request = LlmRequest::new(
            "openai/gpt-5.2",
            vec![adk_core::Content::new("user").with_text("hello")],
        )
        .with_config(config);
        let round_trip_request: LlmRequest = serde_json::from_value(
            serde_json::to_value(&request).expect("request should serialize"),
        )
        .expect("request should deserialize");

        let mut stream = client
            .generate_content(round_trip_request, false)
            .await
            .expect("generation should start");

        let response = stream.next().await.expect("response").expect("response should succeed");
        assert_eq!(
            response
                .content
                .as_ref()
                .and_then(|content| content.parts.first())
                .and_then(Part::text),
            Some("hello back")
        );
        assert_eq!(response.usage_metadata.as_ref().and_then(|usage| usage.cost), Some(0.001));
    }

    #[tokio::test]
    async fn generate_content_responses_stream_emits_function_call_with_terminal_response() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/responses"))
            .respond_with(ResponseTemplate::new(200).set_body_string(
                "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_weather\",\"name\":\"lookup_weather\",\"arguments\":\"\",\"status\":\"in_progress\"},\"sequence_number\":1}\n\n\
                 data: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_1\",\"delta\":\"{\\\"city\\\":\\\"Na\",\"sequence_number\":2}\n\n\
                 data: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_1\",\"delta\":\"irobi\\\"}\",\"sequence_number\":3}\n\n\
                 data: {\"type\":\"response.function_call_arguments.done\",\"item_id\":\"fc_1\",\"arguments\":\"{\\\"city\\\":\\\"Nairobi\\\"}\",\"sequence_number\":4}\n\n\
                 data: {\"type\":\"response.completed\",\"sequence_number\":5,\"response\":{\"id\":\"resp_1\",\"status\":\"completed\",\"output\":[{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_weather\",\"name\":\"lookup_weather\",\"arguments\":\"{\\\"city\\\":\\\"Nairobi\\\"}\",\"status\":\"completed\"}]}}\n\n\
                 data: [DONE]\n\n",
            ))
            .mount(&server)
            .await;

        let client = OpenRouterClient::new(
            OpenRouterConfig::new("sk-or-test", "openai/gpt-5.2").with_base_url(server.uri()),
        )
        .expect("client should build");

        let mut config = GenerateContentConfig::default();
        OpenRouterRequestOptions::default()
            .with_api_mode(OpenRouterApiMode::Responses)
            .insert_into_config(&mut config)
            .expect("options should insert");

        let mut stream = client
            .generate_content(
                LlmRequest::new(
                    "openai/gpt-5.2",
                    vec![adk_core::Content::new("user").with_text("weather")],
                )
                .with_config(config),
                true,
            )
            .await
            .expect("generation should start");

        let response = stream.next().await.expect("response").expect("response should succeed");
        let part = response
            .content
            .as_ref()
            .and_then(|content| content.parts.first())
            .expect("function call part should exist");

        match part {
            Part::FunctionCall { name, args, id, .. } => {
                assert_eq!(name, "lookup_weather");
                assert_eq!(id.as_deref(), Some("call_weather"));
                assert_eq!(args["city"], json!("Nairobi"));
            }
            other => panic!("expected function call part, got {other:?}"),
        }

        assert_eq!(response.content.as_ref().map(|content| content.parts.len()), Some(1));
        assert!(response.turn_complete);
        assert!(!response.partial);
        assert!(stream.next().await.is_none());
    }

    /// Regression: parallel tool-call fragments must be bucketed by their
    /// streaming `index`, not by position within each delta. OpenRouter streams
    /// each fragment in a single-element array, so position is always 0; keying
    /// by position merged every parallel call into one bucket whose concatenated
    /// arguments were invalid JSON and got silently dropped.
    #[test]
    fn streaming_keeps_parallel_tool_calls_separate_by_index() {
        use super::ChatStreamState;
        use crate::openrouter::chat::{OpenRouterChatToolCall, OpenRouterChatToolFunction};

        fn frag(
            index: usize,
            id: Option<&str>,
            name: Option<&str>,
            args: &str,
        ) -> OpenRouterChatToolCall {
            OpenRouterChatToolCall {
                index: Some(index),
                id: id.map(str::to_string),
                kind: String::new(),
                function: Some(OpenRouterChatToolFunction {
                    name: name.map(str::to_string),
                    arguments: Some(args.to_string()),
                    output: None,
                    extra: Default::default(),
                }),
                extra: Default::default(),
            }
        }

        // Two parallel calls, fragments interleaved as OpenRouter streams them:
        // each delta is a single-element array whose `index` (not its position)
        // identifies the call.
        let mut state = ChatStreamState::default();
        state.capture_chat_tool_calls(&[frag(0, Some("call_a"), Some("bash"), "{\"command\": ")]);
        state.capture_chat_tool_calls(&[frag(1, Some("call_b"), Some("bash"), "{\"command\": ")]);
        state.capture_chat_tool_calls(&[frag(0, None, None, "\"whoami\"}")]);
        state.capture_chat_tool_calls(&[frag(1, None, None, "\"pwd\"}")]);

        let mut calls: Vec<(Option<String>, String, serde_json::Value)> = state
            .drain_chat_tool_calls()
            .expect("both calls carry a name and JSON-object arguments")
            .into_iter()
            .map(|p| match p {
                Part::FunctionCall { id, name, args, .. } => (id, name, args),
                other => panic!("expected a function call, got {other:?}"),
            })
            .collect();
        calls.sort_by(|a, b| a.0.cmp(&b.0));

        assert_eq!(calls.len(), 2, "both parallel calls survive (was 0 before the index fix)");
        assert_eq!(calls[0].0.as_deref(), Some("call_a"));
        assert_eq!(calls[0].1, "bash");
        assert_eq!(calls[0].2, serde_json::json!({ "command": "whoami" }));
        assert_eq!(calls[1].0.as_deref(), Some("call_b"));
        assert_eq!(calls[1].2, serde_json::json!({ "command": "pwd" }));
    }

    fn chat_choice(
        message: serde_json::Value,
        finish: &str,
        native: &str,
    ) -> adk_core::LlmResponse {
        let response: crate::openrouter::chat::OpenRouterChatResponse =
            serde_json::from_value(json!({
                "choices": [{
                    "index": 0,
                    "message": message,
                    "finish_reason": finish,
                    "native_finish_reason": native
                }]
            }))
            .unwrap();
        super::chat_response_to_llm_response(&response)
    }

    #[test]
    fn a_chat_tool_call_with_malformed_arguments_is_kept_and_marked_invalid() {
        let call = |name: &str, arguments: &str| {
            json!({
                "id": name,
                "type": "function",
                "function": { "name": name, "arguments": arguments }
            })
        };
        let reply = chat_choice(
            json!({ "role": "assistant", "tool_calls": [call("lookup", "{}"), call("check", "{")] }),
            "tool_calls",
            "tool_calls",
        );
        let parts = reply.content.unwrap().parts;
        let calls: Vec<(&str, bool)> = parts
            .iter()
            .filter_map(|part| match part {
                adk_core::Part::FunctionCall { name, args, .. } => {
                    Some((name.as_str(), adk_core::invalid_tool_arguments_reason(args).is_some()))
                }
                _ => None,
            })
            .collect();
        assert_eq!(calls, vec![("lookup", false), ("check", true)]);
    }

    #[test]
    fn a_chat_refusal_is_the_text_and_finishes_with_refusal() {
        let response = chat_choice(
            json!({"role": "assistant", "content": null, "refusal": "I can't help with that."}),
            "stop",
            "stop",
        );
        assert_eq!(
            (response.finish_reason, response.content.unwrap().parts),
            (
                Some(adk_core::FinishReason::Refusal),
                vec![Part::Text { text: "I can't help with that.".into() }]
            )
        );
    }

    #[test]
    fn the_native_finish_reason_reports_refusals_and_malformed_tool_calls() {
        for (finish, native, expected) in [
            ("stop", "refusal", adk_core::FinishReason::Refusal),
            ("stop", "MALFORMED_FUNCTION_CALL", adk_core::FinishReason::MalformedToolCall),
            ("stop", "UNEXPECTED_TOOL_CALL", adk_core::FinishReason::MalformedToolCall),
            ("stop", "malformed_tool_use", adk_core::FinishReason::MalformedToolCall),
            ("stop", "end_turn", adk_core::FinishReason::Stop),
            ("length", "max_tokens", adk_core::FinishReason::MaxTokens),
            ("content_filter", "SAFETY", adk_core::FinishReason::Safety),
        ] {
            let response =
                chat_choice(json!({"role": "assistant", "content": "x"}), finish, native);
            assert_eq!(response.finish_reason, Some(expected), "{finish}/{native}");
        }
    }

    #[test]
    fn a_responses_refusal_part_is_the_text_and_finishes_with_refusal() {
        let response: crate::openrouter::responses::OpenRouterResponse =
            serde_json::from_value(json!({
                "status": "completed",
                "output": [{
                    "type": "message",
                    "id": "msg",
                    "role": "assistant",
                    "content": [{"type": "refusal", "refusal": "I can't help with that."}]
                }]
            }))
            .unwrap();
        let response = super::responses_response_to_llm_response(&response).unwrap().unwrap();
        assert_eq!(
            (response.finish_reason, response.content.unwrap().parts),
            (
                Some(adk_core::FinishReason::Refusal),
                vec![Part::Text { text: "I can't help with that.".into() }]
            )
        );
    }
}