mofa-foundation 0.1.1

MoFA Foundation - Core building blocks and utilities
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
//! OpenAI Provider Implementation
//!
//! 使用 `async-openai` crate 实现 OpenAI API 交互
//!
//! # 支持的服务
//!
//! - OpenAI API (api.openai.com)
//! - Azure OpenAI
//! - 兼容 OpenAI API 的本地服务 (Ollama, vLLM, LocalAI 等)
//!
//! # 示例
//!
//! ```rust,ignore
//! use mofa_foundation::llm::openai::{OpenAIProvider, OpenAIConfig};
//!
//! // 使用 OpenAI
//! let provider = OpenAIProvider::new("sk-xxx");
//!
//! // 使用自定义 endpoint
//! let provider = OpenAIProvider::with_config(
//!     OpenAIConfig::new("sk-xxx")
//!         .with_base_url("http://localhost:11434/v1")
//!         .with_model("llama2")
//! );
//!
//! // 使用 Azure OpenAI
//! let provider = OpenAIProvider::azure("https://xxx.openai.azure.com", "api-key", "deployment");
//! ```

use super::provider::{ChatStream, LLMProvider, ModelCapabilities, ModelInfo};
use super::types::*;
use async_openai::{
    Client,
    config::OpenAIConfig as AsyncOpenAIConfig,
    types::{
        ChatCompletionRequestAssistantMessageArgs, ChatCompletionRequestMessage,
        ChatCompletionRequestMessageContentPartAudio, ChatCompletionRequestMessageContentPartImage,
        ChatCompletionRequestMessageContentPartText, ChatCompletionRequestSystemMessageArgs,
        ChatCompletionRequestToolMessageArgs, ChatCompletionRequestUserMessageArgs,
        ChatCompletionRequestUserMessageContent, ChatCompletionRequestUserMessageContentPart,
        ChatCompletionToolArgs, ChatCompletionToolChoiceOption, ChatCompletionToolType,
        CreateChatCompletionRequestArgs, FunctionObjectArgs, ImageDetail as OpenAIImageDetail,
        ImageUrl as OpenAIImageUrl, InputAudio, InputAudioFormat,
    },
};
use async_trait::async_trait;
use futures::StreamExt;

/// OpenAI Provider 配置
#[derive(Debug, Clone)]
pub struct OpenAIConfig {
    /// API Key
    pub api_key: String,
    /// API 基础 URL
    pub base_url: Option<String>,
    /// 组织 ID
    pub org_id: Option<String>,
    /// 默认模型
    pub default_model: String,
    /// 默认温度
    pub default_temperature: f32,
    /// 默认最大 token 数
    pub default_max_tokens: u32,
    /// 请求超时(秒)
    pub timeout_secs: u64,
}

impl Default for OpenAIConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            base_url: None,
            org_id: None,
            default_model: "gpt-4o".to_string(),
            default_temperature: 0.7,
            default_max_tokens: 4096,
            timeout_secs: 60,
        }
    }
}

impl OpenAIConfig {
    /// 创建新配置
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Default::default()
        }
    }

    /// 从环境变量创建配置
    pub fn from_env() -> Self {
        Self {
            api_key: std::env::var("OPENAI_API_KEY").unwrap_or_default(),
            base_url: std::env::var("OPENAI_BASE_URL").ok(),
            default_model: std::env::var("OPENAI_MODEL").unwrap_or_default(),
            ..Default::default()
        }
    }

    /// 设置 base URL
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// 设置默认模型
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.default_model = model.into();
        self
    }

    /// 设置默认温度
    pub fn with_temperature(mut self, temp: f32) -> Self {
        self.default_temperature = temp;
        self
    }

    /// 设置默认最大 token 数
    pub fn with_max_tokens(mut self, tokens: u32) -> Self {
        self.default_max_tokens = tokens;
        self
    }

    /// 设置组织 ID
    pub fn with_org_id(mut self, org_id: impl Into<String>) -> Self {
        self.org_id = Some(org_id.into());
        self
    }

    /// 设置超时
    pub fn with_timeout(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }
}

/// OpenAI LLM Provider
///
/// 支持 OpenAI API 及兼容服务
pub struct OpenAIProvider {
    client: Client<AsyncOpenAIConfig>,
    config: OpenAIConfig,
}

impl OpenAIProvider {
    /// 使用 API Key 创建 Provider
    pub fn new(api_key: impl Into<String>) -> Self {
        let config = OpenAIConfig::new(api_key);
        Self::with_config(config)
    }

