litellm-rs 0.1.1

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! Vector database implementation
//!
//! This module provides vector storage and similarity search functionality.

use crate::config::VectorDbConfig;
use crate::utils::error::{GatewayError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, info};

/// Vector data for storage and retrieval
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorData {
    /// Unique identifier
    pub id: String,
    /// Vector embedding
    pub vector: Vec<f32>,
    /// Associated metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Vector store trait
#[async_trait::async_trait]
pub trait VectorStore: Send + Sync {
    /// Search for similar vectors
    async fn search(&self, vector: Vec<f32>, limit: usize) -> Result<Vec<SearchResult>>;

    /// Insert vectors
    async fn insert(&self, vectors: Vec<VectorData>) -> Result<()>;

    /// Delete vectors by ID
    async fn delete(&self, ids: Vec<String>) -> Result<()>;
}

/// Vector store backend enum
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum VectorStoreBackend {
    /// Qdrant vector database
    Qdrant(QdrantStore),
    /// Weaviate vector database
    Weaviate(WeaviateStore),
    /// Pinecone vector database
    Pinecone(PineconeStore),
}

/// Qdrant vector store
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct QdrantStore {
    url: String,
    api_key: Option<String>,
    collection: String,
    client: reqwest::Client,
}

/// Weaviate vector store
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct WeaviateStore {
    url: String,
    api_key: Option<String>,
    collection: String,
    client: reqwest::Client,
}

/// Pinecone vector store
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct PineconeStore {
    url: String,
    api_key: Option<String>,
    collection: String,
    client: reqwest::Client,
}

/// Search result from vector database
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Result ID
    pub id: String,
    /// Similarity score
    pub score: f32,
    /// Associated metadata
    pub metadata: Option<serde_json::Value>,
    /// Vector data (optional)
    pub vector: Option<Vec<f32>>,
}

/// Vector point for storage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorPoint {
    /// Point ID
    pub id: String,
    /// Vector data
    pub vector: Vec<f32>,
    /// Associated metadata
    pub metadata: Option<serde_json::Value>,
}

/// Pinecone vector store implementation
#[allow(dead_code)]
pub struct PineconeVectorStore {
    config: VectorDbConfig,
    client: reqwest::Client,
}

#[allow(dead_code)]
impl VectorStoreBackend {
    /// Create a new vector store instance
    pub async fn new(config: &VectorDbConfig) -> Result<Self> {
        info!("Initializing vector database: {}", config.db_type);

        match config.db_type.as_str() {
            "qdrant" => Ok(VectorStoreBackend::Qdrant(QdrantStore::new(config).await?)),
            "weaviate" => Ok(VectorStoreBackend::Weaviate(
                WeaviateStore::new(config).await?,
            )),
            "pinecone" => Ok(VectorStoreBackend::Pinecone(
                PineconeStore::new(config).await?,
            )),
            _ => Err(GatewayError::Config(format!(
                "Unsupported vector DB type: {}",
                config.db_type
            ))),
        }
    }

