litellm-rs 0.4.16

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! HuggingFace Provider Implementation
//!
//! Main provider implementation integrating HuggingFace Hub capabilities.

use futures::Stream;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::pin::Pin;
use tracing::{debug, warn};

use crate::core::providers::base::{
    BaseConfig, BaseHttpClient, HttpErrorMapper, apply_headers, header, header_static,
};
use crate::core::traits::{
    error_mapper::trait_def::ErrorMapper, provider::ProviderConfig,
    provider::llm_provider::trait_definition::LLMProvider,
};
use crate::core::types::{
    chat::ChatRequest,
    context::RequestContext,
    embedding::EmbeddingRequest,
    health::HealthStatus,
    model::ModelInfo,
    model::ProviderCapability,
    responses::{ChatChunk, ChatResponse, EmbeddingResponse},
};

use super::config::{HF_HUB_URL, HuggingFaceConfig};
use super::embedding::HuggingFaceEmbeddingHandler;
use super::error::{HuggingFaceError, parse_hf_error_response};
use super::models::{get_default_models, parse_model_string};
use crate::core::providers::unified_provider::ProviderError;

// Static capabilities
const HUGGINGFACE_CAPABILITIES: &[ProviderCapability] = &[
    ProviderCapability::ChatCompletion,
    ProviderCapability::ChatCompletionStream,
    ProviderCapability::ToolCalling,
    ProviderCapability::Embeddings,
];

/// HuggingFace error mapper
pub struct HuggingFaceErrorMapper;

impl ErrorMapper<HuggingFaceError> for HuggingFaceErrorMapper {
    fn map_http_error(&self, status_code: u16, response_body: &str) -> HuggingFaceError {
        parse_hf_error_response(status_code, response_body)
    }

    fn map_json_error(&self, error_response: &Value) -> HuggingFaceError {
        HttpErrorMapper::parse_json_error("huggingface", error_response)
    }

    fn map_network_error(&self, error: &dyn std::error::Error) -> HuggingFaceError {
        HuggingFaceError::network("huggingface", error.to_string())
    }

    fn map_parsing_error(&self, error: &dyn std::error::Error) -> HuggingFaceError {
        HuggingFaceError::response_parsing("huggingface", error.to_string())
    }

    fn map_timeout_error(&self, timeout_duration: std::time::Duration) -> HuggingFaceError {
        HuggingFaceError::timeout(
            "huggingface",
            format!("Request timed out after {:?}", timeout_duration),
        )
    }
}

/// HuggingFace provider implementation
#[derive(Debug, Clone)]
pub struct HuggingFaceProvider {
    config: HuggingFaceConfig,
    base_client: BaseHttpClient,
    embedding_handler: HuggingFaceEmbeddingHandler,
    models: Vec<ModelInfo>,
}

impl HuggingFaceProvider {
    /// Create a new HuggingFace provider instance
    pub async fn new(config: HuggingFaceConfig) -> Result<Self, HuggingFaceError> {
        // Validate configuration
        config
            .validate()
            .map_err(|e| HuggingFaceError::configuration("huggingface", e))?;

        // Create base HTTP client
        let base_config = BaseConfig {
            api_key: Some(config.api_key.clone()),
            api_base: config.api_base.clone(),
            timeout: config.timeout_seconds,
            max_retries: config.max_retries,
            headers: HashMap::new(),
            organization: None,
            api_version: None,
        };

        let base_client = BaseHttpClient::new(base_config)?;
        let embedding_handler = HuggingFaceEmbeddingHandler::new(config.clone());
        let models = get_default_models();

        Ok(Self {
            config,
            base_client,
            embedding_handler,
            models,
        })
    }

    /// Create provider with API key only
    pub async fn with_api_key(api_key: impl Into<String>) -> Result<Self, HuggingFaceError> {
        let config = HuggingFaceConfig::new(api_key);
        Self::new(config).await
    }

    /// Get the config
    pub fn config(&self) -> &HuggingFaceConfig {
        &self.config
    }

