llm-connector 0.3.7

Minimal Rust library for LLM protocol abstraction. Supports 4 protocols (OpenAI, Anthropic, Aliyun, Ollama) with unified interface, and dynamic model discovery.
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
//! Aliyun Protocol Implementation
//!
//! This module implements the Aliyun DashScope API protocol.
//!
//! # Supported Providers
//!
//! - **Aliyun (DashScope)** - `qwen()` - Qwen-Max, Qwen-Plus, Qwen-Turbo
//!
//! # Protocol Differences
//!
//! Aliyun uses a custom protocol that differs significantly from both OpenAI and Anthropic:
//!
//! ## 1. Endpoint
//! - Aliyun: `POST /services/aigc/text-generation/generation`
//! - OpenAI: `POST /v1/chat/completions`
//!
//! ## 2. Request Structure
//! - **Nested structure**: Uses `input` and `parameters` objects
//! - **Model field**: At top level, not in parameters
//! - **Result format**: Explicit `result_format` field for response type
//!
//! ## 3. Response Structure
//! - **Nested output**: Response data in `output.choices` instead of top-level `choices`
//! - **Request ID**: Includes `request_id` for tracking
//! - **Usage**: Different field structure
//!
//! ## 4. Authentication
//! - Uses `Authorization: Bearer <api-key>` header
//! - API key format: `sk-...`
//!
//! # Request Format
//!
//! ```json
//! {
//!   "model": "qwen-max",
//!   "input": {
//!     "messages": [
//!       {"role": "user", "content": "Hello"}
//!     ]
//!   },
//!   "parameters": {
//!     "max_tokens": 1000,
//!     "temperature": 0.7,
//!     "result_format": "message"
//!   }
//! }
//! ```
//!
//! # Response Format
//!
//! ```json
//! {
//!   "request_id": "req_123",
//!   "output": {
//!     "choices": [{
//!       "message": {
//!         "role": "assistant",
//!         "content": "Hello! How can I help you?"
//!       },
//!       "finish_reason": "stop"
//!     }]
//!   },
//!   "usage": {
//!     "input_tokens": 10,
//!     "output_tokens": 20,
//!     "total_tokens": 30
//!   }
//! }
//! ```
//!
//! # Example
//!
//! ```rust
//! use llm_connector::{LlmClient};
//! use llm_connector::types::{ChatRequest, Message};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create Aliyun client (DashScope)
//! let client = LlmClient::aliyun("your-api-key");
//!
//! // Create request
//! let request = ChatRequest {
//!     model: "qwen-max".to_string(),
//!     messages: vec![Message::user("Hello!")],
//!     ..Default::default()
//! };
//!
//! // Send request
//! let response = client.chat(&request).await?;
//! println!("Response: {}", response.choices[0].message.content);
//! # Ok(())
//! # }
//! ```

use crate::core::Provider;
use crate::error::LlmConnectorError;
use crate::types::{ChatRequest as Request, ChatResponse as Response, Role, Usage};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;

/// Parse a role string into a Role enum
fn parse_role(role: &str) -> Role {
    match role {
        "system" => Role::System,
        "user" => Role::User,
        "assistant" => Role::Assistant,
        "tool" => Role::Tool,
        _ => Role::User, // Default to user for unknown roles
    }
}

#[cfg(feature = "streaming")]
use crate::types::{StreamingResponse, ChatStream};

// ============================================================================
// Aliyun-specific Request Structures
// ============================================================================

#[derive(Debug, Serialize)]
pub struct AliyunRequest {
    model: String,
    input: AliyunInput,
    #[serde(skip_serializing_if = "Option::is_none")]
    parameters: Option<AliyunParameters>,
}

#[derive(Debug, Serialize)]
pub struct AliyunInput {
    messages: Vec<AliyunMessage>,
}

#[derive(Debug, Serialize)]
pub struct AliyunMessage {
    role: String,
    content: String,
}

#[derive(Debug, Serialize, Default)]
pub struct AliyunParameters {
    #[serde(skip_serializing_if = "Option::is_none")]
    max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    seed: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    result_format: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    incremental_output: Option<bool>,
}

// ============================================================================
// Aliyun-specific Response Structures
// ============================================================================

#[derive(Debug, Deserialize)]
pub struct AliyunResponse {
    request_id: String,
    output: AliyunOutput,
    usage: AliyunUsage,
}

#[derive(Debug, Deserialize)]
pub struct AliyunOutput {
    choices: Vec<AliyunChoice>,
}

