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
//! Custom Provider Implementation Guide
//!
//! This module provides comprehensive documentation and examples for implementing
//! custom AI providers using the siumai library framework.

use crate::custom_provider::*;
use crate::error::LlmError;
use crate::stream::ChatStream;
// Note: types are used in the examples and implementations below
#[allow(unused_imports)]
use crate::types::*;
use async_trait::async_trait;
use serde_json;

/// # Custom Provider Implementation Guide
///
/// This guide shows you how to implement a custom AI provider for the siumai library.
///
/// ## Step 1: Implement the `CustomProvider` trait
///
/// ```rust,no_run
/// use siumai::prelude::*;
/// use async_trait::async_trait;
///
/// pub struct MyCustomProvider {
///     name: String,
///     base_url: String,
///     api_key: String,
/// }
///
/// #[async_trait]
/// impl CustomProvider for MyCustomProvider {
///     fn name(&self) -> &str {
///         &self.name
///     }
///
///     fn supported_models(&self) -> Vec<String> {
///         vec!["my-model-v1".to_string(), "my-model-v2".to_string()]
///     }
///
///     fn capabilities(&self) -> ProviderCapabilities {
///         ProviderCapabilities::new()
///             .with_chat()
///             .with_streaming()
///             .with_tools()
///     }
///
///     async fn chat(&self, request: CustomChatRequest) -> Result<CustomChatResponse, LlmError> {
///         // Implement your API call here
///         todo!()
///     }
///
///     async fn chat_stream(&self, request: CustomChatRequest) -> Result<ChatStream, LlmError> {
///         // Implement streaming API call here
///         todo!()
///     }
/// }
/// ```
///
/// ## Step 2: Create a configuration and client
///
/// ```rust,ignore
/// # use siumai::prelude::*;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = CustomProviderConfig::new(
///     "my-provider",
///     "https://api.myprovider.com/v1",
///     "your-api-key"
/// )
/// .with_model("my-model-v1")
/// .with_header("User-Agent", "my-app/1.0")
/// .with_timeout(30)
/// .with_param("temperature", 0.7);
///
/// let provider = Box::new(MyCustomProvider::new(config.clone()));
/// let client = CustomProviderClient::new(provider, config)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Step 3: Use the client
///
/// ```rust,no_run
/// # use siumai::prelude::*;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = quick_openai().await?;
/// let messages = vec![user!("Hello, how are you?")];
/// let response = client.chat_with_tools(messages, None).await?;
/// println!("Response: {}", response.content.text().unwrap_or(""));
/// # Ok(())
/// # }
/// ```
/// Example: Hugging Face Provider
///
/// This example shows how to implement a provider for Hugging Face's Inference API
pub struct HuggingFaceProvider {
    http_client: reqwest::Client,
    config: CustomProviderConfig,
}

impl HuggingFaceProvider {
    pub fn new(config: CustomProviderConfig) -> Self {
        let http_client = reqwest::Client::new();
        Self {
            http_client,
            config,
        }
    }

    /// Convert messages to Hugging Face format
    fn convert_messages(&self, messages: &[ChatMessage]) -> Vec<serde_json::Value> {
        messages
            .iter()
            .map(|msg| {
                serde_json::json!({
                    "role": match msg.role {
                        MessageRole::System => "system",
                        MessageRole::User => "user",
                        MessageRole::Assistant => "assistant",
                        MessageRole::Developer => "system", // Developer messages are treated as system messages
                        MessageRole::Tool => "tool",
                    },
                    "content": match &msg.content {
                        MessageContent::Text(text) => text,
                        MessageContent::MultiModal(_) => "[multimodal content not supported]",
                    }
                })
            })
            .collect()
    }

    /// Build request payload
    fn build_request_payload(&self, request: &CustomChatRequest) -> serde_json::Value {
        let mut payload = serde_json::json!({
            "model": request.model,
            "messages": self.convert_messages(&request.messages),
            "stream": request.stream,
        });

        // Add custom parameters
        for (key, value) in &request.params {
            payload[key] = value.clone();
        }

        payload
    }