    /// Store a vector with metadata
    pub async fn store(
        &self,
        id: &str,
        vector: &[f32],
        metadata: Option<serde_json::Value>,
    ) -> Result<()> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.store(id, vector, metadata).await,
            VectorStoreBackend::Weaviate(store) => store.store(id, vector, metadata).await,
            VectorStoreBackend::Pinecone(store) => store.store(id, vector, metadata).await,
        }
    }

    /// Search for similar vectors
    pub async fn search(
        &self,
        query_vector: &[f32],
        limit: usize,
        threshold: Option<f32>,
    ) -> Result<Vec<SearchResult>> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.search(query_vector, limit, threshold).await,
            VectorStoreBackend::Weaviate(store) => {
                store.search(query_vector, limit, threshold).await
            }
            VectorStoreBackend::Pinecone(store) => {
                store.search(query_vector, limit, threshold).await
            }
        }
    }

    /// Delete a vector by ID
    pub async fn delete(&self, id: &str) -> Result<()> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.delete(id).await,
            VectorStoreBackend::Weaviate(store) => store.delete(id).await,
            VectorStoreBackend::Pinecone(store) => store.delete(id).await,
        }
    }

    /// Get a vector by ID
    pub async fn get(&self, id: &str) -> Result<Option<VectorPoint>> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.get(id).await,
            VectorStoreBackend::Weaviate(store) => store.get(id).await,
            VectorStoreBackend::Pinecone(store) => store.get(id).await,
        }
    }

    /// Health check
    pub async fn health_check(&self) -> Result<()> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.health_check().await,
            VectorStoreBackend::Weaviate(store) => store.health_check().await,
            VectorStoreBackend::Pinecone(store) => store.health_check().await,
        }
    }

    /// Close connections
    pub async fn close(&self) -> Result<()> {
        match self {
            VectorStoreBackend::Qdrant(_store) => Ok(()), // No explicit close needed for HTTP clients
            VectorStoreBackend::Weaviate(_store) => Ok(()),
            VectorStoreBackend::Pinecone(_store) => Ok(()),
        }
    }

    /// Batch store vectors
    pub async fn batch_store(&self, points: &[VectorPoint]) -> Result<()> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.batch_store(points).await,
            VectorStoreBackend::Weaviate(store) => store.batch_store(points).await,
            VectorStoreBackend::Pinecone(store) => store.batch_store(points).await,
        }
    }

    /// Count vectors in collection
    pub async fn count(&self) -> Result<u64> {
        match self {
            VectorStoreBackend::Qdrant(store) => store.count().await,
            VectorStoreBackend::Weaviate(store) => store.count().await,
            VectorStoreBackend::Pinecone(store) => store.count().await,
        }
    }
}

#[allow(dead_code)]
impl QdrantStore {
    /// Create a new Qdrant store
    pub async fn new(config: &VectorDbConfig) -> Result<Self> {
        let client = reqwest::Client::new();

        let store = Self {
            url: config.url.clone(),
            api_key: Some(config.api_key.clone()),
            collection: config.index_name.clone(),
            client,
        };

        // Ensure collection exists
        store.ensure_collection().await?;

        info!("Qdrant vector store initialized");
        Ok(store)
    }