#[derive(Debug, Deserialize)]
pub struct AliyunChoice {
    message: AliyunResponseMessage,
    finish_reason: String,
}

#[derive(Debug, Deserialize)]
pub struct AliyunResponseMessage {
    role: String,
    content: String,
}

#[derive(Debug, Deserialize)]
pub struct AliyunUsage {
    input_tokens: i32,
    output_tokens: i32,
}

// ============================================================================
// Aliyun-specific Streaming Response
// ============================================================================

#[cfg(feature = "streaming")]
#[derive(Debug, Deserialize)]
pub struct AliyunStreamResponse {
    request_id: String,
    output: AliyunStreamOutput,
    #[serde(skip_serializing_if = "Option::is_none")]
    usage: Option<AliyunUsage>,
}

#[cfg(feature = "streaming")]
#[derive(Debug, Deserialize)]
pub struct AliyunStreamOutput {
    choices: Vec<AliyunStreamChoice>,
}

#[cfg(feature = "streaming")]
#[derive(Debug, Deserialize)]
pub struct AliyunStreamChoice {
    message: AliyunResponseMessage,
    finish_reason: Option<String>,
}

// ============================================================================
// Legacy Error Mapper (to be removed after migration)
// ============================================================================

#[deprecated(note = "Error mapping is now handled directly in AliyunProvider")]
pub struct AliyunErrorMapper;

// ============================================================================
// Aliyun Adapter Implementation
// ============================================================================

/// Aliyun Provider for DashScope API
///
/// Direct implementation of the Provider trait for Aliyun's custom API.
#[derive(Debug, Clone)]
pub struct AliyunProvider {
    name: Arc<str>,
    base_url: Arc<str>,
    api_key: Arc<str>,
    client: reqwest::Client,
}

impl AliyunProvider {
    /// Create new Aliyun provider with API key and default base URL
    pub fn new(api_key: &str) -> Self {
        Self {
            name: Arc::from("aliyun"),
            base_url: Arc::from("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"),
            api_key: Arc::from(api_key),
            client: reqwest::Client::new(),
        }
    }

    /// Create new Aliyun provider with API key and custom base URL
    pub fn with_url(api_key: &str, base_url: &str) -> Self {
        Self {
            name: Arc::from("aliyun"),
            base_url: Arc::from(base_url),
            api_key: Arc::from(api_key),
            client: reqwest::Client::new(),
        }
    }

    /// Send HTTP POST request to Aliyun API
    async fn post_request<T: Serialize, R: serde::de::DeserializeOwned>(
        &self,
        request_body: &T,
    ) -> Result<R, LlmConnectorError> {
        let response = self
            .client
            .post(&*self.base_url)
            .header("Authorization", format!("Bearer {}", &self.api_key))
            .header("Content-Type", "application/json")
            .json(request_body)
            .send()
            .await
            .map_err(LlmConnectorError::from)?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body: Value = response.json().await.unwrap_or_default();
            return Err(self.map_http_error(status, body));
        }

        let text = response
            .text()
            .await
            .map_err(|e| LlmConnectorError::ParseError(e.to_string()))?;