    /// Parse response from Hugging Face API
    fn parse_response(
        &self,
        response_data: serde_json::Value,
    ) -> Result<CustomChatResponse, LlmError> {
        let content = response_data
            .get("choices")
            .and_then(|choices| choices.as_array())
            .and_then(|arr| arr.first())
            .and_then(|choice| choice.get("message"))
            .and_then(|message| message.get("content"))
            .and_then(|content| content.as_str())
            .unwrap_or("")
            .to_string();

        let finish_reason = response_data
            .get("choices")
            .and_then(|choices| choices.as_array())
            .and_then(|arr| arr.first())
            .and_then(|choice| choice.get("finish_reason"))
            .and_then(|reason| reason.as_str())
            .map(std::string::ToString::to_string);

        let usage = response_data.get("usage").map(|usage_data| Usage {
            prompt_tokens: usage_data
                .get("prompt_tokens")
                .and_then(serde_json::Value::as_u64)
                .map(|v| v as u32)
                .unwrap_or(0),
            completion_tokens: usage_data
                .get("completion_tokens")
                .and_then(serde_json::Value::as_u64)
                .map(|v| v as u32)
                .unwrap_or(0),
            total_tokens: usage_data
                .get("total_tokens")
                .and_then(serde_json::Value::as_u64)
                .map(|v| v as u32)
                .unwrap_or(0),
            reasoning_tokens: None,
            cached_tokens: None,
        });

        let mut response = CustomChatResponse::new(content);

        if let Some(reason) = finish_reason {
            response = response.with_finish_reason(reason);
        }

        if let Some(usage) = usage {
            response = response.with_usage(usage);
        }

        Ok(response)
    }
}

#[async_trait]
impl CustomProvider for HuggingFaceProvider {
    fn name(&self) -> &str {
        "huggingface"
    }

    fn supported_models(&self) -> Vec<String> {
        vec![
            "microsoft/DialoGPT-medium".to_string(),
            "microsoft/DialoGPT-large".to_string(),
            "facebook/blenderbot-400M-distill".to_string(),
            "facebook/blenderbot-1B-distill".to_string(),
        ]
    }

    fn capabilities(&self) -> ProviderCapabilities {
        ProviderCapabilities::new().with_chat().with_streaming()
    }

    async fn chat(&self, request: CustomChatRequest) -> Result<CustomChatResponse, LlmError> {
        let url = format!("{}/chat/completions", self.config.base_url);
        let payload = self.build_request_payload(&request);

        let mut req_builder = self
            .http_client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .header("Content-Type", "application/json");

        // Add custom headers
        for (key, value) in &self.config.headers {
            req_builder = req_builder.header(key, value);
        }

        let response = req_builder
            .json(&payload)
            .send()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if !response.status().is_success() {
            let status_code = response.status().as_u16();
            let error_text = response.text().await.unwrap_or_default();
            return Err(LlmError::api_error(
                status_code,
                format!("Hugging Face API error: {error_text}"),
            ));
        }

        let response_data: serde_json::Value = response
            .json()
            .await
            .map_err(|e| LlmError::ParseError(e.to_string()))?;

        self.parse_response(response_data)
    }

    async fn chat_stream(&self, request: CustomChatRequest) -> Result<ChatStream, LlmError> {
        // For this example, we'll implement a simple streaming simulation
        // In practice, you'd handle Server-Sent Events (SSE) from the API

        use crate::stream::ChatStreamEvent;
        use futures::stream;

        let response = self.chat(request).await?;

        // Simulate streaming by splitting the response into chunks
        let content = response.content;
        let words: Vec<&str> = content.split_whitespace().collect();

        let events: Vec<Result<ChatStreamEvent, LlmError>> = words
            .into_iter()
            .enumerate()
            .map(|(i, word)| {
                let delta = if i == 0 {
                    word.to_string()
                } else {
                    format!(" {word}")
                };
                Ok(ChatStreamEvent::ContentDelta { delta, index: None })
            })
            .collect();

        let stream = stream::iter(events);
        Ok(Box::pin(stream))
    }