    /// Transform a chat request to HuggingFace/OpenAI-compatible format
    fn transform_chat_request(&self, request: &ChatRequest, mapped_model: &str) -> Value {
        let mut body = json!({
            "model": mapped_model,
            "messages": request.messages,
        });

        // Add optional parameters
        if let Some(temp) = request.temperature {
            // HuggingFace requires temperature > 0
            let temp_value = if temp <= 0.0 { 0.01 } else { temp };
            body["temperature"] = json!(temp_value);
        }

        if let Some(max_tokens) = request.max_tokens {
            // HuggingFace uses max_new_tokens
            let max_value = if max_tokens == 0 { 1 } else { max_tokens };
            body["max_tokens"] = json!(max_value);
        }

        if let Some(max_completion_tokens) = request.max_completion_tokens {
            let max_value = if max_completion_tokens == 0 {
                1
            } else {
                max_completion_tokens
            };
            body["max_tokens"] = json!(max_value);
        }

        if let Some(top_p) = request.top_p {
            body["top_p"] = json!(top_p);
        }

        if let Some(stop) = &request.stop {
            body["stop"] = json!(stop);
        }

        if let Some(n) = request.n {
            body["n"] = json!(n);
        }

        if let Some(seed) = request.seed {
            body["seed"] = json!(seed);
        }

        if let Some(user) = &request.user {
            body["user"] = json!(user);
        }

        if let Some(tools) = &request.tools {
            body["tools"] = json!(tools);
        }

        if let Some(tool_choice) = &request.tool_choice {
            body["tool_choice"] = json!(tool_choice);
        }

        if let Some(response_format) = &request.response_format {
            body["response_format"] = json!(response_format);
        }

        body
    }

    /// Fetch provider mapping from HuggingFace Hub API
    async fn fetch_provider_mapping(
        &self,
        model: &str,
    ) -> Result<HashMap<String, Value>, HuggingFaceError> {
        let url = format!("{}/api/models/{}", HF_HUB_URL, model);

        let headers = vec![
            header("Authorization", format!("Bearer {}", self.config.api_key)),
            header("Accept", "application/json".to_string()),
        ];

        let response = apply_headers(self.base_client.inner().get(&url), headers)
            .query(&[("expand", "inferenceProviderMapping")])
            .send()
            .await
            .map_err(|e| HuggingFaceError::huggingface_network_error(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body = response.text().await.unwrap_or_default();
            return Err(parse_hf_error_response(status, &body));
        }

        let data: Value = response
            .json()
            .await
            .map_err(|e| HuggingFaceError::huggingface_response_parsing(e.to_string()))?;

        if let Some(mapping) = data.get("inferenceProviderMapping")
            && let Some(obj) = mapping.as_object()
        {
            return Ok(obj.clone().into_iter().collect());
        }

        Ok(HashMap::new())
    }

    /// Get the mapped model ID for a specific provider
    async fn get_mapped_model(
        &self,
        model: &str,
        provider: &str,
    ) -> Result<String, HuggingFaceError> {
        let mapping = self.fetch_provider_mapping(model).await?;

        if let Some(provider_info) = mapping.get(provider) {
            if let Some(status) = provider_info.get("status").and_then(|s| s.as_str())
                && status == "staging"
            {
                warn!(
                    "Model {} is in staging mode for provider {}. Meant for test purposes only.",
                    model, provider
                );
            }

            if let Some(provider_id) = provider_info.get("providerId").and_then(|p| p.as_str()) {
                return Ok(provider_id.to_string());
            }
        }

        // Check if provider is available
        if mapping.is_empty() || !mapping.contains_key(provider) {
            return Err(HuggingFaceError::huggingface_provider_not_found(
                model, provider,
            ));
        }

        Ok(model.to_string())
    }

    /// Determine if this is a TGI/custom endpoint request
    fn is_custom_endpoint(&self) -> bool {
        self.config.api_base.is_some()
    }
}

impl LLMProvider for HuggingFaceProvider {
    fn name(&self) -> &'static str {
        "huggingface"
    }