    /// 从环境变量创建 Provider
    pub fn from_env() -> Self {
        Self::with_config(OpenAIConfig::from_env())
    }

    /// 使用配置创建 Provider
    pub fn with_config(config: OpenAIConfig) -> Self {
        let mut openai_config = AsyncOpenAIConfig::new().with_api_key(&config.api_key);

        if let Some(ref base_url) = config.base_url {
            openai_config = openai_config.with_api_base(base_url);
        }

        if let Some(ref org_id) = config.org_id {
            openai_config = openai_config.with_org_id(org_id);
        }

        let client = Client::with_config(openai_config);

        Self { client, config }
    }

    /// 创建 Azure OpenAI Provider
    pub fn azure(
        endpoint: impl Into<String>,
        api_key: impl Into<String>,
        deployment: impl Into<String>,
    ) -> Self {
        let endpoint = endpoint.into();
        let deployment = deployment.into();

        // Azure OpenAI 使用不同的 URL 格式
        let base_url = format!(
            "{}/openai/deployments/{}",
            endpoint.trim_end_matches('/'),
            deployment
        );

        let config = OpenAIConfig::new(api_key)
            .with_base_url(base_url)
            .with_model(deployment);

        Self::with_config(config)
    }

    /// 创建兼容 OpenAI API 的本地服务 Provider
    pub fn local(base_url: impl Into<String>, model: impl Into<String>) -> Self {
        let config = OpenAIConfig::new("not-needed")
            .with_base_url(base_url)
            .with_model(model);

        Self::with_config(config)
    }

    /// 获取底层 async-openai 客户端
    pub fn client(&self) -> &Client<AsyncOpenAIConfig> {
        &self.client
    }

    /// 获取配置
    pub fn config(&self) -> &OpenAIConfig {
        &self.config
    }

    /// 转换消息格式
    fn convert_messages(
        messages: &[ChatMessage],
    ) -> Result<Vec<ChatCompletionRequestMessage>, LLMError> {
        messages.iter().map(Self::convert_message).collect()
    }