    /// Ensure collection exists
    async fn ensure_collection(&self) -> Result<()> {
        let url = format!("{}/collections/{}", self.url, self.collection);
        let mut request = self.client.get(&url);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to check collection: {}", e)))?;

        if response.status() == 404 {
            // Collection doesn't exist, create it
            self.create_collection().await?;
        } else if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to check collection: {}",
                response.status()
            )));
        }

        Ok(())
    }

    /// Create collection
    async fn create_collection(&self) -> Result<()> {
        let url = format!("{}/collections/{}", self.url, self.collection);
        let payload = serde_json::json!({
            "vectors": {
                "size": 1536, // Default OpenAI embedding size
                "distance": "Cosine"
            }
        });

        let mut request = self.client.put(&url).json(&payload);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to create collection: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to create collection: {}",
                response.status()
            )));
        }

        info!("Created Qdrant collection: {}", self.collection);
        Ok(())
    }

    /// Store a vector
    pub async fn store(
        &self,
        id: &str,
        vector: &[f32],
        metadata: Option<serde_json::Value>,
    ) -> Result<()> {
        let url = format!("{}/collections/{}/points", self.url, self.collection);
        let payload = serde_json::json!({
            "points": [{
                "id": id,
                "vector": vector,
                "payload": metadata.unwrap_or_default()
            }]
        });

        let mut request = self.client.put(&url).json(&payload);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to store vector: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to store vector: {}",
                response.status()
            )));
        }

        debug!("Stored vector: {}", id);
        Ok(())
    }

    /// Search for similar vectors
    pub async fn search(
        &self,
        query_vector: &[f32],
        limit: usize,
        threshold: Option<f32>,
    ) -> Result<Vec<SearchResult>> {
        let url = format!("{}/collections/{}/points/search", self.url, self.collection);
        let mut payload = serde_json::json!({
            "vector": query_vector,
            "limit": limit,
            "with_payload": true,
            "with_vector": false
        });

        if let Some(threshold) = threshold {
            payload["score_threshold"] =
                serde_json::Value::Number(serde_json::Number::from_f64(threshold as f64).unwrap());
        }

        let mut request = self.client.post(&url).json(&payload);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to search vectors: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to search vectors: {}",
                response.status()
            )));
        }

        let result: serde_json::Value = response.json().await.map_err(|e| {
            GatewayError::VectorDb(format!("Failed to parse search response: {}", e))
        })?;

        let mut search_results = Vec::new();
        if let Some(points) = result["result"].as_array() {
            for point in points {
                if let (Some(id), Some(score)) = (point["id"].as_str(), point["score"].as_f64()) {
                    search_results.push(SearchResult {
                        id: id.to_string(),
                        score: score as f32,
                        metadata: point["payload"].clone().into(),
                        vector: None,
                    });
                }
            }
        }

        Ok(search_results)
    }

    /// Delete a vector
    pub async fn delete(&self, id: &str) -> Result<()> {
        let url = format!("{}/collections/{}/points/delete", self.url, self.collection);
        let payload = serde_json::json!({
            "points": [id]
        });

        let mut request = self.client.post(&url).json(&payload);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to delete vector: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to delete vector: {}",
                response.status()
            )));
        }

        debug!("Deleted vector: {}", id);
        Ok(())
    }

    /// Get a vector by ID
    pub async fn get(&self, id: &str) -> Result<Option<VectorPoint>> {
        let url = format!("{}/collections/{}/points/{}", self.url, self.collection, id);
        let mut request = self.client.get(&url);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to get vector: {}", e)))?;

        if response.status() == 404 {
            return Ok(None);
        }

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to get vector: {}",
                response.status()
            )));
        }

        let result: serde_json::Value = response
            .json()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to parse get response: {}", e)))?;

        if let Some(point) = result["result"].as_object() {
            if let (Some(id), Some(vector)) = (point["id"].as_str(), point["vector"].as_array()) {
                let vector_data: Vec<f32> = vector
                    .iter()
                    .filter_map(|v| v.as_f64().map(|f| f as f32))
                    .collect();

                return Ok(Some(VectorPoint {
                    id: id.to_string(),
                    vector: vector_data,
                    metadata: point["payload"].clone().into(),
                }));
            }
        }

        Ok(None)
    }

    /// Health check
    pub async fn health_check(&self) -> Result<()> {
        let url = format!("{}/", self.url);
        let mut request = self.client.get(&url);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Qdrant health check failed: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Qdrant health check failed: {}",
                response.status()
            )));
        }

        Ok(())
    }

    /// Close connections
    pub async fn close(&self) -> Result<()> {
        // HTTP client doesn't need explicit closing
        Ok(())
    }

    /// Batch store vectors
    pub async fn batch_store(&self, points: &[VectorPoint]) -> Result<()> {
        let url = format!("{}/collections/{}/points", self.url, self.collection);
        let qdrant_points: Vec<serde_json::Value> = points
            .iter()
            .map(|point| {
                serde_json::json!({
                    "id": point.id,
                    "vector": point.vector,
                    "payload": point.metadata.clone().unwrap_or_default()
                })
            })
            .collect();

        let payload = serde_json::json!({
            "points": qdrant_points
        });

        let mut request = self.client.put(&url).json(&payload);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to batch store vectors: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to batch store vectors: {}",
                response.status()
            )));
        }

        debug!("Batch stored {} vectors", points.len());
        Ok(())
    }

    /// Count vectors in collection
    pub async fn count(&self) -> Result<u64> {
        let url = format!("{}/collections/{}", self.url, self.collection);
        let mut request = self.client.get(&url);

        if let Some(api_key) = &self.api_key {
            request = request.header("api-key", api_key);
        }

        let response = request
            .send()
            .await
            .map_err(|e| GatewayError::VectorDb(format!("Failed to get collection info: {}", e)))?;

        if !response.status().is_success() {
            return Err(GatewayError::VectorDb(format!(
                "Failed to get collection info: {}",
                response.status()
            )));
        }

        let result: serde_json::Value = response.json().await.map_err(|e| {
            GatewayError::VectorDb(format!("Failed to parse collection info: {}", e))
        })?;

        if let Some(count) = result["result"]["points_count"].as_u64() {
            Ok(count)
        } else {
            Ok(0)
        }
    }
}

