openai-ergonomic 0.5.2

Ergonomic Rust wrapper for OpenAI API
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
//! Vector Stores API builders.
//!
//! This module provides ergonomic builders for `OpenAI` Vector Stores API operations,
//! including creating and managing vector stores for RAG (Retrieval-Augmented Generation) use cases.
//!
//! Vector stores are used to store and search through documents that can be used
//! by assistants with file search capabilities.

use std::collections::HashMap;

/// Builder for creating a new vector store.
///
/// Vector stores are collections of files that can be searched through
/// using semantic similarity. They're commonly used for RAG applications.
#[derive(Debug, Clone)]
pub struct VectorStoreBuilder {
    name: Option<String>,
    file_ids: Vec<String>,
    expires_after: Option<VectorStoreExpirationPolicy>,
    metadata: HashMap<String, String>,
}

/// Expiration policy for vector stores.
#[derive(Debug, Clone)]
pub struct VectorStoreExpirationPolicy {
    /// Number of days after which the vector store expires.
    pub days: i32,
}

impl VectorStoreBuilder {
    /// Create a new vector store builder.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use openai_ergonomic::builders::vector_stores::VectorStoreBuilder;
    ///
    /// let builder = VectorStoreBuilder::new()
    ///     .name("My Knowledge Base")
    ///     .file_ids(vec!["file-123".to_string(), "file-456".to_string()]);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            name: None,
            file_ids: Vec::new(),
            expires_after: None,
            metadata: HashMap::new(),
        }
    }

    /// Set the vector store's name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the file IDs to include in the vector store.
    #[must_use]
    pub fn file_ids(mut self, file_ids: Vec<String>) -> Self {
        self.file_ids = file_ids;
        self
    }

    /// Add a single file ID to the vector store.
    #[must_use]
    pub fn add_file(mut self, file_id: impl Into<String>) -> Self {
        self.file_ids.push(file_id.into());
        self
    }

    /// Add multiple file IDs to the vector store.
    #[must_use]
    pub fn add_files<I, S>(mut self, file_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.file_ids
            .extend(file_ids.into_iter().map(std::convert::Into::into));
        self
    }

    /// Clear all file IDs from the vector store.
    #[must_use]
    pub fn clear_files(mut self) -> Self {
        self.file_ids.clear();
        self
    }

    /// Set expiration policy for the vector store.
    #[must_use]
    pub fn expires_after_days(mut self, days: i32) -> Self {
        self.expires_after = Some(VectorStoreExpirationPolicy { days });
        self
    }

    /// Add metadata to the vector store.
    #[must_use]
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Get the name of this vector store.
    #[must_use]
    pub fn name_ref(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Get the file IDs for this vector store.
    #[must_use]
    pub fn file_ids_ref(&self) -> &[String] {
        &self.file_ids
    }

    /// Get the expiration policy for this vector store.
    #[must_use]
    pub fn expires_after_ref(&self) -> Option<&VectorStoreExpirationPolicy> {
        self.expires_after.as_ref()
    }

    /// Get the metadata for this vector store.
    #[must_use]
    pub fn metadata_ref(&self) -> &HashMap<String, String> {
        &self.metadata
    }

    /// Check if the vector store has any files.
    #[must_use]
    pub fn has_files(&self) -> bool {
        !self.file_ids.is_empty()
    }

    /// Get the number of files in the vector store.
    #[must_use]
    pub fn file_count(&self) -> usize {
        self.file_ids.len()
    }
}

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

/// Builder for vector store file operations.
#[derive(Debug, Clone)]
pub struct VectorStoreFileBuilder {
    vector_store_id: String,
    file_id: String,
}

impl VectorStoreFileBuilder {
    /// Create a new vector store file builder.
    #[must_use]
    pub fn new(vector_store_id: impl Into<String>, file_id: impl Into<String>) -> Self {
        Self {
            vector_store_id: vector_store_id.into(),
            file_id: file_id.into(),
        }
    }

    /// Get the vector store ID.
    #[must_use]
    pub fn vector_store_id(&self) -> &str {
        &self.vector_store_id
    }

    /// Get the file ID.
    #[must_use]
    pub fn file_id(&self) -> &str {
        &self.file_id
    }
}

