adk-model 2.3.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
//! Shared OpenAI-compatible provider implementation.

use crate::openai::{OpenAIReasoningEffort, convert};
use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
use crate::sse::take_line;
use adk_core::{
    AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, GenericSchemaAdapter, Llm,
    LlmRequest, LlmResponse, LlmResponseStream, Part, SchemaAdapter, SchemaCache, UsageMetadata,
};
use async_openai::types::chat::{
    CreateChatCompletionRequestArgs, ReasoningEffort as OaiReasoningEffort, ResponseFormat,
    ResponseFormatJsonSchema,
};
use async_stream::try_stream;
use async_trait::async_trait;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Assistant-message field accepted by an OpenAI-compatible provider for reasoning replay.
///
/// Reasoning replay is disabled by default. Enabling it selects `reasoning_content`;
/// an explicit field overrides that choice for endpoints such as newer vLLM servers.
///
/// # Example
///
/// ```
/// use adk_model::ReasoningReplayField;
///
/// let field = ReasoningReplayField::ReasoningContent;
/// assert_eq!(field, ReasoningReplayField::ReasoningContent);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReasoningReplayField {
    /// Use the `reasoning_content` assistant-message field.
    ReasoningContent,
    /// Use the `reasoning` assistant-message field, as used by newer vLLM servers.
    Reasoning,
}

/// Configuration for OpenAI-compatible providers.
///
/// The API key is redacted from `Debug` output and omitted when serializing.
#[derive(Clone, Serialize, Deserialize)]
pub struct OpenAICompatibleConfig {
    /// Provider display name used in error messages.
    pub provider_name: String,
    /// API key. Never serialized; deserializing a config without it yields an empty key.
    #[serde(skip_serializing, default)]
    pub api_key: String,
    /// Model name.
    pub model: String,
    /// Optional API base URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    /// Optional organization ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_id: Option<String>,
    /// Optional project ID for providers that support it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// Optional reasoning effort for OpenAI reasoning models.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<OaiReasoningEffort>,
    /// Whether to allow the model to call multiple tools in a single turn.
    pub parallel_tool_calls: bool,
}

impl std::fmt::Debug for OpenAICompatibleConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenAICompatibleConfig")
            .field("provider_name", &self.provider_name)
            .field("api_key", &"[REDACTED]")
            .field("model", &self.model)
            .field("base_url", &self.base_url)
            .field("organization_id", &self.organization_id)
            .field("project_id", &self.project_id)
            .field("reasoning_effort", &self.reasoning_effort)
            .field("parallel_tool_calls", &self.parallel_tool_calls)
            .finish()
    }
}

impl OpenAICompatibleConfig {
    /// Create config for an OpenAI-compatible provider.
    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            provider_name: "openai-compatible".to_string(),
            api_key: api_key.into(),
            model: model.into(),
            base_url: None,
            organization_id: None,
            project_id: None,
            reasoning_effort: None,
            parallel_tool_calls: true,
        }
    }

    /// Set provider display name used in errors.
    pub fn with_provider_name(mut self, provider_name: impl Into<String>) -> Self {
        self.provider_name = provider_name.into();
        self
    }

    /// Set a custom API base URL.
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Set organization ID.
    pub fn with_organization(mut self, organization_id: impl Into<String>) -> Self {
        self.organization_id = Some(organization_id.into());
        self
    }

    /// Set project ID.
    pub fn with_project(mut self, project_id: impl Into<String>) -> Self {
        self.project_id = Some(project_id.into());
        self
    }

    /// Set reasoning effort for reasoning models.
    pub fn with_reasoning_effort(mut self, effort: OaiReasoningEffort) -> Self {
        self.reasoning_effort = Some(effort);
        self
    }

    /// Set whether parallel tool calls are allowed.
    pub fn with_parallel_tool_calls(mut self, parallel_tool_calls: bool) -> Self {
        self.parallel_tool_calls = parallel_tool_calls;
        self
    }

    // ── Provider presets ─────────────────────────────────────────

    /// Fireworks AI preset.
    ///
    /// Default model: `accounts/fireworks/models/kimi-k2p6`
    pub fn fireworks(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("fireworks")
            .with_base_url("https://api.fireworks.ai/inference/v1")
    }

    /// Together AI preset.
    ///
    /// Default model: `MiniMaxAI/MiniMax-M2.7`
    pub fn together(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("together")
            .with_base_url("https://api.together.xyz/v1")
    }

    /// Mistral AI preset.
    ///
    /// Default model: `mistral-medium-latest`
    pub fn mistral(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("mistral")
            .with_base_url("https://api.mistral.ai/v1")
    }

    /// Perplexity preset.
    ///
    /// Default model: `sonar-pro`
    pub fn perplexity(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("perplexity")
            .with_base_url("https://api.perplexity.ai")
    }

    /// Cerebras preset.
    ///
    /// Default model: `gpt-oss-120b`
    pub fn cerebras(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("cerebras")
            .with_base_url("https://api.cerebras.ai/v1")
    }

    /// SambaNova preset.
    ///
    /// Default model: `gpt-oss-120b`
    pub fn sambanova(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("sambanova")
            .with_base_url("https://api.sambanova.ai/v1")
    }

    /// xAI (Grok) preset.
    ///
    /// Default model: `grok-4.6`
    pub fn xai(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model).with_provider_name("xai").with_base_url("https://api.x.ai/v1")
    }

    /// OrcaRouter preset.
    ///
    /// OrcaRouter routes one OpenAI-compatible endpoint to models from several
    /// vendors; model IDs carry a vendor prefix such as `openai/` or `anthropic/`.
    ///
    /// Default model suggestion: `openai/gpt-5.6-terra`
    ///
    /// # Example
    ///
    /// ```
    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
    ///
    /// let config = OpenAICompatibleConfig::orcarouter("sk-orca-...", "openai/gpt-5.6-terra");
    /// assert_eq!(config.base_url.as_deref(), Some("https://api.orcarouter.ai/v1"));
    ///
    /// let model = OpenAICompatible::new(config)?;
    /// # let _ = model;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    pub fn orcarouter(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("orcarouter")
            .with_base_url("https://api.orcarouter.ai/v1")
    }

    /// Google Gemini (OpenAI-compatible) preset.
    ///
    /// Targets Gemini's OpenAI-compatibility endpoint, letting you use a Gemini
    /// API key and a Gemini model (e.g. `gemini-3.7-flash`) through the OpenAI
    /// Chat Completions wire format. Use a `GEMINI_API_KEY` for the `api_key`.
    ///
    /// For native Gemini features (thinking levels, server-side tools, the
    /// Interactions API), prefer [`GeminiModel`](crate::gemini::GeminiModel).
    /// This preset is for callers who want a single OpenAI-compatible code path
    /// across providers.
    ///
    /// Default model suggestion: `gemini-3.7-flash`.
    pub fn gemini(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("gemini")
            .with_base_url("https://generativelanguage.googleapis.com/v1beta/openai")
    }

    /// MiniMax preset.
    ///
    /// Default model: `MiniMax-M2.7` (case-sensitive)
    pub fn minimax(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("minimax")
            .with_base_url("https://api.minimax.chat/v1")
    }

    /// ByteDance Doubao (Volcano Engine Ark) preset.
    ///
    /// Default model: `doubao-1-5-pro-256k`
    pub fn bytedance(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("bytedance")
            .with_base_url("https://ark.cn-beijing.volces.com/api/v3")
    }

    /// Zhipu AI (GLM) preset.
    ///
    /// Default model: `glm-5.2`
    pub fn zhipu(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("zhipu")
            .with_base_url("https://open.bigmodel.cn/api/paas/v4")
    }

    /// Baidu ERNIE (Qianfan) preset via OpenAI-compatible endpoint.
    ///
    /// Default model: `ernie-5.1`
    ///
    /// Note: Uses the Qianfan OpenAI-compatible endpoint. For the native
    /// Qianfan API with OAuth2 token exchange, use a dedicated client.
    pub fn baidu(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("baidu")
            .with_base_url("https://qianfan.baidubce.com/v2")
    }

    /// Cohere preset via OpenAI-compatible endpoint.
    ///
    /// Default model: `command-a-plus-05-2026`
    ///
    /// Note: For full Cohere features (citations, connectors, RAG), use
    /// the native Cohere API. This preset provides basic chat completions.
    pub fn cohere(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self::new(api_key, model)
            .with_provider_name("cohere")
            .with_base_url("https://api.cohere.com/compatibility/v1")
    }
}

