siumai 0.10.3

A unified LLM interface library for Rust
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
//! Siumai LLM Interface
//!
//! This module provides the main siumai interface for calling different provider functionality,
//! similar to `llm_dart`'s approach. It uses dynamic dispatch to route calls to the
//! appropriate provider implementation.

use crate::client::LlmClient;
use crate::error::LlmError;
use crate::retry_api::RetryOptions;
use crate::stream::ChatStream;
use crate::traits::*;
use crate::types::*;
use std::collections::HashMap;
use std::time::Duration;

/// The main siumai LLM provider that can dynamically dispatch to different capabilities
///
/// This is inspired by `llm_dart`'s unified interface design, allowing you to
/// call different provider functionality through a single interface.
pub struct Siumai {
    /// The underlying provider client
    client: Box<dyn LlmClient>,
    /// Provider-specific metadata
    metadata: ProviderMetadata,
    /// Optional retry options for chat calls
    retry_options: Option<RetryOptions>,
}

impl Clone for Siumai {
    fn clone(&self) -> Self {
        // Clone the client using the ClientWrapper approach
        let client = self.client.clone_box();

        Self {
            client,
            metadata: self.metadata.clone(),
            retry_options: self.retry_options.clone(),
        }
    }
}

impl std::fmt::Debug for Siumai {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Siumai")
            .field("provider_type", &self.metadata.provider_type)
            .field("provider_name", &self.metadata.provider_name)
            .field(
                "supported_models_count",
                &self.metadata.supported_models.len(),
            )
            .field("capabilities", &self.metadata.capabilities)
            .finish()
    }
}

/// Metadata about the provider
#[derive(Debug, Clone)]
pub struct ProviderMetadata {
    pub provider_type: ProviderType,
    pub provider_name: String,
    pub supported_models: Vec<String>,
    pub capabilities: ProviderCapabilities,
}

impl Siumai {
    /// Create a new siumai provider
    pub fn new(client: Box<dyn LlmClient>) -> Self {
        let metadata = ProviderMetadata {
            provider_type: client.provider_type(),
            provider_name: client.provider_name().to_string(),
            supported_models: client.supported_models(),
            capabilities: client.capabilities(),
        };

        Self {
            client,
            metadata,
            retry_options: None,
        }
    }

    /// Attach retry options (builder-style)
    pub fn with_retry_options(mut self, options: Option<RetryOptions>) -> Self {
        self.retry_options = options;
        self
    }

    /// Check if a capability is supported
    pub fn supports(&self, capability: &str) -> bool {
        self.metadata.capabilities.supports(capability)
    }

    /// Get provider metadata
    pub const fn metadata(&self) -> &ProviderMetadata {
        &self.metadata
    }

    /// Get the underlying client
    pub fn client(&self) -> &dyn LlmClient {
        self.client.as_ref()
    }

    /// Type-safe audio capability access
    ///
    /// Note: This method provides access regardless of reported capability support.
    /// Actual support depends on the specific model being used.
    pub fn audio_capability(&self) -> AudioCapabilityProxy<'_> {
        AudioCapabilityProxy::new(self, self.supports("audio"))
    }

    /// Type-safe embedding capability access
    ///
    /// Note: This method provides access regardless of reported capability support.
    /// Actual support depends on the specific model being used.
    pub fn embedding_capability(&self) -> EmbeddingCapabilityProxy<'_> {
        EmbeddingCapabilityProxy::new(self, self.supports("embedding"))
    }

    /// Type-safe vision capability access
    ///
    /// Note: This method provides access regardless of reported capability support.
    /// Actual support depends on the specific model being used.
    pub fn vision_capability(&self) -> VisionCapabilityProxy<'_> {
        VisionCapabilityProxy::new(self, self.supports("vision"))
    }

    /// Generate embeddings for the given input texts
    ///
    /// This is a convenience method that directly calls the embedding functionality
    /// without requiring the user to go through the capability proxy.
    ///
    /// # Arguments
    /// * `texts` - List of strings to generate embeddings for
    ///
    /// # Returns
    /// List of embedding vectors (one per input text)
    ///
    /// # Example
    /// ```rust,no_run
    /// use siumai::prelude::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Siumai::builder()
    ///     .openai()
    ///     .api_key("your-api-key")
    ///     .build()
    ///     .await?;
    ///
    /// let texts = vec!["Hello, world!".to_string()];
    /// let response = client.embed(texts).await?;
    /// println!("Got {} embeddings", response.embeddings.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn embed(&self, texts: Vec<String>) -> Result<EmbeddingResponse, LlmError> {
        EmbeddingCapability::embed(self, texts).await
    }
}

#[async_trait::async_trait]
impl ChatCapability for Siumai {
    async fn chat_with_tools(
        &self,
        messages: Vec<ChatMessage>,
        tools: Option<Vec<Tool>>,
    ) -> Result<ChatResponse, LlmError> {
        if let Some(opts) = &self.retry_options {
            crate::retry_api::retry_with(
                || {
                    let m = messages.clone();
                    let t = tools.clone();
                    async move { self.client.chat_with_tools(m, t).await }
                },
                opts.clone(),
            )
            .await
        } else {
            self.client.chat_with_tools(messages, tools).await
        }
    }

    async fn chat_stream(
        &self,
        messages: Vec<ChatMessage>,
        tools: Option<Vec<Tool>>,
    ) -> Result<ChatStream, LlmError> {
        self.client.chat_stream(messages, tools).await
    }
}

#[async_trait::async_trait]
impl EmbeddingCapability for Siumai {
    async fn embed(&self, texts: Vec<String>) -> Result<EmbeddingResponse, LlmError> {
        // Use the new capability method instead of downcasting
        if let Some(embedding_client) = self.client.as_embedding_capability() {
            embedding_client.embed(texts).await
        } else {
            Err(LlmError::UnsupportedOperation(format!(
                "Provider {} does not support embedding functionality. Consider using OpenAI, Gemini, or Ollama for embeddings.",
                self.client.provider_name()
            )))
        }
    }

    fn embedding_dimension(&self) -> usize {
        // Use the new capability method to get dimension
        if let Some(embedding_client) = self.client.as_embedding_capability() {
            embedding_client.embedding_dimension()
        } else {
            // Fallback to default dimension based on provider
            match self.client.provider_name() {
                "openai" => 1536,
                "ollama" => 384,
                "gemini" => 768,
                _ => 1536,
            }
        }
    }

    fn max_tokens_per_embedding(&self) -> usize {
        // Use the new capability method to get max tokens
        if let Some(embedding_client) = self.client.as_embedding_capability() {
            embedding_client.max_tokens_per_embedding()
        } else {
            // Fallback to default based on provider
            match self.client.provider_name() {
                "openai" => 8192,
                "ollama" => 8192,
                "gemini" => 2048,
                _ => 8192,
            }
        }
    }