/// Builder for searching through vector stores.
#[derive(Debug, Clone)]
pub struct VectorStoreSearchBuilder {
    vector_store_id: String,
    query: String,
    limit: Option<i32>,
    filter: HashMap<String, String>,
}

impl VectorStoreSearchBuilder {
    /// Create a new vector store search builder.
    #[must_use]
    pub fn new(vector_store_id: impl Into<String>, query: impl Into<String>) -> Self {
        Self {
            vector_store_id: vector_store_id.into(),
            query: query.into(),
            limit: None,
            filter: HashMap::new(),
        }
    }

    /// Set the maximum number of results to return.
    #[must_use]
    pub fn limit(mut self, limit: i32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Add a filter to the search.
    #[must_use]
    pub fn filter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.filter.insert(key.into(), value.into());
        self
    }

    /// Get the vector store ID for this search.
    #[must_use]
    pub fn vector_store_id(&self) -> &str {
        &self.vector_store_id
    }

    /// Get the search query.
    #[must_use]
    pub fn query(&self) -> &str {
        &self.query
    }

    /// Get the search limit.
    #[must_use]
    pub fn limit_ref(&self) -> Option<i32> {
        self.limit
    }

    /// Get the search filters.
    #[must_use]
    pub fn filter_ref(&self) -> &HashMap<String, String> {
        &self.filter
    }
}

/// Helper function to create a simple vector store with a name.
#[must_use]
pub fn simple_vector_store(name: impl Into<String>) -> VectorStoreBuilder {
    VectorStoreBuilder::new().name(name)
}

/// Helper function to create a vector store with files.
#[must_use]
pub fn vector_store_with_files(
    name: impl Into<String>,
    file_ids: Vec<String>,
) -> VectorStoreBuilder {
    VectorStoreBuilder::new().name(name).file_ids(file_ids)
}

/// Helper function to create a temporary vector store that expires after a specified number of days.
#[must_use]
pub fn temporary_vector_store(
    name: impl Into<String>,
    expires_after_days: i32,
) -> VectorStoreBuilder {
    VectorStoreBuilder::new()
        .name(name)
        .expires_after_days(expires_after_days)
}

/// Helper function to add a file to a vector store.
#[must_use]
pub fn add_file_to_vector_store(
    vector_store_id: impl Into<String>,
    file_id: impl Into<String>,
) -> VectorStoreFileBuilder {
    VectorStoreFileBuilder::new(vector_store_id, file_id)
}

/// Helper function to search through a vector store.
#[must_use]
pub fn search_vector_store(
    vector_store_id: impl Into<String>,
    query: impl Into<String>,
) -> VectorStoreSearchBuilder {
    VectorStoreSearchBuilder::new(vector_store_id, query)
}