/// Error codes a compatible client reports.
///
/// Native services routed through [`OpenAICompatible`] keep the codes their
/// dedicated clients reported, because error codes are part of the public contract.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ErrorCodes {
    /// Transport failure before a response arrived.
    pub(crate) request: &'static str,
    /// Non-success HTTP status without a status-specific code.
    pub(crate) api_error: &'static str,
    /// Response body that is not valid JSON.
    pub(crate) parse: &'static str,
    /// Tool-call arguments that are not a JSON object.
    pub(crate) invalid_tool_arguments: &'static str,
    /// Status-specific codes that take precedence over `api_error`.
    pub(crate) status: &'static [(u16, &'static str)],
}

impl ErrorCodes {
    /// Codes for providers reached through the generic compatible client.
    pub(crate) const COMPATIBLE: Self = Self {
        request: "model.openai_compat.request",
        api_error: "model.openai_compat.api_error",
        parse: "model.openai_compat.parse",
        invalid_tool_arguments: "model.openai_compat.invalid_tool_arguments",
        status: &[],
    };

    fn for_status(&self, status: u16) -> &'static str {
        self.status
            .iter()
            .find_map(|(candidate, code)| (*candidate == status).then_some(*code))
            .unwrap_or(self.api_error)
    }
}

/// Shared OpenAI-compatible client implementation.
pub struct OpenAICompatible {
    completion_url: Option<String>,
    http: reqwest::Client,
    /// Headers added to every request, kept so later calls extend rather than replace them.
    default_headers: http::HeaderMap,
    request_adapter: Option<crate::openai::RequestAdapter>,
    api_key: String,
    base_url: String,
    model: String,
    provider_name: String,
    retry_config: RetryConfig,
    reasoning_effort: Option<OpenAIReasoningEffort>,
    organization_id: Option<String>,
    parallel_tool_calls: bool,
    reasoning_replay_field: Option<ReasoningReplayField>,
    error_codes: ErrorCodes,
}

impl OpenAICompatible {
    /// Create a new OpenAI-compatible client.
    pub fn new(config: OpenAICompatibleConfig) -> Result<Self, AdkError> {
        let reasoning_effort = config.reasoning_effort.clone().map(|effort| match effort {
            OaiReasoningEffort::None => OpenAIReasoningEffort::None,
            OaiReasoningEffort::Minimal => OpenAIReasoningEffort::Minimal,
            OaiReasoningEffort::Low => OpenAIReasoningEffort::Low,
            OaiReasoningEffort::Medium => OpenAIReasoningEffort::Medium,
            OaiReasoningEffort::High => OpenAIReasoningEffort::High,
            OaiReasoningEffort::Xhigh => OpenAIReasoningEffort::XHigh,
        });
        Self::new_with_reasoning_effort(config, reasoning_effort)
    }

    /// Create an OpenAI-compatible client with the complete OpenAI reasoning vocabulary.
    ///
    /// This supports newer values such as `none`, `xhigh`, and `max` without changing
    /// the backward-compatible [`OpenAICompatibleConfig::reasoning_effort`] field type.
    pub fn new_with_reasoning_effort(
        config: OpenAICompatibleConfig,
        reasoning_effort: Option<OpenAIReasoningEffort>,
    ) -> Result<Self, AdkError> {
        crate::catalog::warn_if_obsolete(&config.provider_name, &config.model);
        let base_url = config.base_url.unwrap_or_else(|| "https://api.openai.com/v1".to_string());

        Ok(Self {
            completion_url: None,
            http: reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .build()
                .map_err(|_| AdkError::model("failed to initialize compatible HTTP transport"))?,
            default_headers: http::HeaderMap::new(),
            request_adapter: None,
            api_key: config.api_key,
            base_url,
            model: config.model,
            provider_name: config.provider_name,
            retry_config: RetryConfig::default(),
            reasoning_effort,
            organization_id: config.organization_id,
            parallel_tool_calls: config.parallel_tool_calls,
            reasoning_replay_field: None,
            error_codes: ErrorCodes::COMPATIBLE,
        })
    }