    fn supported_embedding_models(&self) -> Vec<String> {
        // Use the new capability method to get supported models
        if let Some(embedding_client) = self.client.as_embedding_capability() {
            embedding_client.supported_embedding_models()
        } else {
            // Fallback to default models based on provider
            match self.client.provider_name() {
                "openai" => vec![
                    "text-embedding-3-small".to_string(),
                    "text-embedding-3-large".to_string(),
                    "text-embedding-ada-002".to_string(),
                ],
                "ollama" => vec![
                    "nomic-embed-text".to_string(),
                    "mxbai-embed-large".to_string(),
                ],
                "gemini" => vec![
                    "embedding-001".to_string(),
                    "text-embedding-004".to_string(),
                ],
                _ => vec![],
            }
        }
    }
}

#[async_trait::async_trait]
impl EmbeddingExtensions for Siumai {
    /// Generate embeddings with advanced configuration including task types.
    ///
    /// This method enables the unified interface to support provider-specific features
    /// like Gemini's task type optimization, OpenAI's custom dimensions, etc.
    ///
    /// # Arguments
    /// * `request` - Detailed embedding request with configuration
    ///
    /// # Returns
    /// Embedding response with vectors and metadata
    ///
    /// # Example
    /// ```rust,no_run
    /// use siumai::prelude::*;
    /// use siumai::types::{EmbeddingRequest, EmbeddingTaskType};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Siumai::builder()
    ///         .gemini()
    ///         .api_key("your-api-key")
    ///         .model("gemini-embedding-001")
    ///         .build()
    ///         .await?;
    ///
    ///     // Use task type for optimization
    ///     let request = EmbeddingRequest::query("What is machine learning?");
    ///     let response = client.embed_with_config(request).await?;
    ///     Ok(())
    /// }
    /// ```
    async fn embed_with_config(
        &self,
        request: EmbeddingRequest,
    ) -> Result<EmbeddingResponse, LlmError> {
        // For now, we'll provide a simplified implementation that works with the current architecture
        // The advanced features like task types will be supported through provider-specific interfaces

        if let Some(embedding_client) = self.client.as_embedding_capability() {
            // Use the basic embed method - the underlying implementations
            // can be enhanced to support more features in the future
            embedding_client.embed(request.input).await
        } else {
            Err(LlmError::UnsupportedOperation(format!(
                "Provider {} does not support embedding functionality. Consider using OpenAI, Gemini, or Ollama for embeddings.",
                self.client.provider_name()
            )))
        }
    }

    /// List available embedding models with their capabilities.
    ///
    /// # Returns
    /// Vector of embedding model information including supported task types
    async fn list_embedding_models(&self) -> Result<Vec<EmbeddingModelInfo>, LlmError> {
        // For now, provide basic model information based on the provider
        if let Some(_embedding_client) = self.client.as_embedding_capability() {
            let models = self.supported_embedding_models();
            let model_infos = models
                .into_iter()
                .map(|id| {
                    let mut model_info = EmbeddingModelInfo::new(
                        id.clone(),
                        id,
                        self.embedding_dimension(),
                        self.max_tokens_per_embedding(),
                    );

                    // Add task type support for Gemini models
                    if self.client.provider_name() == "gemini" {
                        model_info = model_info
                            .with_task(EmbeddingTaskType::RetrievalQuery)
                            .with_task(EmbeddingTaskType::RetrievalDocument)
                            .with_task(EmbeddingTaskType::SemanticSimilarity)
                            .with_task(EmbeddingTaskType::Classification)
                            .with_task(EmbeddingTaskType::Clustering)
                            .with_task(EmbeddingTaskType::QuestionAnswering)
                            .with_task(EmbeddingTaskType::FactVerification);
                    }

                    // Add custom dimensions support for OpenAI models
                    if self.client.provider_name() == "openai" {
                        model_info = model_info.with_custom_dimensions();
                    }

                    model_info
                })
                .collect();
            Ok(model_infos)
        } else {
            Err(LlmError::UnsupportedOperation(format!(
                "Provider {} does not support embedding functionality.",
                self.client.provider_name()
            )))
        }
    }
}

impl LlmClient for Siumai {
    fn provider_name(&self) -> &'static str {
        // We need to return a static str, so we'll use a match
        match self.metadata.provider_type {
            ProviderType::OpenAi => "openai",
            ProviderType::Anthropic => "anthropic",
            ProviderType::Gemini => "gemini",
            ProviderType::XAI => "xai",
            ProviderType::Ollama => "ollama",
            ProviderType::Custom(_) => "custom",
            ProviderType::Groq => "groq",
        }
    }

    fn supported_models(&self) -> Vec<String> {
        self.metadata.supported_models.clone()
    }

    fn capabilities(&self) -> ProviderCapabilities {
        self.metadata.capabilities.clone()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn clone_box(&self) -> Box<dyn LlmClient> {
        Box::new(self.clone())
    }
}

/// Unified Interface Builder - Provider Abstraction Layer
///
/// ## 🎯 Core Responsibility: Unified Provider Interface
///
/// SiumaiBuilder provides a **unified interface** for creating LLM clients
/// across different providers while abstracting away provider-specific details.
///
/// ### ✅ What SiumaiBuilder Does:
/// - **Provider Abstraction**: Unified interface for all LLM providers
/// - **Parameter Unification**: Common parameter interface (temperature, max_tokens, etc.)
/// - **Reasoning Abstraction**: Unified reasoning interface across providers
/// - **Configuration Validation**: Validates configuration before client creation
/// - **Provider Selection**: Determines which provider to use based on configuration
/// - **Parameter Delegation**: Delegates to appropriate builders for actual construction
///
/// ### ❌ What SiumaiBuilder Does NOT Do:
/// - **Direct Client Creation**: Does not directly create HTTP clients
/// - **Parameter Mapping**: Does not handle provider-specific parameter mapping
/// - **HTTP Configuration**: Does not configure HTTP settings directly
///
/// ## 🏗️ Architecture Position
///
/// ```text
/// User Code
////// SiumaiBuilder (Unified Interface Layer) ← YOU ARE HERE
////// ┌─────────────────┬─────────────────────────────────────┐
/// ↓                 ↓                                     ↓
/// LlmBuilder        RequestBuilder                Provider Clients
/// (Client Config)   (Parameter Management)        (Implementation)
/// ```
///
/// ## 🔄 Delegation Pattern
///
/// SiumaiBuilder acts as a **coordinator** that delegates to specialized builders:
///
/// 1. **Parameter Validation**: Uses RequestBuilder for parameter validation
/// 2. **Client Construction**: Uses LlmBuilder or direct client constructors
/// 3. **Provider Selection**: Chooses appropriate implementation based on provider type
///
/// ### Example Flow:
/// ```rust,no_run
/// use siumai::prelude::*;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // 1. User configures through unified interface
///     let client = Siumai::builder()
///         .anthropic()                    // Provider selection
///         .api_key("your-api-key")        // Required API key
///         .model("claude-3-5-sonnet")     // Common parameter
///         .temperature(0.7)               // Common parameter
///         .reasoning(true)                // Unified reasoning
///         .build().await?;                // Delegation to appropriate builders
///     Ok(())
/// }
/// ```
///
/// This design allows users to switch providers with minimal code changes
/// while maintaining access to provider-specific features when needed.
pub struct SiumaiBuilder {
    pub(crate) provider_type: Option<ProviderType>,
    pub(crate) provider_name: Option<String>,
    api_key: Option<String>,
    base_url: Option<String>,
    capabilities: Vec<String>,
    common_params: CommonParams,
    http_config: HttpConfig,
    organization: Option<String>,
    project: Option<String>,
    tracing_config: Option<crate::tracing::TracingConfig>,
    // Unified reasoning configuration
    reasoning_enabled: Option<bool>,
    reasoning_budget: Option<i32>,
    // Unified retry configuration
    retry_options: Option<RetryOptions>,
}