    /// 转换单个消息
    fn convert_message(msg: &ChatMessage) -> Result<ChatCompletionRequestMessage, LLMError> {
        let text_only_content = msg
            .content
            .as_ref()
            .map(|c| match c {
                MessageContent::Text(s) => s.clone(),
                MessageContent::Parts(parts) => parts
                    .iter()
                    .filter_map(|p| match p {
                        ContentPart::Text { text } => Some(text.clone()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n"),
            })
            .unwrap_or_default();

        match msg.role {
            Role::System => Ok(ChatCompletionRequestSystemMessageArgs::default()
                .content(text_only_content)
                .build()
                .map_err(|e| LLMError::Other(e.to_string()))?
                .into()),
            Role::User => {
                let content = match msg.content.as_ref() {
                    Some(MessageContent::Text(s)) => {
                        ChatCompletionRequestUserMessageContent::Text(s.clone())
                    }
                    Some(MessageContent::Parts(parts)) => {
                        let mut out = Vec::new();
                        for part in parts {
                            match part {
                                ContentPart::Text { text } => {
                                    out.push(ChatCompletionRequestUserMessageContentPart::Text(
                                        ChatCompletionRequestMessageContentPartText {
                                            text: text.clone(),
                                        },
                                    ));
                                }
                                ContentPart::Image { image_url } => {
                                    let detail = image_url.detail.as_ref().map(|d| match d {
                                        ImageDetail::Auto => OpenAIImageDetail::Auto,
                                        ImageDetail::Low => OpenAIImageDetail::Low,
                                        ImageDetail::High => OpenAIImageDetail::High,
                                    });
                                    let image_part = ChatCompletionRequestMessageContentPartImage {
                                        image_url: OpenAIImageUrl {
                                            url: image_url.url.clone(),
                                            detail,
                                        },
                                    };
                                    out.push(
                                        ChatCompletionRequestUserMessageContentPart::ImageUrl(
                                            image_part,
                                        ),
                                    );
                                }
                                ContentPart::Audio { audio } => {
                                    let format = match audio.format.to_lowercase().as_str() {
                                        "wav" => InputAudioFormat::Wav,
                                        _ => InputAudioFormat::Mp3,
                                    };
                                    let audio_part = ChatCompletionRequestMessageContentPartAudio {
                                        input_audio: InputAudio {
                                            data: audio.data.clone(),
                                            format,
                                        },
                                    };
                                    out.push(
                                        ChatCompletionRequestUserMessageContentPart::InputAudio(
                                            audio_part,
                                        ),
                                    );
                                }
                            }
                        }
                        ChatCompletionRequestUserMessageContent::Array(out)
                    }
                    None => ChatCompletionRequestUserMessageContent::Text(String::new()),
                };

                Ok(ChatCompletionRequestUserMessageArgs::default()
                    .content(content)
                    .build()
                    .map_err(|e| LLMError::Other(e.to_string()))?
                    .into())
            }
            Role::Assistant => {
                let mut builder = ChatCompletionRequestAssistantMessageArgs::default();
                if !text_only_content.is_empty() {
                    builder.content(text_only_content);
                }

                // 处理工具调用
                if let Some(ref tool_calls) = msg.tool_calls {
                    let converted_calls: Vec<_> = tool_calls
                        .iter()
                        .map(|tc| async_openai::types::ChatCompletionMessageToolCall {
                            id: tc.id.clone(),
                            r#type: ChatCompletionToolType::Function,
                            function: async_openai::types::FunctionCall {
                                name: tc.function.name.clone(),
                                arguments: tc.function.arguments.clone(),
                            },
                        })
                        .collect();
                    builder.tool_calls(converted_calls);
                }

                Ok(builder
                    .build()
                    .map_err(|e| LLMError::Other(e.to_string()))?
                    .into())
            }
            Role::Tool => {
                let tool_call_id = msg
                    .tool_call_id
                    .clone()
                    .unwrap_or_else(|| "unknown".to_string());

                Ok(ChatCompletionRequestToolMessageArgs::default()
                    .tool_call_id(tool_call_id)
                    .content(text_only_content)
                    .build()
                    .map_err(|e| LLMError::Other(e.to_string()))?
                    .into())
            }
        }
    }

    /// 转换工具定义
    fn convert_tools(
        tools: &[Tool],
    ) -> Result<Vec<async_openai::types::ChatCompletionTool>, LLMError> {
        tools
            .iter()
            .map(|tool| {
                let function = FunctionObjectArgs::default()
                    .name(&tool.function.name)
                    .description(tool.function.description.clone().unwrap_or_default())
                    .parameters(
                        tool.function
                            .parameters
                            .clone()
                            .unwrap_or(serde_json::json!({})),
                    )
                    .build()
                    .map_err(|e| LLMError::Other(e.to_string()))?;

                ChatCompletionToolArgs::default()
                    .r#type(ChatCompletionToolType::Function)
                    .function(function)
                    .build()
                    .map_err(|e| LLMError::Other(e.to_string()))
            })
            .collect()
    }

    /// 转换响应
    fn convert_response(
        response: async_openai::types::CreateChatCompletionResponse,
    ) -> ChatCompletionResponse {
        let choices: Vec<Choice> = response
            .choices
            .into_iter()
            .map(|choice| {
                let message = Self::convert_response_message(choice.message);
                let finish_reason = choice.finish_reason.map(|r| match r {
                    async_openai::types::FinishReason::Stop => FinishReason::Stop,
                    async_openai::types::FinishReason::Length => FinishReason::Length,
                    async_openai::types::FinishReason::ToolCalls => FinishReason::ToolCalls,
                    async_openai::types::FinishReason::ContentFilter => FinishReason::ContentFilter,
                    async_openai::types::FinishReason::FunctionCall => FinishReason::ToolCalls,
                });

                Choice {
                    index: choice.index,
                    message,
                    finish_reason,
                    logprobs: None,
                }
            })
            .collect();

        let usage = response.usage.map(|u| Usage {
            prompt_tokens: u.prompt_tokens,
            completion_tokens: u.completion_tokens,
            total_tokens: u.total_tokens,
        });

        ChatCompletionResponse {
            id: response.id,
            object: response.object,
            created: response.created as u64,
            model: response.model,
            choices,
            usage,
            system_fingerprint: response.system_fingerprint,
        }
    }

    /// 转换响应消息
    fn convert_response_message(
        msg: async_openai::types::ChatCompletionResponseMessage,
    ) -> ChatMessage {
        let content = msg.content.map(MessageContent::Text);

        let tool_calls = msg.tool_calls.map(|calls| {
            calls
                .into_iter()
                .map(|tc| ToolCall {
                    id: tc.id,
                    call_type: "function".to_string(),
                    function: FunctionCall {
                        name: tc.function.name,
                        arguments: tc.function.arguments,
                    },
                })
                .collect()
        });

        ChatMessage {
            role: Role::Assistant,
            content,
            name: None,
            tool_calls,
            tool_call_id: None,
        }
    }
}

#[async_trait]
impl LLMProvider for OpenAIProvider {
    fn name(&self) -> &str {
        "openai"
    }

    fn default_model(&self) -> &str {
        &self.config.default_model
    }

    fn supported_models(&self) -> Vec<&str> {
        vec![
            "gpt-4o",
            "gpt-4o-mini",
            "gpt-4-turbo",
            "gpt-4",
            "gpt-3.5-turbo",
            "o1",
            "o1-mini",
            "o1-preview",
        ]
    }

    fn supports_streaming(&self) -> bool {
        true
    }

    fn supports_tools(&self) -> bool {
        true
    }

    fn supports_vision(&self) -> bool {
        true
    }

    fn supports_embedding(&self) -> bool {
        true
    }

    async fn chat(&self, request: ChatCompletionRequest) -> LLMResult<ChatCompletionResponse> {
        let messages = Self::convert_messages(&request.messages)?;

        let model = if request.model.is_empty() {
            self.config.default_model.clone()
        } else {
            request.model.clone()
        };

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

        // 设置可选参数
        if let Some(temp) = request.temperature {
            builder.temperature(temp);
        } else {
            builder.temperature(self.config.default_temperature);
        }

        if let Some(max_tokens) = request.max_tokens {
            builder.max_tokens(max_tokens);
        }

        if let Some(top_p) = request.top_p {
            builder.top_p(top_p);
        }

        if let Some(ref stop) = request.stop {
            builder.stop(stop.clone());
        }

        if let Some(freq_penalty) = request.frequency_penalty {
            builder.frequency_penalty(freq_penalty);
        }

        if let Some(pres_penalty) = request.presence_penalty {
            builder.presence_penalty(pres_penalty);
        }

        if let Some(ref user) = request.user {
            builder.user(user);
        }

        // 设置工具
        if let Some(ref tools) = request.tools
            && !tools.is_empty()
        {
            let converted_tools = Self::convert_tools(tools)?;
            builder.tools(converted_tools);

            // 设置 tool_choice
            if let Some(ref choice) = request.tool_choice {
                let tc = match choice {
                    ToolChoice::Auto => ChatCompletionToolChoiceOption::Auto,
                    ToolChoice::None => ChatCompletionToolChoiceOption::None,
                    ToolChoice::Required => ChatCompletionToolChoiceOption::Required,
                    ToolChoice::Specific { function, .. } => ChatCompletionToolChoiceOption::Named(
                        async_openai::types::ChatCompletionNamedToolChoice {
                            r#type: ChatCompletionToolType::Function,
                            function: async_openai::types::FunctionName {
                                name: function.name.clone(),
                            },
                        },
                    ),
                };
                builder.tool_choice(tc);
            }
        }

        // 设置响应格式
        if let Some(ref format) = request.response_format
            && format.format_type == "json_object"
        {
            builder.response_format(async_openai::types::ResponseFormat::JsonObject);
        }

        let openai_request = builder
            .build()
            .map_err(|e| LLMError::ConfigError(e.to_string()))?;

        let response = self
            .client
            .chat()
            .create(openai_request)
            .await
            .map_err(Self::convert_error)?;

        Ok(Self::convert_response(response))
    }

    async fn chat_stream(&self, request: ChatCompletionRequest) -> LLMResult<ChatStream> {
        let messages = Self::convert_messages(&request.messages)?;

        let model = if request.model.is_empty() {
            self.config.default_model.clone()
        } else {
            request.model.clone()
        };

        let mut builder = CreateChatCompletionRequestArgs::default();
        builder.model(&model).messages(messages).stream(true);

        if let Some(temp) = request.temperature {
            builder.temperature(temp);
        }

        if let Some(max_tokens) = request.max_tokens {
            builder.max_tokens(max_tokens);
        }

        // 设置工具
        if let Some(ref tools) = request.tools
            && !tools.is_empty()
        {
            let converted_tools = Self::convert_tools(tools)?;
            builder.tools(converted_tools);
        }

        let openai_request = builder
            .build()
            .map_err(|e| LLMError::ConfigError(e.to_string()))?;

        let stream = self
            .client
            .chat()
            .create_stream(openai_request)
            .await
            .map_err(Self::convert_error)?;

        // 转换流,过滤掉 UTF-8 错误(某些 OpenAI 兼容 API 可能返回无效的 UTF-8 数据)
        let converted_stream = stream
            .filter_map(|result| async move {
                match result {
                    Ok(chunk) => Some(Ok(Self::convert_chunk(chunk))),
                    Err(e) => {
                        let err_str = e.to_string();
                        // 过滤掉 UTF-8 错误,记录日志但继续处理流
                        if err_str.contains("stream did not contain valid UTF-8") || err_str.contains("utf8") {
                            tracing::warn!("Skipping invalid UTF-8 chunk from stream (may happen with some OpenAI-compatible APIs)");
                            None
                        } else {
                            Some(Err(Self::convert_error(e)))
                        }
                    }
                }
            });

        Ok(Box::pin(converted_stream))
    }

    async fn embedding(&self, request: EmbeddingRequest) -> LLMResult<EmbeddingResponse> {
        use async_openai::types::CreateEmbeddingRequestArgs;

        let input = match request.input {
            EmbeddingInput::Single(s) => vec![s],
            EmbeddingInput::Multiple(v) => v,
        };

        let openai_request = CreateEmbeddingRequestArgs::default()
            .model(&request.model)
            .input(input)
            .build()
            .map_err(|e| LLMError::ConfigError(e.to_string()))?;

        let response = self
            .client
            .embeddings()
            .create(openai_request)
            .await
            .map_err(Self::convert_error)?;

        let data: Vec<EmbeddingData> = response
            .data
            .into_iter()
            .map(|d| EmbeddingData {
                object: "embedding".to_string(),
                index: d.index,
                embedding: d.embedding,
            })
            .collect();

        Ok(EmbeddingResponse {
            object: "list".to_string(),
            model: response.model,
            data,
            usage: EmbeddingUsage {
                prompt_tokens: response.usage.prompt_tokens,
                total_tokens: response.usage.total_tokens,
            },
        })
    }

    async fn health_check(&self) -> LLMResult<bool> {
        // 发送一个简单请求来检查连接
        let request = ChatCompletionRequest::new(&self.config.default_model)
            .system("Say 'ok'")
            .max_tokens(5);

        match self.chat(request).await {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    async fn get_model_info(&self, model: &str) -> LLMResult<ModelInfo> {
        // OpenAI 没有公开的模型信息 API,返回预定义信息
        let info = match model {
            "gpt-4o" => ModelInfo {
                id: "gpt-4o".to_string(),
                name: "GPT-4o".to_string(),
                description: Some("Most capable GPT-4 model with vision".to_string()),
                context_window: Some(128000),
                max_output_tokens: Some(16384),
                training_cutoff: Some("2023-10".to_string()),
                capabilities: ModelCapabilities {
                    streaming: true,
                    tools: true,
                    vision: true,
                    json_mode: true,
                    json_schema: true,
                },
            },
            "gpt-4o-mini" => ModelInfo {
                id: "gpt-4o-mini".to_string(),
                name: "GPT-4o Mini".to_string(),
                description: Some("Smaller, faster GPT-4o".to_string()),
                context_window: Some(128000),
                max_output_tokens: Some(16384),
                training_cutoff: Some("2023-10".to_string()),
                capabilities: ModelCapabilities {
                    streaming: true,
                    tools: true,
                    vision: true,
                    json_mode: true,
                    json_schema: true,
                },
            },
            "gpt-4-turbo" => ModelInfo {
                id: "gpt-4-turbo".to_string(),
                name: "GPT-4 Turbo".to_string(),
                description: Some("GPT-4 Turbo with vision".to_string()),
                context_window: Some(128000),
                max_output_tokens: Some(4096),
                training_cutoff: Some("2023-12".to_string()),
                capabilities: ModelCapabilities {
                    streaming: true,
                    tools: true,
                    vision: true,
                    json_mode: true,
                    json_schema: false,
                },
            },
            "gpt-3.5-turbo" => ModelInfo {
                id: "gpt-3.5-turbo".to_string(),
                name: "GPT-3.5 Turbo".to_string(),
                description: Some("Fast and cost-effective".to_string()),
                context_window: Some(16385),
                max_output_tokens: Some(4096),
                training_cutoff: Some("2021-09".to_string()),
                capabilities: ModelCapabilities {
                    streaming: true,
                    tools: true,
                    vision: false,
                    json_mode: true,
                    json_schema: false,
                },
            },
            _ => ModelInfo {
                id: model.to_string(),
                name: model.to_string(),
                description: None,
                context_window: None,
                max_output_tokens: None,
                training_cutoff: None,
                capabilities: ModelCapabilities::default(),
            },
        };

        Ok(info)
    }
}

impl OpenAIProvider {
    /// 转换流式响应块
    fn convert_chunk(
        chunk: async_openai::types::CreateChatCompletionStreamResponse,
    ) -> ChatCompletionChunk {
        let choices: Vec<ChunkChoice> = chunk
            .choices
            .into_iter()
            .map(|choice| {
                let delta = ChunkDelta {
                    role: choice.delta.role.map(|_| Role::Assistant),
                    content: choice.delta.content,
                    tool_calls: choice.delta.tool_calls.map(|calls| {
                        calls
                            .into_iter()
                            .map(|tc| ToolCallDelta {
                                index: tc.index,
                                id: tc.id,
                                call_type: Some("function".to_string()),
                                function: tc.function.map(|f| FunctionCallDelta {
                                    name: f.name,
                                    arguments: f.arguments,
                                }),
                            })
                            .collect()
                    }),
                };

                let finish_reason = choice.finish_reason.map(|r| match r {
                    async_openai::types::FinishReason::Stop => FinishReason::Stop,
                    async_openai::types::FinishReason::Length => FinishReason::Length,
                    async_openai::types::FinishReason::ToolCalls => FinishReason::ToolCalls,
                    async_openai::types::FinishReason::ContentFilter => FinishReason::ContentFilter,
                    async_openai::types::FinishReason::FunctionCall => FinishReason::ToolCalls,
                });

                ChunkChoice {
                    index: choice.index,
                    delta,
                    finish_reason,
                }
            })
            .collect();

        ChatCompletionChunk {
            id: chunk.id,
            object: "chat.completion.chunk".to_string(),
            created: chunk.created as u64,
            model: chunk.model,
            choices,
            usage: chunk.usage.map(|u| Usage {
                prompt_tokens: u.prompt_tokens,
                completion_tokens: u.completion_tokens,
                total_tokens: u.total_tokens,
            }),
        }
    }

    /// 转换错误
    fn convert_error(err: async_openai::error::OpenAIError) -> LLMError {
        match err {
            async_openai::error::OpenAIError::ApiError(api_err) => {
                let code = api_err.code.clone();
                let message = api_err.message.clone();

                // 根据错误类型分类
                if message.contains("rate limit") {
                    LLMError::RateLimited(message)
                } else if message.contains("quota") || message.contains("billing") {
                    LLMError::QuotaExceeded(message)
                } else if message.contains("model") && message.contains("not found") {
                    LLMError::ModelNotFound(message)
                } else if message.contains("context") || message.contains("tokens") {
                    LLMError::ContextLengthExceeded(message)
                } else if message.contains("content") && message.contains("filter") {
                    LLMError::ContentFiltered(message)
                } else {
                    LLMError::ApiError { code, message }
                }
            }
            async_openai::error::OpenAIError::Reqwest(e) => {
                if e.is_timeout() {
                    LLMError::Timeout(e.to_string())
                } else {
                    LLMError::NetworkError(e.to_string())
                }
            }
            async_openai::error::OpenAIError::InvalidArgument(msg) => LLMError::ConfigError(msg),
            _ => LLMError::Other(err.to_string()),
        }
    }

    /// 快速创建 OpenAI Provider
    pub fn openai(api_key: impl Into<String>) -> OpenAIProvider {
        OpenAIProvider::new(api_key)
    }

    /// 快速创建兼容 OpenAI API 的本地 Provider
    pub fn openai_compatible(
        base_url: impl Into<String>,
        api_key: impl Into<String>,
        model: impl Into<String>,
    ) -> OpenAIProvider {
        let config = OpenAIConfig::new(api_key)
            .with_base_url(base_url)
            .with_model(model);
        OpenAIProvider::with_config(config)
    }
}

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

    #[test]
    fn test_config_builder() {
        let config = OpenAIConfig::new("sk-test")
            .with_base_url("http://localhost:8080")
            .with_model("gpt-4")
            .with_temperature(0.5)
            .with_max_tokens(2048);

        assert_eq!(config.api_key, "sk-test");
        assert_eq!(config.base_url, Some("http://localhost:8080".to_string()));
        assert_eq!(config.default_model, "gpt-4");
        assert_eq!(config.default_temperature, 0.5);
        assert_eq!(config.default_max_tokens, 2048);
    }

    #[test]
    fn test_provider_name() {
        let provider = OpenAIProvider::new("test-key");
        assert_eq!(provider.name(), "openai");
    }
}