    fn capabilities(&self) -> &'static [ProviderCapability] {
        HUGGINGFACE_CAPABILITIES
    }

    fn models(&self) -> &[ModelInfo] {
        &self.models
    }

    fn get_supported_openai_params(&self, _model: &str) -> &'static [&'static str] {
        &[
            "temperature",
            "top_p",
            "max_tokens",
            "max_completion_tokens",
            "stream",
            "stop",
            "n",
            "seed",
            "tools",
            "tool_choice",
            "response_format",
            "user",
        ]
    }

    async fn map_openai_params(
        &self,
        params: HashMap<String, Value>,
        _model: &str,
    ) -> Result<HashMap<String, Value>, ProviderError> {
        // HuggingFace uses OpenAI-compatible parameters with some adjustments
        let mut mapped = HashMap::new();

        for (key, value) in params {
            match key.as_str() {
                // Temperature must be > 0
                "temperature" => {
                    let temp = value.as_f64().unwrap_or(1.0);
                    let adjusted = if temp <= 0.0 { 0.01 } else { temp };
                    mapped.insert(key, json!(adjusted));
                }
                // max_tokens/max_completion_tokens must be > 0
                "max_tokens" | "max_completion_tokens" => {
                    let tokens = value.as_u64().unwrap_or(1024);
                    let adjusted = if tokens == 0 { 1 } else { tokens };
                    mapped.insert("max_tokens".to_string(), json!(adjusted));
                }
                // Direct pass-through for standard parameters
                "top_p" | "stream" | "stop" | "n" | "seed" | "tools" | "tool_choice"
                | "response_format" | "user" => {
                    mapped.insert(key, value);
                }
                // Skip unsupported parameters
                _ => {
                    debug!("Skipping unsupported parameter: {}", key);
                }
            }
        }

        Ok(mapped)
    }

    async fn transform_request(
        &self,
        request: ChatRequest,
        _context: RequestContext,
    ) -> Result<Value, ProviderError> {
        // Parse model string to extract provider and model ID
        let (provider, model_id) = parse_model_string(&request.model);

        // Get mapped model if using provider routing
        let mapped_model = if let Some(ref prov) = provider {
            if !self.is_custom_endpoint() {
                self.get_mapped_model(&model_id, prov).await?
            } else {
                model_id.clone()
            }
        } else {
            model_id.clone()
        };

        Ok(self.transform_chat_request(&request, &mapped_model))
    }

    async fn transform_response(
        &self,
        raw_response: &[u8],
        _model: &str,
        _request_id: &str,
    ) -> Result<ChatResponse, ProviderError> {
        // Parse OpenAI-compatible response
        serde_json::from_slice(raw_response)
            .map_err(|e| HuggingFaceError::huggingface_response_parsing(e.to_string()))
    }

    fn get_error_mapper(&self) -> Box<dyn ErrorMapper<ProviderError>> {
        Box::new(HuggingFaceErrorMapper)
    }

    async fn chat_completion(
        &self,
        request: ChatRequest,
        _context: RequestContext,
    ) -> Result<ChatResponse, ProviderError> {
        debug!("HuggingFace chat request: model={}", request.model);

        // Parse model string to extract provider and model ID
        let (provider, model_id) = parse_model_string(&request.model);

        // Get mapped model if using provider routing
        let mapped_model = if let Some(ref prov) = provider {
            if !self.is_custom_endpoint() {
                self.get_mapped_model(&model_id, prov).await?
            } else {
                model_id.clone()
            }
        } else {
            model_id.clone()
        };

        // Transform request
        let body = self.transform_chat_request(&request, &mapped_model);

        // Build URL
        let url = self.config.get_chat_url(provider.as_deref(), &model_id);

        debug!("HuggingFace request URL: {}", url);

        // Build headers
        let headers = vec![
            header("Authorization", format!("Bearer {}", self.config.api_key)),
            header_static("Content-Type", "application/json"),
        ];

        let response = apply_headers(self.base_client.inner().post(&url), headers)
            .json(&body)
            .send()
            .await
            .map_err(|e| HuggingFaceError::huggingface_network_error(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body = response.text().await.unwrap_or_default();
            return Err(parse_hf_error_response(status, &body));
        }

        response
            .json()
            .await
            .map_err(|e| HuggingFaceError::huggingface_response_parsing(e.to_string()))
    }

    async fn chat_completion_stream(
        &self,
        request: ChatRequest,
        _context: RequestContext,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<ChatChunk, ProviderError>> + Send>>, ProviderError>
    {
        debug!(
            "HuggingFace streaming chat request: model={}",
            request.model
        );

        // Parse model string to extract provider and model ID
        let (provider, model_id) = parse_model_string(&request.model);

        // Get mapped model if using provider routing
        let mapped_model = if let Some(ref prov) = provider {
            if !self.is_custom_endpoint() {
                self.get_mapped_model(&model_id, prov).await?
            } else {
                model_id.clone()
            }
        } else {
            model_id.clone()
        };

        // Transform request with streaming enabled
        let mut body = self.transform_chat_request(&request, &mapped_model);
        body["stream"] = json!(true);

        // Build URL
        let url = self.config.get_chat_url(provider.as_deref(), &model_id);

        // Build headers
        let headers = vec![
            header("Authorization", format!("Bearer {}", self.config.api_key)),
            header_static("Content-Type", "application/json"),
        ];

        let response = apply_headers(self.base_client.inner().post(&url), headers)
            .json(&body)
            .send()
            .await
            .map_err(|e| HuggingFaceError::huggingface_network_error(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body = response.text().await.unwrap_or_default();
            return Err(parse_hf_error_response(status, &body));
        }

        Ok(crate::core::providers::base::create_provider_sse_stream(
            response,
            "huggingface",
        ))
    }

    async fn embeddings(
        &self,
        request: EmbeddingRequest,
        _context: RequestContext,
    ) -> Result<EmbeddingResponse, ProviderError> {
        debug!("HuggingFace embedding request: model={}", request.model);

        // Transform request
        let body = self.embedding_handler.transform_request(&request);

        // Determine task type
        let task = if request.model.contains("sentence-transformers") {
            "sentence-similarity"
        } else {
            "feature-extraction"
        };

        // Build URL
        let url = self.config.get_embeddings_url(task, &request.model);

        // Build headers
        let headers = vec![
            header("Authorization", format!("Bearer {}", self.config.api_key)),
            header_static("Content-Type", "application/json"),
        ];

        let response = apply_headers(self.base_client.inner().post(&url), headers)
            .json(&body)
            .send()
            .await
            .map_err(|e| HuggingFaceError::huggingface_network_error(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let body_text = response.text().await.unwrap_or_default();
            return Err(parse_hf_error_response(status, &body_text));
        }

        let response_json: Value = response
            .json()
            .await
            .map_err(|e| HuggingFaceError::huggingface_response_parsing(e.to_string()))?;

        // Calculate input count for usage estimation
        let input_count = match &request.input {
            crate::core::types::embedding::EmbeddingInput::Text(_) => 1,
            crate::core::types::embedding::EmbeddingInput::Array(arr) => arr.len(),
        };

        self.embedding_handler
            .transform_response(response_json, &request.model, input_count)
    }

    async fn health_check(&self) -> HealthStatus {
        // Try a simple models endpoint request
        let url = format!("{}/api/models", HF_HUB_URL);

        match apply_headers(
            self.base_client.inner().get(&url),
            vec![
                header("Authorization", format!("Bearer {}", self.config.api_key)),
                header("Accept", "application/json".to_string()),
            ],
        )
        .query(&[("limit", "1")])
        .send()
        .await
        {
            Ok(response) if response.status().is_success() => HealthStatus::Healthy,
            Ok(response) => {
                debug!(
                    "HuggingFace health check failed: status={}",
                    response.status()
                );
                HealthStatus::Unhealthy
            }
            Err(e) => {
                debug!("HuggingFace health check error: {}", e);
                HealthStatus::Unhealthy
            }
        }
    }

    async fn calculate_cost(
        &self,
        _model: &str,
        _input_tokens: u32,
        _output_tokens: u32,
    ) -> Result<f64, ProviderError> {
        // HuggingFace pricing varies by provider, returning 0 as default
        // Users are billed through their HuggingFace account at provider rates
        Ok(0.0)
    }
}