        serde_json::from_str::<R>(&text)
            .map_err(|e| LlmConnectorError::ParseError(e.to_string()))
    }

    /// Map HTTP errors to LlmConnectorError
    fn map_http_error(&self, status: u16, body: Value) -> LlmConnectorError {
        let error_message = body["error"]["message"]
            .as_str()
            .or_else(|| body["message"].as_str())
            .unwrap_or("Unknown Aliyun error");

        let error_code = body["error"]["code"]
            .as_str()
            .or_else(|| body["code"].as_str())
            .unwrap_or("unknown");

        match status {
            400 => LlmConnectorError::InvalidRequest(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            401 => LlmConnectorError::AuthenticationError(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            403 => LlmConnectorError::PermissionError(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            429 => LlmConnectorError::RateLimitError(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            500..=599 => LlmConnectorError::ServerError(format!(
                "Aliyun HTTP {}: {} ({})",
                status, error_message, error_code
            )),
            _ => LlmConnectorError::ProviderError(format!(
                "Aliyun HTTP {}: {} ({})",
                status, error_message, error_code
            )),
        }
    }

    /// Build Aliyun-specific request from generic request
    fn build_request(&self, request: &Request, stream: bool) -> AliyunRequest {
        let messages = request
            .messages
            .iter()
            .map(|msg| AliyunMessage {
                role: match msg.role {
                    Role::System => "system".to_string(),
                    Role::User => "user".to_string(),
                    Role::Assistant => "assistant".to_string(),
                    Role::Tool => "tool".to_string(),
                },
                content: msg.content.clone(),
            })
            .collect();

        let parameters = AliyunParameters {
            max_tokens: request.max_tokens,
            temperature: request.temperature,
            top_p: request.top_p,
            seed: None, // Aliyun-specific field, could be configurable
            result_format: Some("message".to_string()),
            incremental_output: if stream { Some(true) } else { None },
        };

        AliyunRequest {
            model: request.model.clone(),
            input: AliyunInput { messages },
            parameters: Some(parameters),
        }
    }

    /// Parse Aliyun response to generic response
    fn parse_response(&self, response: AliyunResponse) -> Response {
        // Convenience: capture first choice content before moving choices
        let first_content = response
            .output
            .choices
            .get(0)
            .map(|c| c.message.content.clone())
            .unwrap_or_default();

        Response {
            id: response.request_id,
            object: "chat.completion".to_string(),
            created: chrono::Utc::now().timestamp() as u64,
            model: "qwen".to_string(), // Aliyun doesn't return model in response
            choices: response
                .output
                .choices
                .into_iter()
                .enumerate()
                .map(|(index, choice)| crate::types::Choice {
                    index: index as u32,
                    message: crate::types::Message {
                        role: parse_role(&choice.message.role),
                        content: choice.message.content,
                        name: None,
                        tool_calls: None,
                        tool_call_id: None,
                        ..Default::default()
                    },
                    finish_reason: Some(choice.finish_reason),
                    logprobs: None,
                })
                .collect(),
            content: first_content,
            usage: Some(Usage {
                prompt_tokens: response.usage.input_tokens as u32,
                completion_tokens: response.usage.output_tokens as u32,
                total_tokens: (response.usage.input_tokens + response.usage.output_tokens) as u32,
                prompt_cache_hit_tokens: None,
                prompt_cache_miss_tokens: None,
                prompt_tokens_details: None,
                completion_tokens_details: None,
            }),
            system_fingerprint: None,
        }
    }

    #[cfg(feature = "streaming")]
    fn parse_stream_response(&self, response: AliyunStreamResponse) -> StreamingResponse {
        // Convenience: capture first chunk content before moving choices
        let first_chunk_content = response
            .output
            .choices
            .get(0)
            .map(|c| c.message.content.clone())
            .unwrap_or_default();

        StreamingResponse {
            id: response.request_id,
            object: "chat.completion.chunk".to_string(),
            created: chrono::Utc::now().timestamp() as u64,
            model: "qwen".to_string(),
            choices: response
                .output
                .choices
                .into_iter()
                .enumerate()
                .map(|(index, choice)| crate::types::StreamingChoice {
                    index: index as u32,
                    delta: crate::types::Delta {
                        role: Some(parse_role(&choice.message.role)),
                        content: Some(choice.message.content),
                        tool_calls: None,
                        reasoning_content: None,
                        ..Default::default()
                    },
                    finish_reason: choice.finish_reason,
                    logprobs: None,
                })
                .collect(),
            content: first_chunk_content,
            reasoning_content: None,
            usage: response.usage.map(|usage| Usage {
                prompt_tokens: usage.input_tokens as u32,
                completion_tokens: usage.output_tokens as u32,
                total_tokens: (usage.input_tokens + usage.output_tokens) as u32,
                prompt_cache_hit_tokens: None,
                prompt_cache_miss_tokens: None,
                prompt_tokens_details: None,
                completion_tokens_details: None,
            }),
            system_fingerprint: None,
        }
    }
}

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

#[async_trait]
impl Provider for AliyunProvider {
    fn name(&self) -> &str {
        &self.name
    }

    async fn chat(&self, request: &Request) -> Result<Response, LlmConnectorError> {
        let ali_request = self.build_request(request, false);
        let ali_response = self.post_request::<AliyunRequest, AliyunResponse>(&ali_request).await?;

        Ok(self.parse_response(ali_response))
    }

    #[cfg(feature = "streaming")]
    async fn chat_stream(&self, request: &Request) -> Result<ChatStream, LlmConnectorError> {
        use futures_util::stream;

        let ali_request = self.build_request(request, true);
        let ali_response = self.post_request::<AliyunRequest, AliyunStreamResponse>(&ali_request).await?;

        let streaming_response = self.parse_stream_response(ali_response);

        // Convert single response to a stream with one chunk
        let single_chunk_stream = stream::once(async { Ok(streaming_response) });
        Ok(Box::pin(single_chunk_stream))
    }

    async fn fetch_models(&self) -> Result<Vec<String>, LlmConnectorError> {
        // Aliyun doesn't have a public models endpoint
        Err(LlmConnectorError::UnsupportedOperation(
            "Aliyun does not support model listing".to_string()
        ))
    }

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

// ============================================================================
// Legacy Compatibility (to be removed after migration)
// ============================================================================

// ============================================================================
// Legacy Compatibility Layer (to be removed after migration)
// ============================================================================

use crate::protocols::{ProviderAdapter, ErrorMapper};

/// Legacy AliyunProtocol for backward compatibility
#[deprecated(note = "Use AliyunProvider instead")]
#[derive(Debug, Clone)]
pub struct AliyunProtocol {
    base_url: Arc<str>,
}

#[allow(deprecated)]
impl AliyunProtocol {
    /// Create new Aliyun protocol with API key
    pub fn new(_api_key: &str) -> Self {
        Self {
            base_url: Arc::from("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"),
        }
    }

    /// Create new Aliyun protocol with custom API key and base URL
    pub fn with_url(_api_key: &str, base_url: &str) -> Self {
        Self {
            base_url: Arc::from(base_url),
        }
    }
}

#[allow(deprecated)]
#[async_trait]
impl ProviderAdapter for AliyunProtocol {
    type RequestType = AliyunRequest;
    type ResponseType = AliyunResponse;
    #[cfg(feature = "streaming")]
    type StreamResponseType = AliyunStreamResponse;
    type ErrorMapperType = AliyunErrorMapper;

    fn name(&self) -> &str {
        "aliyun"
    }

    fn endpoint_url(&self, base_url: &Option<String>) -> String {
        base_url.as_deref().unwrap_or(&self.base_url).to_string()
    }

    fn models_endpoint_url(&self, _base_url: &Option<String>) -> Option<String> {
        None // Aliyun doesn't have models endpoint
    }

    fn build_request_data(&self, request: &crate::types::ChatRequest, stream: bool) -> Self::RequestType {
        let messages = request
            .messages
            .iter()
            .map(|msg| AliyunMessage {
                role: match msg.role {
                    crate::types::Role::System => "system".to_string(),
                    crate::types::Role::User => "user".to_string(),
                    crate::types::Role::Assistant => "assistant".to_string(),
                    crate::types::Role::Tool => "tool".to_string(),
                },
                content: msg.content.clone(),
            })
            .collect();

        let parameters = AliyunParameters {
            max_tokens: request.max_tokens,
            temperature: request.temperature,
            top_p: request.top_p,
            seed: None,
            result_format: Some("message".to_string()),
            incremental_output: if stream { Some(true) } else { None },
        };

        AliyunRequest {
            model: request.model.clone(),
            input: AliyunInput { messages },
            parameters: Some(parameters),
        }
    }

    fn parse_response_data(&self, response: Self::ResponseType) -> crate::types::ChatResponse {
        let first_content = response
            .output
            .choices
            .get(0)
            .map(|c| c.message.content.clone())
            .unwrap_or_default();

        crate::types::ChatResponse {
            id: response.request_id,
            object: "chat.completion".to_string(),
            created: chrono::Utc::now().timestamp() as u64,
            model: "qwen".to_string(),
            choices: response
                .output
                .choices
                .into_iter()
                .enumerate()
                .map(|(index, choice)| crate::types::Choice {
                    index: index as u32,
                    message: crate::types::Message {
                        role: parse_role(&choice.message.role),
                        content: choice.message.content,
                        name: None,
                        tool_calls: None,
                        tool_call_id: None,
                        ..Default::default()
                    },
                    finish_reason: Some(choice.finish_reason),
                    logprobs: None,
                })
                .collect(),
            content: first_content,
            usage: Some(Usage {
                prompt_tokens: response.usage.input_tokens as u32,
                completion_tokens: response.usage.output_tokens as u32,
                total_tokens: (response.usage.input_tokens + response.usage.output_tokens) as u32,
                prompt_cache_hit_tokens: None,
                prompt_cache_miss_tokens: None,
                prompt_tokens_details: None,
                completion_tokens_details: None,
            }),
            system_fingerprint: None,
        }
    }

    #[cfg(feature = "streaming")]
    fn parse_stream_response_data(&self, response: Self::StreamResponseType) -> crate::types::StreamingResponse {
        let first_chunk_content = response
            .output
            .choices
            .get(0)
            .map(|c| c.message.content.clone())
            .unwrap_or_default();

        crate::types::StreamingResponse {
            id: response.request_id,
            object: "chat.completion.chunk".to_string(),
            created: chrono::Utc::now().timestamp() as u64,
            model: "qwen".to_string(),
            choices: response
                .output
                .choices
                .into_iter()
                .enumerate()
                .map(|(index, choice)| crate::types::StreamingChoice {
                    index: index as u32,
                    delta: crate::types::Delta {
                        role: Some(parse_role(&choice.message.role)),
                        content: Some(choice.message.content),
                        tool_calls: None,
                        reasoning_content: None,
                        ..Default::default()
                    },
                    finish_reason: choice.finish_reason,
                    logprobs: None,
                })
                .collect(),
            content: first_chunk_content,
            reasoning_content: None,
            usage: response.usage.map(|usage| Usage {
                prompt_tokens: usage.input_tokens as u32,
                completion_tokens: usage.output_tokens as u32,
                total_tokens: (usage.input_tokens + usage.output_tokens) as u32,
                prompt_cache_hit_tokens: None,
                prompt_cache_miss_tokens: None,
                prompt_tokens_details: None,
                completion_tokens_details: None,
            }),
            system_fingerprint: None,
        }
    }
}

#[allow(deprecated)]
impl ErrorMapper for AliyunErrorMapper {
    fn map_http_error(status: u16, body: Value) -> LlmConnectorError {
        let error_message = body["error"]["message"]
            .as_str()
            .or_else(|| body["message"].as_str())
            .unwrap_or("Unknown Aliyun error");

        let error_code = body["error"]["code"]
            .as_str()
            .or_else(|| body["code"].as_str())
            .unwrap_or("unknown");

        match status {
            400 => LlmConnectorError::InvalidRequest(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            401 => LlmConnectorError::AuthenticationError(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            403 => LlmConnectorError::PermissionError(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            429 => LlmConnectorError::RateLimitError(format!(
                "Aliyun: {} ({})",
                error_message, error_code
            )),
            500..=599 => LlmConnectorError::ServerError(format!(
                "Aliyun HTTP {}: {} ({})",
                status, error_message, error_code
            )),
            _ => LlmConnectorError::ProviderError(format!(
                "Aliyun HTTP {}: {} ({})",
                status, error_message, error_code
            )),
        }
    }

    fn map_network_error(error: reqwest::Error) -> LlmConnectorError {
        if error.is_timeout() {
            LlmConnectorError::TimeoutError(format!("Aliyun: {}", error))
        } else if error.is_connect() {
            LlmConnectorError::ConnectionError(format!("Aliyun: {}", error))
        } else {
            LlmConnectorError::NetworkError(format!("Aliyun: {}", error))
        }
    }

    fn is_retriable_error(error: &LlmConnectorError) -> bool {
        matches!(
            error,
            LlmConnectorError::RateLimitError(_)
                | LlmConnectorError::ServerError(_)
                | LlmConnectorError::TimeoutError(_)
                | LlmConnectorError::ConnectionError(_)
        )
    }
}

// ============================================================================
// Convenience Functions and Type Aliases
// ============================================================================

/// Create an Aliyun provider
pub fn aliyun(api_key: &str) -> AliyunProvider {
    AliyunProvider::new(api_key)
}

/// Create an Aliyun provider with custom base URL
pub fn aliyun_with_url(api_key: &str, base_url: &str) -> AliyunProvider {
    AliyunProvider::with_url(api_key, base_url)
}

/// Bridge implementation: Implement old Provider trait for AliyunProvider
/// This allows gradual migration from the old architecture to the new one
#[async_trait]
impl crate::protocols::Provider for AliyunProvider {
    fn name(&self) -> &str {
        &self.name
    }

    async fn chat(&self, request: &crate::types::ChatRequest) -> Result<crate::types::ChatResponse, LlmConnectorError> {
        Provider::chat(self, request).await
    }

    #[cfg(feature = "streaming")]
    async fn chat_stream(&self, request: &crate::types::ChatRequest) -> Result<crate::types::ChatStream, LlmConnectorError> {
        Provider::chat_stream(self, request).await
    }

    async fn fetch_models(&self) -> Result<Vec<String>, LlmConnectorError> {
        Provider::fetch_models(self).await
    }

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