    /// Adds default HTTP headers to every request, replacing earlier defaults with the same name.
    ///
    /// The bearer token and organization headers set per request take precedence, and
    /// redirects stay disabled. Unlike builder methods that only store a value, this
    /// method rebuilds the underlying `reqwest` client, so it returns `Result`.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
    /// use http::header::{HeaderMap, HeaderValue};
    ///
    /// let mut headers = HeaderMap::new();
    /// headers.insert("x-session-id", HeaderValue::from_static("conversation-1"));
    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("api-key", "model"))?
    ///     .with_default_headers(headers)?;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an `Internal` error with code `model.openai.http_client_init` when the
    /// HTTP client cannot be built.
    pub fn with_default_headers(mut self, headers: http::HeaderMap) -> Result<Self, AdkError> {
        self.default_headers.extend(headers);
        self.http = reqwest::Client::builder()
            .default_headers(self.default_headers.clone())
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|err| {
                AdkError::new(
                    ErrorComponent::Model,
                    ErrorCategory::Internal,
                    "model.openai.http_client_init",
                    format!("failed to initialize the {} HTTP client: {err}", self.provider_name),
                )
                .with_provider(&self.provider_name)
                .with_source(err)
            })?;
        Ok(self)
    }

    /// Set the retry configuration (builder pattern).
    #[must_use]
    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
        self.retry_config = retry_config;
        self
    }

    /// Customize generation request fields and headers before each HTTP attempt.
    ///
    /// The adapter runs under this client's [`RetryConfig`]; see
    /// [`RequestAdapter`](crate::openai::RequestAdapter) for an example.
    #[must_use]
    pub fn with_request_adapter(mut self, adapter: crate::openai::RequestAdapter) -> Self {
        self.request_adapter = Some(adapter);
        self
    }

    /// Use a native service's fully qualified Chat Completions route.
    pub(crate) fn with_completion_url(mut self, url: String) -> Self {
        self.completion_url = Some(url);
        self
    }

    pub(crate) fn with_reasoning_effort(mut self, effort: Option<OpenAIReasoningEffort>) -> Self {
        self.reasoning_effort = effort;
        self
    }

    /// Report a native service's error codes instead of the compatible ones.
    pub(crate) fn with_error_codes(mut self, error_codes: ErrorCodes) -> Self {
        self.error_codes = error_codes;
        self
    }

    /// Set the retry configuration (mutable reference).
    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
        self.retry_config = retry_config;
    }

    /// Returns the current retry configuration.
    pub fn retry_config(&self) -> &RetryConfig {
        &self.retry_config
    }

    /// Enables or disables assistant reasoning replay through `reasoning_content`.
    ///
    /// Disabled by default. Passing `true` selects `reasoning_content`, replacing
    /// any previous field selection; passing `false` clears the selection.
    /// This controls history serialization, not whether the model thinks.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
    ///
    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("key", "model"))?
    ///     .with_reasoning_replay(true);
    /// # let _ = client;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    #[must_use]
    pub fn with_reasoning_replay(mut self, enabled: bool) -> Self {
        self.reasoning_replay_field = enabled.then_some(ReasoningReplayField::ReasoningContent);
        self
    }

    /// Enables assistant reasoning replay with an explicit provider field.
    ///
    /// Newer vLLM servers use `ReasoningReplayField::Reasoning`. Older deployments
    /// may still require `reasoning_content`; select the field the endpoint accepts.
    /// The last call to either reasoning-replay builder determines the selection.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_model::{
    ///     OpenAICompatible, OpenAICompatibleConfig, ReasoningReplayField,
    /// };
    ///
    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("key", "model"))?
    ///     .with_reasoning_replay_field(ReasoningReplayField::Reasoning);
    /// # let _ = client;
    /// # Ok::<(), adk_core::AdkError>(())
    /// ```
    #[must_use]
    pub fn with_reasoning_replay_field(mut self, field: ReasoningReplayField) -> Self {
        self.reasoning_replay_field = Some(field);
        self
    }
}

fn inject_assistant_reasoning(
    body: &mut serde_json::Value,
    contents: &[Content],
    field: Option<ReasoningReplayField>,
) {
    let Some(field) = field else {
        return;
    };
    let Some(messages) = body.get_mut("messages").and_then(serde_json::Value::as_array_mut) else {
        return;
    };
    let field_name = match field {
        ReasoningReplayField::ReasoningContent => "reasoning_content",
        ReasoningReplayField::Reasoning => "reasoning",
    };

    for (message, content) in messages.iter_mut().zip(contents) {
        if !matches!(content.role.as_str(), "model" | "assistant") {
            continue;
        }
        let Some(reasoning) = convert::extract_reasoning_content(&content.parts) else {
            continue;
        };
        let Some(message) = message.as_object_mut() else {
            continue;
        };

        message.insert(field_name.to_string(), serde_json::Value::String(reasoning));
    }
}

/// Provider capabilities that shape a Chat Completions request body.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ChatCapabilities {
    /// Value of `parallel_tool_calls` sent with tool declarations.
    pub(crate) parallel_tool_calls: bool,
    /// Send inline PDFs as `file` parts. Only OpenAI and Azure OpenAI accept them,
    /// so every other compatible provider keeps the text fallback.
    pub(crate) native_pdf: bool,
}