/// Helper function to search with a limit.
#[must_use]
pub fn search_vector_store_with_limit(
    vector_store_id: impl Into<String>,
    query: impl Into<String>,
    limit: i32,
) -> VectorStoreSearchBuilder {
    VectorStoreSearchBuilder::new(vector_store_id, query).limit(limit)
}

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

    #[test]
    fn test_vector_store_builder() {
        let builder = VectorStoreBuilder::new()
            .name("Test Store")
            .add_file("file-1")
            .add_file("file-2")
            .expires_after_days(30)
            .metadata("key", "value");

        assert_eq!(builder.name_ref(), Some("Test Store"));
        assert_eq!(builder.file_count(), 2);
        assert_eq!(builder.file_ids_ref(), &["file-1", "file-2"]);
        assert!(builder.has_files());
        assert!(builder.expires_after_ref().is_some());
        assert_eq!(builder.expires_after_ref().unwrap().days, 30);
        assert_eq!(builder.metadata_ref().len(), 1);
    }

    #[test]
    fn test_vector_store_builder_with_file_ids() {
        let file_ids = vec![
            "file-1".to_string(),
            "file-2".to_string(),
            "file-3".to_string(),
        ];
        let builder = VectorStoreBuilder::new()
            .name("Bulk Files Store")
            .file_ids(file_ids.clone());

        assert_eq!(builder.name_ref(), Some("Bulk Files Store"));
        assert_eq!(builder.file_ids_ref(), file_ids.as_slice());
        assert_eq!(builder.file_count(), 3);
        assert!(builder.has_files());
    }

    #[test]
    fn test_vector_store_file_builder() {
        let builder = VectorStoreFileBuilder::new("vs-123", "file-456");
        assert_eq!(builder.vector_store_id(), "vs-123");
        assert_eq!(builder.file_id(), "file-456");
    }

    #[test]
    fn test_vector_store_search_builder() {
        let builder = VectorStoreSearchBuilder::new("vs-123", "search query")
            .limit(10)
            .filter("category", "documentation");

        assert_eq!(builder.vector_store_id(), "vs-123");
        assert_eq!(builder.query(), "search query");
        assert_eq!(builder.limit_ref(), Some(10));
        assert_eq!(builder.filter_ref().len(), 1);
        assert_eq!(
            builder.filter_ref().get("category"),
            Some(&"documentation".to_string())
        );
    }

    #[test]
    fn test_simple_vector_store_helper() {
        let builder = simple_vector_store("Simple Store");
        assert_eq!(builder.name_ref(), Some("Simple Store"));
        assert!(!builder.has_files());
    }

    #[test]
    fn test_vector_store_with_files_helper() {
        let file_ids = vec!["file-1".to_string(), "file-2".to_string()];
        let builder = vector_store_with_files("Files Store", file_ids.clone());
        assert_eq!(builder.name_ref(), Some("Files Store"));
        assert_eq!(builder.file_ids_ref(), file_ids.as_slice());
        assert!(builder.has_files());
    }

    #[test]
    fn test_temporary_vector_store_helper() {
        let builder = temporary_vector_store("Temp Store", 7);
        assert_eq!(builder.name_ref(), Some("Temp Store"));
        assert!(builder.expires_after_ref().is_some());
        assert_eq!(builder.expires_after_ref().unwrap().days, 7);
    }

    #[test]
    fn test_add_file_to_vector_store_helper() {
        let builder = add_file_to_vector_store("vs-123", "file-456");
        assert_eq!(builder.vector_store_id(), "vs-123");
        assert_eq!(builder.file_id(), "file-456");
    }

    #[test]
    fn test_search_vector_store_helper() {
        let builder = search_vector_store("vs-123", "test query");
        assert_eq!(builder.vector_store_id(), "vs-123");
        assert_eq!(builder.query(), "test query");
        assert!(builder.limit_ref().is_none());
    }

    #[test]
    fn test_search_vector_store_with_limit_helper() {
        let builder = search_vector_store_with_limit("vs-123", "test query", 5);
        assert_eq!(builder.vector_store_id(), "vs-123");
        assert_eq!(builder.query(), "test query");
        assert_eq!(builder.limit_ref(), Some(5));
    }

    #[test]
    fn test_vector_store_builder_default() {
        let builder = VectorStoreBuilder::default();
        assert!(builder.name_ref().is_none());
        assert!(!builder.has_files());
        assert!(builder.expires_after_ref().is_none());
        assert!(builder.metadata_ref().is_empty());
    }

    #[test]
    fn test_vector_store_expiration_policy() {
        let policy = VectorStoreExpirationPolicy { days: 15 };
        assert_eq!(policy.days, 15);
    }

    #[test]
    fn test_vector_store_builder_add_files() {
        let builder = VectorStoreBuilder::new()
            .name("Multi-File Store")
            .add_file("file-1")
            .add_files(vec!["file-2", "file-3", "file-4"])
            .add_file("file-5");

        assert_eq!(builder.name_ref(), Some("Multi-File Store"));
        assert_eq!(builder.file_count(), 5);
        assert_eq!(
            builder.file_ids_ref(),
            &["file-1", "file-2", "file-3", "file-4", "file-5"]
        );
        assert!(builder.has_files());
    }

    #[test]
    fn test_vector_store_builder_clear_files() {
        let builder = VectorStoreBuilder::new()
            .add_files(vec!["file-1", "file-2", "file-3"])
            .clear_files()
            .add_file("file-new");

        assert_eq!(builder.file_count(), 1);
        assert_eq!(builder.file_ids_ref(), &["file-new"]);
        assert!(builder.has_files());
    }
}