// Placeholder implementations for Weaviate and Pinecone
#[allow(dead_code)]
impl WeaviateStore {
    /// Create new Weaviate store (not implemented)
    pub async fn new(_config: &VectorDbConfig) -> Result<Self> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Store vector (not implemented)
    pub async fn store(
        &self,
        _id: &str,
        _vector: &[f32],
        _metadata: Option<serde_json::Value>,
    ) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Search vectors (not implemented)
    pub async fn search(
        &self,
        _query_vector: &[f32],
        _limit: usize,
        _threshold: Option<f32>,
    ) -> Result<Vec<SearchResult>> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Delete vector (not implemented)
    pub async fn delete(&self, _id: &str) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Get vector by ID (not implemented)
    pub async fn get(&self, _id: &str) -> Result<Option<VectorPoint>> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Health check (not implemented)
    pub async fn health_check(&self) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Close connection
    pub async fn close(&self) -> Result<()> {
        Ok(())
    }

    /// Batch store vectors (not implemented)
    pub async fn batch_store(&self, _points: &[VectorPoint]) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }

    /// Count vectors (not implemented)
    pub async fn count(&self) -> Result<u64> {
        Err(GatewayError::VectorDb(
            "Weaviate not implemented yet".to_string(),
        ))
    }
}

#[allow(dead_code)]
impl PineconeStore {
    /// Create new Pinecone store (not implemented)
    pub async fn new(_config: &VectorDbConfig) -> Result<Self> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Store vector (not implemented)
    pub async fn store(
        &self,
        _id: &str,
        _vector: &[f32],
        _metadata: Option<serde_json::Value>,
    ) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Search vectors (not implemented)
    pub async fn search(
        &self,
        _query_vector: &[f32],
        _limit: usize,
        _threshold: Option<f32>,
    ) -> Result<Vec<SearchResult>> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Delete vector (not implemented)
    pub async fn delete(&self, _id: &str) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Get vector by ID (not implemented)
    pub async fn get(&self, _id: &str) -> Result<Option<VectorPoint>> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Health check (not implemented)
    pub async fn health_check(&self) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Close connection
    pub async fn close(&self) -> Result<()> {
        Ok(())
    }

    /// Batch store vectors (not implemented)
    pub async fn batch_store(&self, _points: &[VectorPoint]) -> Result<()> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }

    /// Count vectors (not implemented)
    pub async fn count(&self) -> Result<u64> {
        Err(GatewayError::VectorDb(
            "Pinecone not implemented yet".to_string(),
        ))
    }
}

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

    #[test]
    fn test_vector_point_creation() {
        let point = VectorPoint {
            id: "test-1".to_string(),
            vector: vec![0.1, 0.2, 0.3],
            metadata: Some(serde_json::json!({"text": "test document"})),
        };

        assert_eq!(point.id, "test-1");
        assert_eq!(point.vector.len(), 3);
        assert!(point.metadata.is_some());
    }

    #[test]
    fn test_search_result_creation() {
        let result = SearchResult {
            id: "result-1".to_string(),
            score: 0.95,
            metadata: Some(serde_json::json!({"category": "test"})),
            vector: None,
        };

        assert_eq!(result.id, "result-1");
        assert_eq!(result.score, 0.95);
        assert!(result.metadata.is_some());
        assert!(result.vector.is_none());
    }
}