impl SiumaiBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            provider_type: None,
            provider_name: None,
            api_key: None,
            base_url: None,
            capabilities: Vec::new(),
            common_params: CommonParams::default(),
            http_config: HttpConfig::default(),
            organization: None,
            project: None,
            tracing_config: None,
            reasoning_enabled: None,
            reasoning_budget: None,
            retry_options: None,
        }
    }

    /// Set the provider type
    pub fn provider(mut self, provider_type: ProviderType) -> Self {
        self.provider_type = Some(provider_type);
        self
    }

    /// Set the provider by name (dynamic dispatch)
    /// This provides the llm_dart-style ai().provider('name') interface
    pub fn provider_name<S: Into<String>>(mut self, name: S) -> Self {
        let name = name.into();
        self.provider_name = Some(name.clone());

        // Map provider name to type
        self.provider_type = Some(match name.as_str() {
            "openai" => ProviderType::OpenAi,
            "anthropic" => ProviderType::Anthropic,
            "gemini" => ProviderType::Gemini,
            "ollama" => ProviderType::Ollama,
            "xai" => ProviderType::XAI,
            "groq" => ProviderType::Groq,
            "siliconflow" => ProviderType::Custom("siliconflow".to_string()),
            "deepseek" => ProviderType::Custom("deepseek".to_string()),
            "openrouter" => ProviderType::Custom("openrouter".to_string()),
            _ => ProviderType::Custom(name),
        });
        self
    }

    // Provider convenience methods are now defined in src/provider_builders.rs

    /// Set the API key
    pub fn api_key<S: Into<String>>(mut self, api_key: S) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Set the base URL
    pub fn base_url<S: Into<String>>(mut self, base_url: S) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Set the model
    pub fn model<S: Into<String>>(mut self, model: S) -> Self {
        self.common_params.model = model.into();
        self
    }

    /// Set temperature
    pub const fn temperature(mut self, temperature: f32) -> Self {
        self.common_params.temperature = Some(temperature);
        self
    }

    /// Set max tokens
    pub const fn max_tokens(mut self, max_tokens: u32) -> Self {
        self.common_params.max_tokens = Some(max_tokens);
        self
    }

    /// Set top_p (nucleus sampling parameter)
    pub const fn top_p(mut self, top_p: f32) -> Self {
        self.common_params.top_p = Some(top_p);
        self
    }

    /// Set random seed for reproducible outputs
    pub const fn seed(mut self, seed: u64) -> Self {
        self.common_params.seed = Some(seed);
        self
    }

    /// Set stop sequences
    pub fn stop_sequences(mut self, sequences: Vec<String>) -> Self {
        self.common_params.stop_sequences = Some(sequences);
        self
    }

    /// Enable or disable reasoning mode (unified interface)
    ///
    /// This method provides a unified interface for enabling reasoning across all providers.
    /// It maps to provider-specific methods:
    /// - Anthropic: `thinking_budget` (10k tokens when enabled)
    /// - Gemini: `thinking` (dynamic when enabled)
    /// - Ollama: `reasoning` (enabled/disabled)
    /// - DeepSeek: `reasoning` (enabled/disabled)
    pub const fn reasoning(mut self, enabled: bool) -> Self {
        self.reasoning_enabled = Some(enabled);
        self
    }

    /// Set reasoning budget (unified interface)
    ///
    /// This method provides a unified interface for setting reasoning budgets.
    /// Different providers interpret this differently:
    /// - Anthropic: Direct token budget
    /// - Gemini: Token budget (-1 for dynamic, 0 for disabled)
    /// - Ollama: Ignored (uses boolean reasoning mode)
    /// - DeepSeek: Ignored (uses boolean reasoning mode)
    pub const fn reasoning_budget(mut self, budget: i32) -> Self {
        self.reasoning_budget = Some(budget);
        // If budget is set, automatically enable reasoning
        if budget > 0 {
            self.reasoning_enabled = Some(true);
        } else if budget == 0 {
            self.reasoning_enabled = Some(false);
        }
        self
    }

    /// Set organization (for `OpenAI`)
    pub fn organization<S: Into<String>>(mut self, organization: S) -> Self {
        self.organization = Some(organization.into());
        self
    }

    /// Set project (for `OpenAI`)
    pub fn project<S: Into<String>>(mut self, project: S) -> Self {
        self.project = Some(project.into());
        self
    }

    /// Enable a specific capability
    pub fn with_capability<S: Into<String>>(mut self, capability: S) -> Self {
        self.capabilities.push(capability.into());
        self
    }

    /// Enable audio capability
    pub fn with_audio(self) -> Self {
        self.with_capability("audio")
    }

    /// Enable vision capability
    pub fn with_vision(self) -> Self {
        self.with_capability("vision")
    }

    /// Enable embedding capability
    pub fn with_embedding(self) -> Self {
        self.with_capability("embedding")
    }

    /// Enable image generation capability
    pub fn with_image_generation(self) -> Self {
        self.with_capability("image_generation")
    }

    // === HTTP configuration (fine-grained) ===

    /// Set HTTP request timeout
    pub fn http_timeout(mut self, timeout: Duration) -> Self {
        self.http_config.timeout = Some(timeout);
        self
    }

    /// Set HTTP connect timeout
    pub fn http_connect_timeout(mut self, timeout: Duration) -> Self {
        self.http_config.connect_timeout = Some(timeout);
        self
    }

    /// Set HTTP user agent
    pub fn http_user_agent<S: Into<String>>(mut self, user_agent: S) -> Self {
        self.http_config.user_agent = Some(user_agent.into());
        self
    }

    /// Set HTTP proxy URL
    pub fn http_proxy<S: Into<String>>(mut self, proxy_url: S) -> Self {
        self.http_config.proxy = Some(proxy_url.into());
        self
    }

    /// Add a default HTTP header
    pub fn http_header<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.http_config.headers.insert(key.into(), value.into());
        self
    }

    /// Merge multiple default HTTP headers
    pub fn http_headers(mut self, headers: HashMap<String, String>) -> Self {
        self.http_config.headers.extend(headers);
        self
    }

    // === Tracing Configuration ===

    /// Set custom tracing configuration
    ///
    /// This allows you to configure detailed tracing and monitoring for this client.
    /// The tracing configuration will override any global tracing settings.
    ///
    /// # Arguments
    /// * `config` - The tracing configuration to use
    ///
    /// # Example
    /// ```rust,no_run
    /// use siumai::prelude::*;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Siumai::builder()
    ///     .openai()
    ///     .api_key("your-key")
    ///     .model("gpt-4o-mini")
    ///     .tracing(TracingConfig::debug())
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn tracing(mut self, config: crate::tracing::TracingConfig) -> Self {
        self.tracing_config = Some(config);
        self
    }

    /// Enable debug tracing (development-friendly configuration)
    pub fn debug_tracing(self) -> Self {
        self.tracing(crate::tracing::TracingConfig::development())
    }

    /// Enable minimal tracing (info level, LLM only)
    pub fn minimal_tracing(self) -> Self {
        self.tracing(crate::tracing::TracingConfig::minimal())
    }

    /// Enable production-ready JSON tracing
    pub fn json_tracing(self) -> Self {
        self.tracing(crate::tracing::TracingConfig::json_production())
    }

    /// Enable simple tracing (uses debug configuration)
    pub fn enable_tracing(self) -> Self {
        self.debug_tracing()
    }

    /// Disable tracing explicitly
    pub fn disable_tracing(self) -> Self {
        self.tracing(crate::tracing::TracingConfig::disabled())
    }

    /// Set unified retry options for chat operations
    pub fn with_retry(mut self, options: RetryOptions) -> Self {
        self.retry_options = Some(options);
        self
    }

    /// Build the siumai provider
    pub async fn build(self) -> Result<Siumai, LlmError> {
        // Helper: build an HTTP client from HttpConfig
        fn build_http_client_from_config(cfg: &HttpConfig) -> Result<reqwest::Client, LlmError> {
            let mut builder = reqwest::Client::builder();

            if let Some(timeout) = cfg.timeout {
                builder = builder.timeout(timeout);
            }
            if let Some(connect_timeout) = cfg.connect_timeout {
                builder = builder.connect_timeout(connect_timeout);
            }
            if let Some(proxy_url) = &cfg.proxy {
                let proxy = reqwest::Proxy::all(proxy_url)
                    .map_err(|e| LlmError::ConfigurationError(format!("Invalid proxy URL: {e}")))?;
                builder = builder.proxy(proxy);
            }
            if let Some(user_agent) = &cfg.user_agent {
                builder = builder.user_agent(user_agent);
            }

            // Default headers
            if !cfg.headers.is_empty() {
                let mut headers = reqwest::header::HeaderMap::new();
                for (k, v) in &cfg.headers {
                    let name =
                        reqwest::header::HeaderName::from_bytes(k.as_bytes()).map_err(|e| {
                            LlmError::ConfigurationError(format!("Invalid header name '{k}': {e}"))
                        })?;
                    let value = reqwest::header::HeaderValue::from_str(v).map_err(|e| {
                        LlmError::ConfigurationError(format!("Invalid header value for '{k}': {e}"))
                    })?;
                    headers.insert(name, value);
                }
                builder = builder.default_headers(headers);
            }

            builder.build().map_err(|e| {
                LlmError::ConfigurationError(format!("Failed to build HTTP client: {e}"))
            })
        }

        // Extract all needed values first to avoid borrow checker issues
        let provider_type = self.provider_type.clone().ok_or_else(|| {
            LlmError::ConfigurationError("Provider type not specified".to_string())
        })?;

        // Check if API key is required for this provider type
        let requires_api_key = match provider_type {
            ProviderType::Ollama => false, // Ollama doesn't require API key
            _ => true,                     // All other providers require API key
        };

        let api_key = if requires_api_key {
            self.api_key
                .clone()
                .ok_or_else(|| LlmError::ConfigurationError("API key not specified".to_string()))?
        } else {
            // For providers that don't require API key, use empty string or None
            self.api_key.clone().unwrap_or_default()
        };

        // Extract all needed values to avoid borrow checker issues
        let base_url = self.base_url.clone();
        let organization = self.organization.clone();
        let project = self.project.clone();
        let reasoning_enabled = self.reasoning_enabled;
        let reasoning_budget = self.reasoning_budget;
        let http_config = self.http_config.clone();
        // Build one HTTP client for this builder, reuse across providers when possible
        let built_http_client = build_http_client_from_config(&http_config)?;

        // Prepare common parameters with the correct model
        let mut common_params = self.common_params.clone();

        // Set default model if none provided
        if common_params.model.is_empty() {
            // Set default model based on provider type
            #[cfg(any(feature = "openai", feature = "anthropic", feature = "google"))]
            use crate::types::models::model_constants as models;

            common_params.model = match provider_type {
                #[cfg(feature = "openai")]
                ProviderType::OpenAi => models::openai::GPT_4O.to_string(),
                #[cfg(feature = "anthropic")]
                ProviderType::Anthropic => models::anthropic::CLAUDE_SONNET_3_5.to_string(),
                #[cfg(feature = "google")]
                ProviderType::Gemini => models::gemini::GEMINI_2_5_FLASH.to_string(),
                #[cfg(feature = "ollama")]
                ProviderType::Ollama => "llama3.2".to_string(),
                #[cfg(feature = "xai")]
                ProviderType::XAI => "grok-beta".to_string(),
                #[cfg(feature = "groq")]
                ProviderType::Groq => "llama-3.1-70b-versatile".to_string(),
                ProviderType::Custom(ref name) => match name.as_str() {
                    #[cfg(feature = "openai")]
                    "siliconflow" => {
                        models::openai_compatible::siliconflow::DEEPSEEK_V3_1.to_string()
                    }
                    #[cfg(feature = "openai")]
                    "deepseek" => models::openai_compatible::deepseek::CHAT.to_string(),
                    #[cfg(feature = "openai")]
                    "openrouter" => models::openai_compatible::openrouter::GPT_4O.to_string(),
                    _ => "default-model".to_string(),
                },

                // For disabled features, return error
                #[cfg(not(feature = "openai"))]
                ProviderType::OpenAi => {
                    return Err(LlmError::UnsupportedOperation(
                        "OpenAI feature not enabled".to_string(),
                    ));
                }
                #[cfg(not(feature = "anthropic"))]
                ProviderType::Anthropic => {
                    return Err(LlmError::UnsupportedOperation(
                        "Anthropic feature not enabled".to_string(),
                    ));
                }
                #[cfg(not(feature = "google"))]
                ProviderType::Gemini => {
                    return Err(LlmError::UnsupportedOperation(
                        "Google feature not enabled".to_string(),
                    ));
                }
                #[cfg(not(feature = "ollama"))]
                ProviderType::Ollama => {
                    return Err(LlmError::UnsupportedOperation(
                        "Ollama feature not enabled".to_string(),
                    ));
                }
                #[cfg(not(feature = "xai"))]
                ProviderType::XAI => {
                    return Err(LlmError::UnsupportedOperation(
                        "xAI feature not enabled".to_string(),
                    ));
                }
                #[cfg(not(feature = "groq"))]
                ProviderType::Groq => {
                    return Err(LlmError::UnsupportedOperation(
                        "Groq feature not enabled".to_string(),
                    ));
                }
            };
        }

        // Build provider-specific parameters
        let provider_params = match provider_type {
            ProviderType::Anthropic => {
                let mut params = ProviderParams::anthropic();

                // Map unified reasoning parameters to Anthropic-specific parameters
                if let Some(budget) = reasoning_budget {
                    params = params.with_param("thinking_budget", budget as u32);
                }

                Some(params)
            }
            ProviderType::Gemini => {
                let mut params = ProviderParams::gemini();

                // Map unified reasoning parameters to Gemini-specific parameters
                if let Some(budget) = reasoning_budget {
                    params = params.with_param("thinking_budget", budget as u32);
                }

                Some(params)
            }
            ProviderType::Ollama => {
                let mut params = ProviderParams::new();

                // Map unified reasoning to Ollama thinking
                if reasoning_enabled.unwrap_or(false) {
                    params = params.with_param("think", true);
                }

                Some(params)
            }
            _ => {
                // For other providers, no specific parameters for now
                None
            }
        };

        // Use RequestBuilder to validate parameters
        let _request_builder =
            crate::request_factory::RequestBuilderFactory::create_and_validate_builder(
                &provider_type,
                common_params.clone(),
                provider_params.clone(),
            )?;

        // Now create the appropriate client based on provider type
        // Parameters have already been validated by RequestBuilder
        let client: Box<dyn LlmClient> = match provider_type {
            #[cfg(feature = "openai")]
            ProviderType::OpenAi => {
                let mut config = crate::providers::openai::OpenAiConfig::new(api_key)
                    .with_base_url(
                        base_url.unwrap_or_else(|| "https://api.openai.com/v1".to_string()),
                    )
                    .with_model(common_params.model.clone());

                // Use validated common parameters
                if let Some(temp) = common_params.temperature {
                    config = config.with_temperature(temp);
                }
                if let Some(max_tokens) = common_params.max_tokens {
                    config = config.with_max_tokens(max_tokens);
                }

                // Set organization and project if provided
                if let Some(org) = organization {
                    config = config.with_organization(org);
                }
                if let Some(proj) = project {
                    config = config.with_project(proj);
                }

                let mut client =
                    crate::providers::openai::OpenAiClient::new(config, built_http_client.clone());
                // Initialize tracing if configured
                if let Some(tc) = self.tracing_config.clone() {
                    let guard = crate::tracing::init_tracing(tc).map_err(|e| {
                        LlmError::ConfigurationError(format!("Failed to init tracing: {e}"))
                    })?;
                    client.set_tracing_guard(guard);
                }
                Box::new(client)
            }
            #[cfg(feature = "anthropic")]
            ProviderType::Anthropic => {
                let anthropic_base_url =
                    base_url.unwrap_or_else(|| "https://api.anthropic.com".to_string());

                // Extract Anthropic-specific parameters from validated provider_params
                let mut anthropic_params = crate::params::AnthropicParams::default();
                if let Some(ref params) = provider_params
                    && let Some(budget) = params.get::<u32>("thinking_budget")
                {
                    anthropic_params.thinking_budget = Some(budget);
                }

                let mut client = crate::providers::anthropic::AnthropicClient::new(
                    api_key,
                    anthropic_base_url,
                    built_http_client.clone(),
                    common_params.clone(),
                    anthropic_params,
                    http_config.clone(),
                );
                if let Some(tc) = self.tracing_config.clone() {
                    let guard = crate::tracing::init_tracing(tc.clone()).map_err(|e| {
                        LlmError::ConfigurationError(format!("Failed to init tracing: {e}"))
                    })?;
                    client.set_tracing_guard(guard);
                    client.set_tracing_config(self.tracing_config.clone());
                }
                Box::new(client)
            }
            #[cfg(feature = "google")]
            ProviderType::Gemini => {
                // Create Gemini client using the provider-specific builder
                // Parameters have already been validated by RequestBuilder
                // Map HttpConfig into LlmBuilder to inherit timeouts/UA/proxy where supported
                let mut base_builder = crate::builder::LlmBuilder::new();
                if let Some(t) = http_config.timeout {
                    base_builder = base_builder.with_timeout(t);
                }
                if let Some(ct) = http_config.connect_timeout {
                    base_builder = base_builder.with_connect_timeout(ct);
                }
                if let Some(ref ua) = http_config.user_agent {
                    base_builder = base_builder.with_user_agent(ua);
                }
                if let Some(ref proxy) = http_config.proxy {
                    base_builder = base_builder.with_proxy(proxy.clone());
                }
                for (k, v) in &http_config.headers {
                    base_builder = base_builder.with_header(k.clone(), v.clone());
                }

                let mut builder = base_builder
                    .gemini()
                    .api_key(api_key)
                    .model(&common_params.model);

                // Apply validated common parameters
                if let Some(temp) = common_params.temperature {
                    builder = builder.temperature(temp);
                }
                if let Some(max_tokens) = common_params.max_tokens {
                    builder = builder.max_tokens(max_tokens as i32);
                }
                if let Some(top_p) = common_params.top_p {
                    builder = builder.top_p(top_p);
                }

                // Apply provider-specific parameters from validated provider_params
                if let Some(ref params) = provider_params
                    && let Some(budget) = params.get::<u32>("thinking_budget")
                {
                    builder = builder.thinking_budget(budget as i32);
                }

                // Apply tracing
                if let Some(tc) = self.tracing_config.clone() {
                    builder = builder.tracing(tc);
                }

                Box::new(builder.build().await.map_err(|e| {
                    LlmError::ConfigurationError(format!("Failed to build Gemini client: {e}"))
                })?)
            }
            #[cfg(feature = "xai")]
            ProviderType::XAI => {
                // Create xAI client using the provider-specific builder
                // Parameters have already been validated by RequestBuilder
                let mut base_builder = crate::builder::LlmBuilder::new();
                if let Some(t) = http_config.timeout {
                    base_builder = base_builder.with_timeout(t);
                }
                if let Some(ct) = http_config.connect_timeout {
                    base_builder = base_builder.with_connect_timeout(ct);
                }
                if let Some(ref ua) = http_config.user_agent {
                    base_builder = base_builder.with_user_agent(ua);
                }
                if let Some(ref proxy) = http_config.proxy {
                    base_builder = base_builder.with_proxy(proxy.clone());
                }
                for (k, v) in &http_config.headers {
                    base_builder = base_builder.with_header(k.clone(), v.clone());
                }

                let mut builder = base_builder
                    .xai()
                    .api_key(api_key)
                    .model(&common_params.model);

                // Apply validated common parameters
                if let Some(temp) = common_params.temperature {
                    builder = builder.temperature(temp);
                }
                if let Some(max_tokens) = common_params.max_tokens {
                    builder = builder.max_tokens(max_tokens);
                }
                if let Some(top_p) = common_params.top_p {
                    builder = builder.top_p(top_p);
                }

                if let Some(tc) = self.tracing_config.clone() {
                    builder = builder.tracing(tc);
                }

                Box::new(builder.build().await.map_err(|e| {
                    LlmError::ConfigurationError(format!("Failed to build xAI client: {e}"))
                })?)
            }
            #[cfg(feature = "ollama")]
            ProviderType::Ollama => {
                let ollama_base_url =
                    base_url.unwrap_or_else(|| "http://localhost:11434".to_string());

                // Extract Ollama-specific parameters from validated provider_params
                let mut ollama_params = crate::providers::ollama::config::OllamaParams::default();
                if let Some(ref params) = provider_params
                    && let Some(think) = params.get::<bool>("think")
                {
                    ollama_params.think = Some(think);
                }

                let config = crate::providers::ollama::config::OllamaConfig {
                    base_url: ollama_base_url,
                    model: Some(common_params.model.clone()),
                    common_params: common_params.clone(),
                    ollama_params,
                    http_config,
                };

                let mut client =
                    crate::providers::ollama::OllamaClient::new(config, built_http_client.clone());
                if let Some(tc) = self.tracing_config.clone() {
                    let guard = crate::tracing::init_tracing(tc.clone()).map_err(|e| {
                        LlmError::ConfigurationError(format!("Failed to init tracing: {e}"))
                    })?;
                    client.set_tracing_guard(guard);
                    client.set_tracing_config(self.tracing_config.clone());
                }
                Box::new(client)
            }
            #[cfg(feature = "groq")]
            ProviderType::Groq => {
                let groq_base_url =
                    base_url.unwrap_or_else(|| "https://api.groq.com/openai/v1".to_string());

                let mut config = crate::providers::groq::GroqConfig::new(api_key)
                    .with_base_url(groq_base_url)
                    .with_model(common_params.model.clone());

                // Use validated common parameters
                if let Some(temp) = common_params.temperature {
                    config = config.with_temperature(temp);
                }
                if let Some(max_tokens) = common_params.max_tokens {
                    config = config.with_max_tokens(max_tokens);
                }

                let mut client =
                    crate::providers::groq::GroqClient::new(config, built_http_client.clone());
                if let Some(tc) = self.tracing_config.clone() {
                    let guard = crate::tracing::init_tracing(tc.clone()).map_err(|e| {
                        LlmError::ConfigurationError(format!("Failed to init tracing: {e}"))
                    })?;
                    client.set_tracing_guard(guard);
                    client.set_tracing_config(self.tracing_config.clone());
                }
                Box::new(client)
            }
            ProviderType::Custom(name) => {
                match name.as_str() {
                    #[cfg(feature = "openai")]
                    "deepseek" => {
                        // Use OpenAI-compatible client for DeepSeek with registry adapter
                        let adapter =
                            crate::providers::openai_compatible::get_provider_adapter("deepseek")?;

                        let base_url =
                            base_url.unwrap_or_else(|| "https://api.deepseek.com/v1".to_string());

                        let mut config =
                            crate::providers::openai_compatible::OpenAiCompatibleConfig::new(
                                "deepseek", &api_key, &base_url, adapter,
                            );

                        // Set model
                        config = config.with_model(&common_params.model);

                        // Set common parameters through common_params field
                        if let Some(temp) = common_params.temperature {
                            config.common_params.temperature = Some(temp);
                        }
                        if let Some(max_tokens) = common_params.max_tokens {
                            config.common_params.max_tokens = Some(max_tokens);
                        }

                        // Propagate HTTP config
                        let config = config.with_http_config(http_config.clone());
                        let client = crate::providers::openai_compatible::OpenAiCompatibleClient::with_http_client(
                            config,
                            built_http_client.clone(),
                        )
                        .await?;
                        Box::new(client)
                    }
                    #[cfg(feature = "openai")]
                    "siliconflow" => {
                        // Use OpenAI-compatible client for SiliconFlow (adapter-based)
                        let adapter = crate::providers::openai_compatible::get_provider_adapter(
                            "siliconflow",
                        )?;
                        let base_url =
                            base_url.unwrap_or_else(|| "https://api.siliconflow.cn/v1".to_string());

                        let mut config =
                            crate::providers::openai_compatible::OpenAiCompatibleConfig::new(
                                "siliconflow",
                                &api_key,
                                &base_url,
                                adapter,
                            );
                        // Set model
                        config = config.with_model(&common_params.model);
                        // Set common parameters
                        if let Some(temp) = common_params.temperature {
                            config.common_params.temperature = Some(temp);
                        }
                        if let Some(max_tokens) = common_params.max_tokens {
                            config.common_params.max_tokens = Some(max_tokens);
                        }
                        // Propagate HTTP config
                        let config = config.with_http_config(http_config.clone());
                        let client = crate::providers::openai_compatible::OpenAiCompatibleClient::with_http_client(
                            config,
                            built_http_client.clone(),
                        )
                        .await?;
                        Box::new(client)
                    }
                    #[cfg(feature = "openai")]
                    "openrouter" => {
                        // Use OpenAI-compatible client for OpenRouter (adapter-based)
                        let adapter = crate::providers::openai_compatible::get_provider_adapter(
                            "openrouter",
                        )?;
                        let base_url =
                            base_url.unwrap_or_else(|| "https://openrouter.ai/api/v1".to_string());

                        let mut config =
                            crate::providers::openai_compatible::OpenAiCompatibleConfig::new(
                                "openrouter",
                                &api_key,
                                &base_url,
                                adapter,
                            );
                        // Set model
                        config = config.with_model(&common_params.model);
                        // Set common parameters
                        if let Some(temp) = common_params.temperature {
                            config.common_params.temperature = Some(temp);
                        }
                        if let Some(max_tokens) = common_params.max_tokens {
                            config.common_params.max_tokens = Some(max_tokens);
                        }
                        // Propagate HTTP config
                        let config = config.with_http_config(http_config.clone());
                        let client = crate::providers::openai_compatible::OpenAiCompatibleClient::with_http_client(
                            config,
                            built_http_client.clone(),
                        )
                        .await?;
                        Box::new(client)
                    }

                    _ => {
                        return Err(LlmError::UnsupportedOperation(format!(
                            "Custom provider '{name}' not yet implemented"
                        )));
                    }
                }
            }

            // Handle cases where required features are not enabled
            #[cfg(not(feature = "openai"))]
            ProviderType::OpenAi => {
                return Err(LlmError::UnsupportedOperation(
                    "OpenAI provider requires the 'openai' feature to be enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "anthropic"))]
            ProviderType::Anthropic => {
                return Err(LlmError::UnsupportedOperation(
                    "Anthropic provider requires the 'anthropic' feature to be enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "google"))]
            ProviderType::Gemini => {
                return Err(LlmError::UnsupportedOperation(
                    "Gemini provider requires the 'google' feature to be enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "ollama"))]
            ProviderType::Ollama => {
                return Err(LlmError::UnsupportedOperation(
                    "Ollama provider requires the 'ollama' feature to be enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "xai"))]
            ProviderType::XAI => {
                return Err(LlmError::UnsupportedOperation(
                    "xAI provider requires the 'xai' feature to be enabled".to_string(),
                ));
            }
            #[cfg(not(feature = "groq"))]
            ProviderType::Groq => {
                return Err(LlmError::UnsupportedOperation(
                    "Groq provider requires the 'groq' feature to be enabled".to_string(),
                ));
            }
        };

        let siumai = Siumai::new(client).with_retry_options(self.retry_options.clone());
        Ok(siumai)
    }
}

/// Type-safe proxy for audio capabilities
pub struct AudioCapabilityProxy<'a> {
    provider: &'a Siumai,
    reported_support: bool,
}

impl<'a> AudioCapabilityProxy<'a> {
    pub const fn new(provider: &'a Siumai, reported_support: bool) -> Self {
        Self {
            provider,
            reported_support,
        }
    }

    /// Check if the provider reports audio support (for reference only)
    ///
    /// Note: This is based on static capability information and may not reflect
    /// the actual capabilities of the current model. Use as a hint, not a restriction.
    /// The library will never block operations based on this information.
    pub const fn is_reported_as_supported(&self) -> bool {
        self.reported_support
    }

    /// Get provider name for debugging
    pub fn provider_name(&self) -> &'static str {
        self.provider.provider_name()
    }

    /// Get a support status message (optional, for user-controlled warnings)
    ///
    /// Returns a message about support status that you can choose to display or ignore.
    /// The library itself will not automatically warn or log anything.
    pub fn support_status_message(&self) -> String {
        if self.reported_support {
            format!("Provider {} reports audio support", self.provider_name())
        } else {
            format!(
                "Provider {} does not report audio support, but this may still work depending on the model",
                self.provider_name()
            )
        }
    }

    /// Placeholder for future audio operations
    ///
    /// This will attempt the operation regardless of reported support.
    /// Actual errors will come from the API if the model doesn't support it.
    pub async fn placeholder_operation(&self) -> Result<String, LlmError> {
        // No automatic warnings - let the user decide if they want to check support
        Err(LlmError::UnsupportedOperation(
            "Audio operations not yet implemented. Use provider-specific client.".to_string(),
        ))
    }
}

/// Type-safe proxy for embedding capabilities
pub struct EmbeddingCapabilityProxy<'a> {
    provider: &'a Siumai,
    reported_support: bool,
}

impl<'a> EmbeddingCapabilityProxy<'a> {
    pub const fn new(provider: &'a Siumai, reported_support: bool) -> Self {
        Self {
            provider,
            reported_support,
        }
    }

    /// Check if the provider reports embedding support (for reference only)
    pub const fn is_reported_as_supported(&self) -> bool {
        self.reported_support
    }

    /// Get provider name for debugging
    pub fn provider_name(&self) -> &'static str {
        self.provider.provider_name()
    }

    /// Get a support status message (optional, for user-controlled information)
    pub fn support_status_message(&self) -> String {
        if self.reported_support {
            format!(
                "Provider {} reports embedding support",
                self.provider_name()
            )
        } else {
            format!(
                "Provider {} does not report embedding support, but this may still work depending on the model",
                self.provider_name()
            )
        }
    }

    /// Generate embeddings for the given input texts
    pub async fn embed(&self, texts: Vec<String>) -> Result<EmbeddingResponse, LlmError> {
        self.provider.embed(texts).await
    }

    /// Get the dimension of embeddings produced by this provider
    pub fn embedding_dimension(&self) -> usize {
        self.provider.embedding_dimension()
    }

    /// Get the maximum number of tokens that can be embedded at once
    pub fn max_tokens_per_embedding(&self) -> usize {
        self.provider.max_tokens_per_embedding()
    }

    /// Get supported embedding models for this provider
    pub fn supported_embedding_models(&self) -> Vec<String> {
        self.provider.supported_embedding_models()
    }

    /// Placeholder for future embedding operations (deprecated, use embed() instead)
    #[deprecated(note = "Use embed() method instead")]
    pub async fn placeholder_operation(&self) -> Result<String, LlmError> {
        // No automatic warnings - let the user decide if they want to check support
        Err(LlmError::UnsupportedOperation(
            "Use embed() method instead of placeholder_operation()".to_string(),
        ))
    }
}

/// Type-safe proxy for vision capabilities
pub struct VisionCapabilityProxy<'a> {
    provider: &'a Siumai,
    reported_support: bool,
}

impl<'a> VisionCapabilityProxy<'a> {
    pub const fn new(provider: &'a Siumai, reported_support: bool) -> Self {
        Self {
            provider,
            reported_support,
        }
    }

    /// Check if the provider reports vision support (for reference only)
    pub const fn is_reported_as_supported(&self) -> bool {
        self.reported_support
    }

    /// Get provider name for debugging
    pub fn provider_name(&self) -> &'static str {
        self.provider.provider_name()
    }

    /// Get a support status message (optional, for user-controlled information)
    pub fn support_status_message(&self) -> String {
        if self.reported_support {
            format!("Provider {} reports vision support", self.provider_name())
        } else {
            format!(
                "Provider {} does not report vision support, but this may still work depending on the model",
                self.provider_name()
            )
        }
    }

    /// Placeholder for future vision operations
    pub async fn placeholder_operation(&self) -> Result<String, LlmError> {
        // No automatic warnings - let the user decide if they want to check support
        Err(LlmError::UnsupportedOperation(
            "Vision operations not yet implemented. Use provider-specific client.".to_string(),
        ))
    }
}

impl Default for SiumaiBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for SiumaiBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug_struct = f.debug_struct("SiumaiBuilder");

        debug_struct
            .field("provider_type", &self.provider_type)
            .field("provider_name", &self.provider_name)
            .field("base_url", &self.base_url)
            .field("model", &self.common_params.model)
            .field("temperature", &self.common_params.temperature)
            .field("max_tokens", &self.common_params.max_tokens)
            .field("top_p", &self.common_params.top_p)
            .field("seed", &self.common_params.seed)
            .field("capabilities_count", &self.capabilities.len())
            .field("reasoning_enabled", &self.reasoning_enabled)
            .field("reasoning_budget", &self.reasoning_budget)
            .field("has_tracing", &self.tracing_config.is_some())
            .field("timeout", &self.http_config.timeout);

        // Only show existence of sensitive fields, not their values
        if self.api_key.is_some() {
            debug_struct.field("has_api_key", &true);
        }
        if self.organization.is_some() {
            debug_struct.field("has_organization", &true);
        }
        if self.project.is_some() {
            debug_struct.field("has_project", &true);
        }

        debug_struct.finish()
    }
}

/// Provider registry for dynamic provider creation
pub struct ProviderRegistry {
    factories: HashMap<String, Box<dyn ProviderFactory>>,
}

/// Factory trait for creating providers
pub trait ProviderFactory: Send + Sync {
    fn create_provider(&self, config: ProviderConfig) -> Result<Box<dyn LlmClient>, LlmError>;
    fn supported_capabilities(&self) -> Vec<String>;
}

/// Configuration for provider creation
#[derive(Debug, Clone)]
pub struct ProviderConfig {
    pub api_key: String,
    pub base_url: Option<String>,
    pub model: Option<String>,
    pub capabilities: Vec<String>,
}

impl ProviderRegistry {
    /// Create a new registry
    pub fn new() -> Self {
        Self {
            factories: HashMap::new(),
        }
    }

    /// Register a provider factory
    pub fn register<S: Into<String>>(&mut self, name: S, factory: Box<dyn ProviderFactory>) {
        self.factories.insert(name.into(), factory);
    }

    /// Create a provider by name
    pub fn create_provider(&self, name: &str, config: ProviderConfig) -> Result<Siumai, LlmError> {
        let factory = self
            .factories
            .get(name)
            .ok_or_else(|| LlmError::ConfigurationError(format!("Unknown provider: {name}")))?;

        let client = factory.create_provider(config)?;
        Ok(Siumai::new(client))
    }

    /// Get supported providers
    pub fn supported_providers(&self) -> Vec<String> {
        self.factories.keys().cloned().collect()
    }
}

impl Default for ProviderRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    // Mock provider for testing that doesn't support embedding
    #[derive(Debug)]
    struct MockProvider;

    #[async_trait]
    impl ChatCapability for MockProvider {
        async fn chat_with_tools(
            &self,
            _messages: Vec<ChatMessage>,
            _tools: Option<Vec<Tool>>,
        ) -> Result<ChatResponse, LlmError> {
            Ok(ChatResponse {
                id: Some("mock-123".to_string()),
                content: MessageContent::Text("Mock response".to_string()),
                model: Some("mock-model".to_string()),
                usage: None,
                finish_reason: Some(FinishReason::Stop),
                tool_calls: None,
                thinking: None,
                metadata: std::collections::HashMap::new(),
            })
        }

        async fn chat_stream(
            &self,
            _messages: Vec<ChatMessage>,
            _tools: Option<Vec<Tool>>,
        ) -> Result<ChatStream, LlmError> {
            Err(LlmError::UnsupportedOperation(
                "Streaming not supported in mock".to_string(),
            ))
        }
    }

    impl LlmClient for MockProvider {
        fn provider_name(&self) -> &'static str {
            "mock"
        }

        fn supported_models(&self) -> Vec<String> {
            vec!["mock-model".to_string()]
        }

        fn capabilities(&self) -> ProviderCapabilities {
            ProviderCapabilities::new().with_chat()
            // Note: not adding .with_embedding() to test unsupported case
        }

        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn clone_box(&self) -> Box<dyn LlmClient> {
            Box::new(MockProvider)
        }
    }

    #[tokio::test]
    async fn test_siumai_embedding_unsupported_provider() {
        // Create a mock provider that doesn't support embedding
        let mock_provider = MockProvider;
        let siumai = Siumai::new(Box::new(mock_provider));

        // Test that embedding returns an error for unsupported provider
        let result = siumai.embed(vec!["test".to_string()]).await;
        assert!(result.is_err());

        if let Err(LlmError::UnsupportedOperation(msg)) = result {
            assert!(msg.contains("does not support embedding functionality"));
        } else {
            panic!("Expected UnsupportedOperation error");
        }
    }

    #[test]
    fn test_embedding_capability_proxy() {
        let mock_provider = MockProvider;
        let siumai = Siumai::new(Box::new(mock_provider));

        let proxy = siumai.embedding_capability();
        assert_eq!(proxy.provider_name(), "custom"); // MockProvider gets mapped to "custom" type
        assert!(!proxy.is_reported_as_supported()); // Mock provider doesn't report embedding support
    }

    #[tokio::test]
    async fn test_embedding_capability_proxy_embed() {
        let mock_provider = MockProvider;
        let siumai = Siumai::new(Box::new(mock_provider));

        let proxy = siumai.embedding_capability();
        let result = proxy.embed(vec!["test".to_string()]).await;
        assert!(result.is_err());

        if let Err(LlmError::UnsupportedOperation(msg)) = result {
            assert!(msg.contains("does not support embedding functionality"));
        } else {
            panic!("Expected UnsupportedOperation error");
        }
    }

    #[tokio::test]
    async fn test_ollama_build_without_api_key() {
        // Test that Ollama can be built without API key
        let result = SiumaiBuilder::new()
            .ollama()
            .model("llama3.2")
            .build()
            .await;

        // This should not fail due to missing API key
        // Note: It might fail for other reasons (like Ollama not running), but not API key
        match result {
            Ok(_) => {
                // Success - Ollama client was created without API key
            }
            Err(LlmError::ConfigurationError(msg)) => {
                // Should not be an API key error
                assert!(
                    !msg.contains("API key not specified"),
                    "Ollama should not require API key, but got: {}",
                    msg
                );
            }
            Err(_) => {
                // Other errors are acceptable (e.g., network issues)
            }
        }
    }

    #[tokio::test]
    async fn test_openai_requires_api_key() {
        // Test that OpenAI still requires API key
        let result = SiumaiBuilder::new().openai().model("gpt-4o").build().await;

        // This should fail due to missing API key
        assert!(result.is_err());
        if let Err(LlmError::ConfigurationError(msg)) = result {
            assert!(msg.contains("API key not specified"));
        } else {
            panic!("Expected ConfigurationError for missing API key");
        }
    }
}