/// Build the serialized JSON request body from an `LlmRequest`.
///
/// This is shared between the streaming and non-streaming paths so that
/// request parameter construction is identical regardless of mode.
pub(crate) fn build_request_json(
    model: &str,
    request: &LlmRequest,
    reasoning_effort: &Option<OpenAIReasoningEffort>,
    capabilities: ChatCapabilities,
    reasoning_replay_field: Option<ReasoningReplayField>,
    adapter: &dyn SchemaAdapter,
    cache: &SchemaCache,
) -> Result<serde_json::Value, AdkError> {
    let bare_model = model.strip_prefix("models/").unwrap_or(model);
    if matches!(bare_model, "gemini-3.6-flash" | "gemini-3.7-flash")
        && request.config.as_ref().is_some_and(|config| {
            config.temperature.is_some() || config.top_p.is_some() || config.top_k.is_some()
        })
    {
        return Err(AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::InvalidInput,
            "model.gemini.sampling_unsupported",
            format!(
                "{bare_model} does not accept temperature, top_p, or top_k; remove explicit sampling parameters"
            ),
        )
        .with_provider("gemini"));
    }
    let contents = crate::tool_result::with_images(&request.contents);
    let messages: Vec<_> = contents
        .iter()
        .map(|content| convert::content_to_message(content, capabilities.native_pdf))
        .collect();

    let mut request_builder = CreateChatCompletionRequestArgs::default();
    request_builder.model(model).messages(messages);

    if !request.tools.is_empty() {
        let tools = convert::convert_tools(&request.tools, adapter, cache);
        request_builder.tools(tools);
        // OpenAI defaults parallel_tool_calls to true.
        request_builder.parallel_tool_calls(capabilities.parallel_tool_calls);
    }

    if let Some(effort) = reasoning_effort.and_then(to_oai_reasoning_effort) {
        request_builder.reasoning_effort(effort);
    }

    if let Some(config) = &request.config {
        if let Some(temp) = config.temperature {
            request_builder.temperature(temp);
        }
        if let Some(top_p) = config.top_p {
            request_builder.top_p(top_p);
        }
        if let Some(max_tokens) = config.max_output_tokens {
            request_builder.max_completion_tokens(max_tokens as u32);
        }

        if let Some(schema) = &config.response_schema {
            let mut schema_with_strict = schema.clone();
            if let Some(obj) = schema_with_strict.as_object_mut() {
                obj.insert("additionalProperties".to_string(), serde_json::json!(false));
            }
            let json_schema = ResponseFormatJsonSchema {
                name: request.model.replace(['-', '.', '/'], "_"),
                description: None,
                schema: schema_with_strict,
                strict: Some(true),
            };
            request_builder.response_format(ResponseFormat::JsonSchema { json_schema });
        }
    }

    let openai_request = request_builder
        .build()
        .map_err(|e| AdkError::model(format!("failed to build request: {e}")))?;

    let mut body = serde_json::to_value(&openai_request)
        .map_err(|e| AdkError::model(format!("failed to serialize request: {e}")))?;

    if matches!(reasoning_effort, Some(OpenAIReasoningEffort::Max)) {
        body["reasoning_effort"] = serde_json::Value::String("max".to_string());
    }

    inject_assistant_reasoning(&mut body, &contents, reasoning_replay_field);

    // Merge provider-specific extensions from config.extensions["openai"] into
    // the request body.  This allows users to pass provider-specific fields
    // that the typed builder doesn't cover (e.g. provider-specific parameters
    // for OpenAI-compatible APIs like DeepSeek, Together, etc.).
    if let Some(config) = &request.config
        && let Some(openai_ext) = config.extensions.get("openai")
        && let (Some(body_obj), Some(ext_obj)) = (body.as_object_mut(), openai_ext.as_object())
    {
        for (key, value) in ext_obj {
            body_obj.insert(key.clone(), value.clone());
        }
    }

    Ok(body)
}

fn to_oai_reasoning_effort(effort: OpenAIReasoningEffort) -> Option<OaiReasoningEffort> {
    match effort {
        OpenAIReasoningEffort::None => Some(OaiReasoningEffort::None),
        OpenAIReasoningEffort::Minimal => Some(OaiReasoningEffort::Minimal),
        OpenAIReasoningEffort::Low => Some(OaiReasoningEffort::Low),
        OpenAIReasoningEffort::Medium => Some(OaiReasoningEffort::Medium),
        OpenAIReasoningEffort::High => Some(OaiReasoningEffort::High),
        OpenAIReasoningEffort::XHigh => Some(OaiReasoningEffort::Xhigh),
        OpenAIReasoningEffort::Max => None,
    }
}

/// Destination, credentials and error codes of one generation request.
#[derive(Clone)]
struct RequestTarget {
    url: String,
    api_key: String,
    organization_id: Option<String>,
    provider_name: String,
    adapter: Option<crate::openai::RequestAdapter>,
    error_codes: ErrorCodes,
}

/// Send an HTTP POST and handle error status codes.
///
/// Returns the raw `reqwest::Response` on success so the caller can decide
/// whether to parse it as JSON (non-streaming) or consume it as an SSE byte
/// stream (streaming).
async fn send_request(
    http: &reqwest::Client,
    target: &RequestTarget,
    body: &serde_json::Value,
) -> Result<reqwest::Response, AdkError> {
    let RequestTarget { url, api_key, organization_id, provider_name, adapter, error_codes } =
        target;
    let mut http_req = http.post(url);
    if !api_key.is_empty() {
        http_req = http_req.bearer_auth(api_key);
    }
    if let Some(adapter) = adapter {
        let mut body = body.clone();
        let mut headers = reqwest::header::HeaderMap::new();
        adapter(&mut body, &mut headers)?;
        http_req = http_req.headers(headers).json(&body);
    } else {
        http_req = http_req.json(body);
    }

    if let Some(org_id) = organization_id {
        http_req = http_req.header("OpenAI-Organization", org_id);
    }

    let http_resp = http_req.send().await.map_err(|e| {
        AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::Unavailable,
            error_codes.request,
            format!("{provider_name} request error: {e}"),
        )
        .with_provider(provider_name)
    })?;

    if !http_resp.status().is_success() {
        let status = http_resp.status();
        let status_code = status.as_u16();
        let retry_after = http_resp
            .headers()
            .get(reqwest::header::RETRY_AFTER)
            .and_then(|value| value.to_str().ok())
            .and_then(crate::retry::parse_retry_after);
        let body = http_resp.text().await.unwrap_or_default();
        let error = AdkError::new(
            ErrorComponent::Model,
            crate::retry::category_for_status_code(status_code),
            error_codes.for_status(status_code),
            format!("{provider_name} API error (HTTP {status}): {body}"),
        )
        .with_upstream_status(status_code)
        .with_provider(provider_name);
        return Err(crate::retry::with_retry_after(error, retry_after));
    }

    Ok(http_resp)
}