    fn validate_config(&self, config: &CustomProviderConfig) -> Result<(), LlmError> {
        // Call the default validation first
        if config.name.is_empty() {
            return Err(LlmError::InvalidParameter(
                "Provider name cannot be empty".to_string(),
            ));
        }
        if config.base_url.is_empty() {
            return Err(LlmError::InvalidParameter(
                "Base URL cannot be empty".to_string(),
            ));
        }
        if config.api_key.is_empty() {
            return Err(LlmError::InvalidParameter(
                "API key cannot be empty".to_string(),
            ));
        }

        // Add Hugging Face-specific validation
        if !config.base_url.contains("huggingface") && !config.base_url.contains("hf.co") {
            return Err(LlmError::InvalidParameter(
                "Base URL should be a Hugging Face endpoint".to_string(),
            ));
        }

        Ok(())
    }
}

/// Builder for Hugging Face provider
pub struct HuggingFaceProviderBuilder {
    config: Option<CustomProviderConfig>,
}

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

impl HuggingFaceProviderBuilder {
    pub const fn new() -> Self {
        Self { config: None }
    }

    pub fn with_config(mut self, config: CustomProviderConfig) -> Self {
        self.config = Some(config);
        self
    }

    pub fn with_api_key<S: Into<String>>(self, api_key: S) -> Self {
        let config = CustomProviderConfig::new(
            "huggingface",
            "https://api-inference.huggingface.co/models",
            &api_key.into(),
        );
        self.with_config(config)
    }
}

impl CustomProviderBuilder for HuggingFaceProviderBuilder {
    fn build(self) -> Result<Box<dyn CustomProvider>, LlmError> {
        let config = self
            .config
            .ok_or_else(|| LlmError::ConfigurationError("Configuration is required".to_string()))?;

        let provider = HuggingFaceProvider::new(config);
        Ok(Box::new(provider))
    }
}

/// Utility functions for custom provider development
pub mod utils {
    use super::*;

    /// Convert standard `ChatMessage` to a generic JSON format
    pub fn message_to_json(message: &ChatMessage) -> serde_json::Value {
        serde_json::json!({
            "role": match message.role {
                MessageRole::System => "system",
                MessageRole::User => "user",
                MessageRole::Assistant => "assistant",
                MessageRole::Developer => "system", // Developer messages are treated as system messages
                MessageRole::Tool => "tool",
            },
            "content": match &message.content {
                MessageContent::Text(text) => serde_json::Value::String(text.clone()),
                MessageContent::MultiModal(parts) => {
                    let content_parts: Vec<serde_json::Value> = parts.iter().map(|part| {
                        match part {
                            ContentPart::Text { text } => serde_json::json!({
                                "type": "text",
                                "text": text
                            }),
                            ContentPart::Image { image_url, detail } => serde_json::json!({
                                "type": "image_url",
                                "image_url": {
                                    "url": image_url,
                                    "detail": detail.as_deref().unwrap_or("auto")
                                }
                            }),
                            ContentPart::Audio { audio_url, format } => serde_json::json!({
                                "type": "audio",
                                "audio_url": audio_url,
                                "format": format
                            }),
                        }
                    }).collect();
                    serde_json::Value::Array(content_parts)
                }
            }
        })
    }

    /// Create a simple error response
    pub fn create_error_response(error_message: &str) -> CustomChatResponse {
        CustomChatResponse::new(format!("Error: {error_message}"))
            .with_finish_reason("error")
            .with_metadata("error", true)
    }

    /// Validate model name against supported models
    pub fn validate_model(model: &str, supported_models: &[String]) -> Result<(), LlmError> {
        if !supported_models.contains(&model.to_string()) {
            return Err(LlmError::InvalidParameter(format!(
                "Model '{}' is not supported. Supported models: {}",
                model,
                supported_models.join(", ")
            )));
        }
        Ok(())
    }
}

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

    #[test]
    fn test_huggingface_provider_creation() {
        let config = CustomProviderConfig::new(
            "huggingface",
            "https://api-inference.huggingface.co/models",
            "test-key",
        );

        let provider = HuggingFaceProvider::new(config);
        assert_eq!(provider.name(), "huggingface");
        assert!(!provider.supported_models().is_empty());
    }

    #[test]
    fn test_message_to_json_conversion() {
        let message = ChatMessage {
            role: MessageRole::User,
            content: MessageContent::Text("Hello".to_string()),
            metadata: MessageMetadata::default(),
            tool_calls: None,
            tool_call_id: None,
        };

        let json = utils::message_to_json(&message);
        assert_eq!(json["role"], "user");
        assert_eq!(json["content"], "Hello");
    }
}