/// Parse a finish_reason string into an ADK `FinishReason`.
fn parse_finish_reason(fr: &str) -> FinishReason {
    match fr {
        "stop" => FinishReason::Stop,
        "length" => FinishReason::MaxTokens,
        "tool_calls" => FinishReason::Stop,
        "content_filter" => FinishReason::Safety,
        "function_call" => FinishReason::Stop,
        _ => FinishReason::Stop,
    }
}

/// Accumulate string deltas while treating structured values as complete snapshots.
fn append_tool_call_arguments(accumulator: &mut String, arguments: &serde_json::Value) {
    match arguments {
        serde_json::Value::String(fragment) => accumulator.push_str(fragment),
        serde_json::Value::Null => {}
        structured => {
            let empty_snapshot = matches!(structured, serde_json::Value::Object(fields) if fields.is_empty())
                || matches!(structured, serde_json::Value::Array(items) if items.is_empty());
            if !empty_snapshot {
                accumulator.clear();
                accumulator.push_str(&structured.to_string());
            }
        }
    }
}

fn parse_tool_call_arguments(
    provider_name: &str,
    error_codes: ErrorCodes,
    tool_name: &str,
    arguments: &str,
) -> Result<serde_json::Value, AdkError> {
    crate::tool_args::parse_streamed_tool_arguments(
        provider_name,
        error_codes.invalid_tool_arguments,
        tool_name,
        arguments,
    )
}

/// Parse usage metadata from a raw SSE chunk JSON value.
fn parse_usage_from_chunk(chunk: &serde_json::Value) -> Option<UsageMetadata> {
    chunk.get("usage").and_then(convert::usage_metadata_from_raw)
}

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

    #[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,
        request: LlmRequest,
        stream: bool,
    ) -> Result<LlmResponseStream, AdkError> {
        let model = self.model.clone();
        let provider_name = self.provider_name.clone();
        let http = self.http.clone();
        let retry_config = self.retry_config.clone();
        let reasoning_effort = self.reasoning_effort;
        let reasoning_replay_field = self.reasoning_replay_field;
        let error_codes = self.error_codes;
        let target = RequestTarget {
            url: self
                .completion_url
                .clone()
                .unwrap_or_else(|| format!("{}/chat/completions", self.base_url)),
            api_key: self.api_key.clone(),
            organization_id: self.organization_id.clone(),
            provider_name: provider_name.clone(),
            adapter: self.request_adapter.clone(),
            error_codes,
        };
        // Text-encoded tool calls are honoured only for tools this request declared.
        let declared_tools: std::collections::HashSet<String> =
            request.tools.keys().cloned().collect();

        // Normalize tool schemas at request time using the schema adapter.
        let adapter = self.schema_adapter();
        use std::sync::LazyLock;
        static SCHEMA_CACHE: LazyLock<SchemaCache> =
            LazyLock::new(|| SchemaCache::for_adapter(std::sync::Arc::new(GenericSchemaAdapter)));
        let request_body = build_request_json(
            &model,
            &request,
            &reasoning_effort,
            ChatCapabilities {
                parallel_tool_calls: self.parallel_tool_calls,
                native_pdf: matches!(provider_name.as_str(), "openai" | "azure-openai"),
            },
            reasoning_replay_field,
            adapter,
            &SCHEMA_CACHE,
        )?;

        let usage_span = adk_telemetry::llm_generate_span(&provider_name, &model, stream);

        if stream {
            // ── Streaming path ──────────────────────────────────────
            let response_stream = try_stream! {
                // Inject streaming fields into the pre-built request body.
                let mut body = request_body.clone();
                if let Some(obj) = body.as_object_mut() {
                    obj.insert("stream".to_string(), serde_json::json!(true));
                    obj.insert(
                        "stream_options".to_string(),
                        serde_json::json!({"include_usage": true}),
                    );
                }

                // Retry covers only the initial HTTP request, not stream consumption.
                let response = execute_with_retry(&retry_config, is_retryable_model_error, || {
                    let http = http.clone();
                    let target = target.clone();
                    let body = body.clone();
                    async move { send_request(&http, &target, &body).await }
                })
                .await?;

                // Process SSE byte stream (following DeepSeekClient pattern).
                let mut byte_stream = response.bytes_stream();
                let mut buffer = Vec::new();
                let mut tool_call_accumulators: HashMap<u32, (String, String, String)> =
                    HashMap::new();
                let mut text_tool_buffer =
                    crate::tool_call_parser::ToolCallBuffer::for_declared_tools(declared_tools);
                let mut pending_final_response: Option<LlmResponse> = None;

                while let Some(chunk_result) = byte_stream.next().await {
                    let chunk = chunk_result.map_err(|e| {
                        AdkError::model(format!("stream read error: {e}"))
                    })?;

                    buffer.extend_from_slice(&chunk);

                    // Process complete SSE lines.
                    while let Some(line) = take_line(&mut buffer)? {

                        if line.is_empty() {
                            continue;
                        }

                        if line == "data: [DONE]" {
                            if let Some(response) = pending_final_response.take() {
                                yield response;
                            }
                            continue;
                        }

                        if let Some(data) = line.strip_prefix("data: ") {
                            let chunk_json: serde_json::Value = match serde_json::from_str(data) {
                                Ok(v) => v,
                                Err(e) => {
                                    tracing::warn!(
                                        "failed to parse SSE chunk: {e} - {data}"
                                    );
                                    continue;
                                }
                            };
                            let usage_metadata = parse_usage_from_chunk(&chunk_json);

                            let choice = match chunk_json.get("choices").and_then(|c| c.get(0)) {
                                Some(c) => c,
                                None => {
                                    if let Some(usage_metadata) = usage_metadata
                                        && let Some(mut response) = pending_final_response.take()
                                    {
                                        response.usage_metadata = Some(usage_metadata);
                                        yield response;
                                    }
                                    continue;
                                }
                            };
                            let delta = match choice.get("delta") {
                                Some(d) => d,
                                None => continue,
                            };

                            let finish_reason_str = choice
                                .get("finish_reason")
                                .and_then(|v| v.as_str())
                                .map(String::from);

                            // Accumulate tool calls by index.
                            if let Some(tool_calls) = delta.get("tool_calls").and_then(|v| v.as_array()) {
                                for tc in tool_calls {
                                    let index = tc.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
                                    let entry = tool_call_accumulators
                                        .entry(index)
                                        .or_insert_with(|| {
                                            let call_id = tc
                                                .get("id")
                                                .and_then(|v| v.as_str())
                                                .unwrap_or("")
                                                .to_string();
                                            (call_id, String::new(), String::new())
                                        });

                                    if let Some(id) = tc.get("id").and_then(|v| v.as_str())
                                        && !id.is_empty() {
                                            entry.0 = id.to_string();
                                        }

                                    if let Some(func) = tc.get("function") {
                                        if let Some(name) = func.get("name").and_then(|v| v.as_str()) {
                                            entry.1 = name.to_string();
                                        }
                                        if let Some(arguments) = func.get("arguments") {
                                            append_tool_call_arguments(&mut entry.2, arguments);
                                        }
                                    }
                                }
                            }

                            // Check for finish_reason → emit final response.
                            if let Some(ref fr) = finish_reason_str {
                                let finish_reason = Some(parse_finish_reason(fr));

                                // Emit accumulated tool calls if any.
                                if !tool_call_accumulators.is_empty() {
                                    let mut sorted_calls: Vec<_> =
                                        tool_call_accumulators.drain().collect();
                                    sorted_calls.sort_by_key(|(idx, _)| *idx);

                                    let parts: Vec<Part> = sorted_calls
                                        .into_iter()
                                        .map(|(_, (id, name, args_str))| {
                                            let args = parse_tool_call_arguments(
                                                &provider_name,
                                                error_codes,
                                                &name,
                                                &args_str,
                                            )?;
                                            Ok(Part::FunctionCall {
                                                name,
                                                args,
                                                id: Some(id),
                                                thought_signature: None,
                                            })
                                        })
                                        .collect::<Result<Vec<_>, AdkError>>()?;

                                    let response = LlmResponse {
                                        content: Some(Content {
                                            role: "model".to_string(),
                                            parts,
                                        }),
                                        usage_metadata,
                                        finish_reason,
                                        citation_metadata: None,
                                        partial: false,
                                        // Tool-call turns are not complete — tool
                                        // results must still be processed (issue #401).
                                        turn_complete: false,
                                        interrupted: false,
                                        error_code: None,
                                        error_message: None,
                                        provider_metadata: None,
                                        interaction_id: None,
                                    };
                                    if response.usage_metadata.is_some() {
                                        yield response;
                                    } else {
                                        pending_final_response = Some(response);
                                    }
                                    continue;
                                }

                                // Final response without tool calls.
                                let mut parts = Vec::new();
                                if let Some(text) = delta.get("content").and_then(|v| v.as_str())
                                    && !text.is_empty() {
                                        parts.push(Part::Text { text: text.to_string() });
                                    }

                                let response = LlmResponse {
                                    content: if parts.is_empty() { None } else {
                                        Some(Content {
                                            role: "model".to_string(),
                                            parts,
                                        })
                                    },
                                    usage_metadata,
                                    finish_reason,
                                    citation_metadata: None,
                                    partial: false,
                                    turn_complete: true,
                                    interrupted: false,
                                    error_code: None,
                                    error_message: None,
                                    provider_metadata: None,
                                    interaction_id: None,
                                };
                                if response.usage_metadata.is_some() {
                                    yield response;
                                } else {
                                    pending_final_response = Some(response);
                                }
                                continue;
                            }

                            // Emit partial reasoning_content as Part::Thinking.
                            // Fallback to "reasoning" field for OpenRouter, Kilo Gateway, SambaNova, Cerebras, Groq
                            let reasoning = delta.get("reasoning_content")
                                .or_else(|| delta.get("reasoning"))
                                .and_then(|v| v.as_str());
                            if let Some(reasoning) = reasoning
                                && !reasoning.is_empty() {
                                    yield LlmResponse {
                                        content: Some(Content {
                                            role: "model".to_string(),
                                            parts: vec![Part::Thinking {
                                                thinking: reasoning.to_string(),
                                                signature: None,
                                            }],
                                        }),
                                        usage_metadata: None,
                                        finish_reason: None,
                                        citation_metadata: None,
                                        partial: true,
                                        turn_complete: false,
                                        interrupted: false,
                                        error_code: None,
                                        error_message: None,
                                        provider_metadata: None,
                                        interaction_id: None,
                                    };
                                }

                            // Emit partial text content via tool call buffer.
                            // The buffer detects <tool_call> tags split across chunks
                            // and converts them to Part::FunctionCall.
                            if let Some(text) = delta.get("content").and_then(|v| v.as_str())
                                && !text.is_empty() {
                                    match text_tool_buffer.push(text) {
                                        crate::tool_call_parser::BufferAction::Emit(parts) => {
                                            for part in parts {
                                                let is_tool = matches!(part, Part::FunctionCall { .. });
                                                yield LlmResponse {
                                                    content: Some(Content {
                                                        role: "model".to_string(),
                                                        parts: vec![part],
                                                    }),
                                                    usage_metadata: None,
                                                    finish_reason: None,
                                                    citation_metadata: None,
                                                    partial: !is_tool,
                                                    turn_complete: false,
                                                    interrupted: false,
                                                    error_code: None,
                                                    error_message: None,
                                                    provider_metadata: None,
                                                    interaction_id: None,
                                                };
                                            }
                                        }
                                        crate::tool_call_parser::BufferAction::Buffering => {
                                            // Still accumulating a potential tool call
                                        }
                                    }
                                }
                        }
                    }
                }

                if let Some(response) = pending_final_response.take() {
                    yield response;
                }

                // Flush any remaining buffered content from the tool call buffer
                for part in text_tool_buffer.flush() {
                    let is_tool = matches!(part, Part::FunctionCall { .. });
                    yield LlmResponse {
                        content: Some(Content {
                            role: "model".to_string(),
                            parts: vec![part],
                        }),
                        usage_metadata: None,
                        finish_reason: if is_tool { Some(adk_core::FinishReason::Stop) } else { None },
                        citation_metadata: None,
                        partial: !is_tool,
                        turn_complete: false,
                        interrupted: false,
                        error_code: None,
                        error_message: None,
                        provider_metadata: None,
                        interaction_id: None,
                    };
                }
            };

            Ok(crate::usage_tracking::with_usage_tracking(Box::pin(response_stream), usage_span))
        } else {
            // ── Non-streaming path (preserved identically) ──────────
            let response_stream = try_stream! {
                let response = execute_with_retry(&retry_config, is_retryable_model_error, || {
                    let model = model.clone();
                    let provider_name = provider_name.clone();
                    let http = http.clone();
                    let target = target.clone();
                    let body = request_body.clone();
                    async move {
                        let http_resp = send_request(&http, &target, &body).await?;

                        let raw_json: serde_json::Value = http_resp.json().await.map_err(|e| {
                            AdkError::new(
                                ErrorComponent::Model,
                                ErrorCategory::Internal,
                                error_codes.parse,
                                format!("{provider_name} response parse error: {e}"),
                            )
                            .with_provider(&provider_name)
                        })?;

                        tracing::debug!(
                            provider = %provider_name,
                            model = %model,
                            has_reasoning = raw_json
                                .pointer("/choices/0/message/reasoning_content")
                                .is_some(),
                            "openai chat completion response"
                        );

                        Ok(raw_json)
                    }
                })
                .await?;

                let adk_response = convert::from_raw_openai_response(&response, &declared_tools).map_err(|error| {
                    AdkError::new(
                        ErrorComponent::Model,
                        ErrorCategory::Internal,
                        error_codes.invalid_tool_arguments,
                        format!("{provider_name} returned {error}"),
                    )
                    .with_provider(&provider_name)
                })?;
                yield adk_response;
            };

            Ok(crate::usage_tracking::with_usage_tracking(Box::pin(response_stream), usage_span))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use adk_core::{GenericSchemaAdapter, LlmRequest, SchemaCache};
    use std::sync::Arc;

    mod sse_lines {
        use super::take_line;

        #[test]
        fn preserves_every_split() {
            let expected = r#"data: {"text":"é中文🙂�","arguments":"{\"path\":\"资料.txt\",\"text\":\"改动🙂\"}"}"#;
            let framed = format!("{expected}\r\n");
            for split in 0..framed.len() {
                let mut buffer = framed.as_bytes()[..split].to_vec();
                assert_eq!(take_line(&mut buffer).unwrap(), None);
                buffer.extend_from_slice(&framed.as_bytes()[split..]);
                assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some(expected));
                assert!(buffer.is_empty());
            }
        }

        #[test]
        fn accepts_bytewise_delivery() {
            let expected = "data: 中文🙂é";
            let mut buffer = Vec::new();
            for byte in expected.as_bytes() {
                buffer.push(*byte);
                assert_eq!(take_line(&mut buffer).unwrap(), None);
            }
            buffer.push(b'\n');
            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some(expected));
            assert!(buffer.is_empty());
        }

        #[test]
        fn leaves_following_lines() {
            let mut buffer = "data: 第一行\r\n\r\ndata: 第二行🙂\n".as_bytes().to_vec();
            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some("data: 第一行"));
            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some(""));
            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some("data: 第二行🙂"));
            assert_eq!(take_line(&mut buffer).unwrap(), None);
        }

        #[test]
        fn rejects_invalid_utf8() {
            for invalid in [b"data: \xc3(\n".as_slice(), b"data: \xf0\x9f\n".as_slice()] {
                assert!(take_line(&mut invalid.to_vec()).is_err());
            }
        }
    }

    #[test]
    fn test_parallel_tool_calls_config() {
        let config =
            OpenAICompatibleConfig::new("test-key", "test-model").with_parallel_tool_calls(false);

        assert!(!config.parallel_tool_calls, "parallel_tool_calls should be false in config");

        let client = OpenAICompatible::new(config).expect("client creation failed");
        assert!(!client.parallel_tool_calls, "parallel_tool_calls should be false in client");
    }

    #[test]
    fn test_parallel_tool_calls_default() {
        let config = OpenAICompatibleConfig::new("test-key", "test-model");

        assert!(config.parallel_tool_calls, "parallel_tool_calls should default to true");

        let client = OpenAICompatible::new(config).expect("client creation failed");
        assert!(client.parallel_tool_calls, "parallel_tool_calls should default to true in client");
    }

    #[test]
    fn streamed_tool_arguments_require_valid_json() {
        let parsed = parse_tool_call_arguments(
            "compatible-provider",
            ErrorCodes::COMPATIBLE,
            "bash",
            r#"{"command":"pwd"}"#,
        )
        .expect("valid arguments should parse");
        assert_eq!(parsed["command"], "pwd");

        assert_eq!(
            parse_tool_call_arguments("compatible-provider", ErrorCodes::COMPATIBLE, "no_args", "")
                .expect("an empty compatible payload should normalize"),
            serde_json::json!({})
        );
        assert_eq!(
            parse_tool_call_arguments(
                "compatible-provider",
                ErrorCodes::COMPATIBLE,
                "no_args",
                "   "
            )
            .expect("a whitespace-only compatible payload should normalize"),
            serde_json::json!({})
        );
        assert_eq!(
            parse_tool_call_arguments(
                "compatible-provider",
                ErrorCodes::COMPATIBLE,
                "no_args",
                "[]"
            )
            .expect("an empty array compatible payload should normalize"),
            serde_json::json!({})
        );

        let error = parse_tool_call_arguments(
            "compatible-provider",
            ErrorCodes::COMPATIBLE,
            "bash",
            r#"{"command":"#,
        )
        .expect_err("truncated arguments must remain invalid");
        assert_eq!(error.component, ErrorComponent::Model);
        assert_eq!(error.category, ErrorCategory::Internal);
        assert_eq!(error.code, "model.openai_compat.invalid_tool_arguments");
        assert_eq!(error.details.provider.as_deref(), Some("compatible-provider"));

        let error = parse_tool_call_arguments(
            "compatible-provider",
            ErrorCodes::COMPATIBLE,
            "bash",
            r#"["pwd"]"#,
        )
        .expect_err("non-empty array arguments must remain invalid");
        assert_eq!(error.code, "model.openai_compat.invalid_tool_arguments");
    }

    #[test]
    fn streamed_structured_tool_arguments_are_canonicalized() {
        let mut arguments = String::new();
        append_tool_call_arguments(&mut arguments, &serde_json::json!({"command": "pwd"}));

        assert_eq!(
            parse_tool_call_arguments(
                "compatible-provider",
                ErrorCodes::COMPATIBLE,
                "bash",
                &arguments
            )
            .expect("a structured object should normalize"),
            serde_json::json!({"command": "pwd"})
        );
    }

    #[test]
    fn streamed_empty_snapshot_before_string_fragments_is_ignored() {
        for placeholder in [serde_json::json!({}), serde_json::json!([])] {
            let mut arguments = String::new();
            append_tool_call_arguments(&mut arguments, &placeholder);
            assert_eq!(
                parse_tool_call_arguments(
                    "compatible-provider",
                    ErrorCodes::COMPATIBLE,
                    "no_args",
                    &arguments
                )
                .expect("an empty snapshot should remain a no-argument call"),
                serde_json::json!({})
            );

            append_tool_call_arguments(&mut arguments, &serde_json::json!(r#"{"command""#));
            append_tool_call_arguments(&mut arguments, &serde_json::json!(r#": "pwd"}"#));

            assert_eq!(
                parse_tool_call_arguments(
                    "compatible-provider",
                    ErrorCodes::COMPATIBLE,
                    "bash",
                    &arguments
                )
                .expect("empty snapshots must not prefix string fragments"),
                serde_json::json!({"command": "pwd"})
            );
        }
    }

    #[test]
    fn gpt_56_chat_tools_preserve_configured_reasoning() {
        let adapter = GenericSchemaAdapter;
        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
        let mut request = LlmRequest {
            model: crate::catalog::OPENAI_DEFAULT.to_string(),
            contents: Vec::new(),
            config: None,
            tools: HashMap::new(),
            previous_response_id: None,
        };
        request.tools.insert(
            "lookup".to_string(),
            serde_json::json!({
                "description": "Look up a record",
                "parameters": {"type": "object", "properties": {}}
            }),
        );

        for (configured_effort, expected) in [
            (None, None),
            (Some(OpenAIReasoningEffort::Medium), Some("medium")),
            (Some(OpenAIReasoningEffort::Max), Some("max")),
        ] {
            let body = build_request_json(
                crate::catalog::OPENAI_DEFAULT,
                &request,
                &configured_effort,
                ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
                None,
                &adapter,
                &cache,
            )
            .expect("request should build");

            assert_eq!(body.get("reasoning_effort").and_then(serde_json::Value::as_str), expected);
        }
    }

    #[test]
    fn gpt_56_without_tools_keeps_server_reasoning_default() {
        let adapter = GenericSchemaAdapter;
        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
        let request = LlmRequest {
            model: crate::catalog::OPENAI_DEFAULT.to_string(),
            contents: Vec::new(),
            config: None,
            tools: HashMap::new(),
            previous_response_id: None,
        };

        let body = build_request_json(
            crate::catalog::OPENAI_DEFAULT,
            &request,
            &None,
            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
            None,
            &adapter,
            &cache,
        )
        .expect("request should build");

        assert!(body.get("reasoning_effort").is_none());
    }

    #[test]
    fn gpt_56_chat_serializes_max_reasoning() {
        let adapter = GenericSchemaAdapter;
        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
        let request = LlmRequest {
            model: crate::catalog::OPENAI_DEFAULT.to_string(),
            contents: Vec::new(),
            config: None,
            tools: HashMap::new(),
            previous_response_id: None,
        };

        let body = build_request_json(
            crate::catalog::OPENAI_DEFAULT,
            &request,
            &Some(OpenAIReasoningEffort::Max),
            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
            None,
            &adapter,
            &cache,
        )
        .expect("request should build");

        assert_eq!(body["reasoning_effort"], "max");
    }

    #[test]
    fn gemini_37_compatible_path_rejects_sampling_locally() {
        let mut request = LlmRequest::new("gemini-3.7-flash", Vec::new());
        request.config =
            Some(adk_core::GenerateContentConfig { top_p: Some(0.9), ..Default::default() });
        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));

        let error = build_request_json(
            "gemini-3.7-flash",
            &request,
            &None,
            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
            None,
            &GenericSchemaAdapter,
            &cache,
        )
        .expect_err("sampling should be rejected before network I/O");

        assert_eq!(error.code, "model.gemini.sampling_unsupported");
    }

    #[test]
    fn orcarouter_preset_sets_endpoint_and_provider() {
        let config = OpenAICompatibleConfig::orcarouter("test-key", "openai/gpt-5.6-terra");
        assert_eq!(config.provider_name, "orcarouter");
        assert_eq!(config.model, "openai/gpt-5.6-terra");
        assert_eq!(config.base_url.as_deref(), Some("https://api.orcarouter.ai/v1"));
        assert_eq!(config.api_key, "test-key");

        let client = OpenAICompatible::new(config).expect("client builds");
        assert_eq!(client.name(), "openai/gpt-5.6-terra");
    }

    #[test]
    fn gemini_preset_sets_endpoint_and_provider() {
        let config = OpenAICompatibleConfig::gemini("test-key", "gemini-3.5-flash");
        assert_eq!(config.provider_name, "gemini");
        assert_eq!(config.model, "gemini-3.5-flash");
        assert_eq!(
            config.base_url.as_deref(),
            Some("https://generativelanguage.googleapis.com/v1beta/openai")
        );
        assert_eq!(config.api_key, "test-key");
    }

    #[test]
    fn gemini_preset_supports_reasoning_effort() {
        // Gemini's OpenAI-compat layer maps reasoning_effort onto thinking levels.
        let config = OpenAICompatibleConfig::gemini("k", "gemini-3.5-flash")
            .with_reasoning_effort(OaiReasoningEffort::Low);
        assert_eq!(config.reasoning_effort, Some(OaiReasoningEffort::Low));
    }

    #[test]
    fn gemini_preset_builds_client() {
        let config = OpenAICompatibleConfig::gemini("k", "gemini-3.5-flash");
        let client = OpenAICompatible::new(config).expect("client builds");
        assert_eq!(client.name(), "gemini-3.5-flash");
    }
}