Skip to main content

openai_core/resources/
vector_stores.rs

1//! Vector Stores 命名空间实现。
2
3use std::collections::BTreeMap;
4
5use http::Method;
6use serde::{Deserialize, Serialize};
7use serde_json::{Number, Value};
8
9use super::{
10    DeleteResponse, JsonRequestBuilder, ListRequestBuilder, VectorStoreFileBatchesResource,
11    VectorStoreFilesResource, VectorStoresResource, encode_path_segment,
12};
13use crate::Page;
14use crate::generated::endpoints;
15
16/// Vector store 元数据。
17pub type VectorStoreMetadata = BTreeMap<String, String>;
18
19/// Vector store 文件属性。
20pub type VectorStoreAttributes = BTreeMap<String, VectorStoreAttributeValue>;
21
22/// 表示 metadata / attributes 中的标量值。
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
24#[serde(untagged)]
25pub enum VectorStoreAttributeValue {
26    /// 字符串值。
27    String(String),
28    /// 数字值。
29    Number(Number),
30    /// 布尔值。
31    Bool(bool),
32}
33
34/// 表示 vector store 文件计数。
35#[derive(Debug, Clone, Serialize, Deserialize, Default)]
36pub struct VectorStoreFileCounts {
37    /// 已取消文件数量。
38    pub cancelled: Option<u64>,
39    /// 已完成文件数量。
40    pub completed: Option<u64>,
41    /// 失败文件数量。
42    pub failed: Option<u64>,
43    /// 处理中数量。
44    pub in_progress: Option<u64>,
45    /// 文件总数。
46    pub total: Option<u64>,
47    /// 额外字段。
48    #[serde(flatten)]
49    pub extra: BTreeMap<String, Value>,
50}
51
52/// 表示 vector store 过期策略。
53#[derive(Debug, Clone, Serialize, Deserialize, Default)]
54pub struct VectorStoreExpiresAfter {
55    /// 锚点。
56    pub anchor: Option<String>,
57    /// 过期天数。
58    pub days: Option<u64>,
59    /// 额外字段。
60    #[serde(flatten)]
61    pub extra: BTreeMap<String, Value>,
62}
63
64/// 表示静态分块策略配置。
65#[derive(Debug, Clone, Serialize, Deserialize, Default)]
66pub struct VectorStoreStaticFileChunkingStrategy {
67    /// chunk 重叠 token 数。
68    pub chunk_overlap_tokens: Option<u64>,
69    /// 每个 chunk 的最大 token 数。
70    pub max_chunk_size_tokens: Option<u64>,
71    /// 额外字段。
72    #[serde(flatten)]
73    pub extra: BTreeMap<String, Value>,
74}
75
76/// 表示文件分块策略。
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(tag = "type", rename_all = "snake_case")]
79pub enum VectorStoreFileChunkingStrategy {
80    /// 静态分块。
81    Static {
82        /// 静态分块配置。
83        #[serde(rename = "static")]
84        configuration: VectorStoreStaticFileChunkingStrategy,
85    },
86    /// 旧文件或未知策略返回的 other 类型。
87    Other,
88    /// 向前兼容的未知策略。
89    #[serde(other)]
90    Unknown,
91}
92
93/// 表示 vector store 文件处理错误。
94#[derive(Debug, Clone, Serialize, Deserialize, Default)]
95pub struct VectorStoreFileLastError {
96    /// 错误码。
97    pub code: Option<String>,
98    /// 错误描述。
99    pub message: Option<String>,
100    /// 额外字段。
101    #[serde(flatten)]
102    pub extra: BTreeMap<String, Value>,
103}
104
105/// 表示 vector store 文件内容项。
106#[derive(Debug, Clone, Serialize, Deserialize, Default)]
107pub struct VectorStoreFileContent {
108    /// 内容文本。
109    pub text: Option<String>,
110    /// 内容类型。
111    #[serde(rename = "type")]
112    pub content_type: Option<String>,
113    /// 额外字段。
114    #[serde(flatten)]
115    pub extra: BTreeMap<String, Value>,
116}
117
118/// 表示 vector store 搜索命中的内容片段。
119#[derive(Debug, Clone, Serialize, Deserialize, Default)]
120pub struct VectorStoreSearchContent {
121    /// 返回的文本内容。
122    pub text: Option<String>,
123    /// 内容类型。
124    #[serde(rename = "type")]
125    pub content_type: Option<String>,
126    /// 额外字段。
127    #[serde(flatten)]
128    pub extra: BTreeMap<String, Value>,
129}
130
131/// 表示 vector store 搜索命中项。
132#[derive(Debug, Clone, Serialize, Deserialize, Default)]
133pub struct VectorStoreSearchResult {
134    /// 文件属性过滤数据。
135    pub attributes: Option<VectorStoreAttributes>,
136    /// 内容片段。
137    #[serde(default)]
138    pub content: Vec<VectorStoreSearchContent>,
139    /// 文件 ID。
140    pub file_id: Option<String>,
141    /// 文件名。
142    pub filename: Option<String>,
143    /// 相似度分数。
144    pub score: Option<f64>,
145    /// 额外字段。
146    #[serde(flatten)]
147    pub extra: BTreeMap<String, Value>,
148}
149
150/// 表示 vector store 对象。
151#[derive(Debug, Clone, Serialize, Deserialize, Default)]
152pub struct VectorStore {
153    /// 对象 ID。
154    pub id: String,
155    /// 对象类型。
156    #[serde(default)]
157    pub object: String,
158    /// 创建时间戳。
159    pub created_at: Option<u64>,
160    /// 描述。
161    pub description: Option<String>,
162    /// 名称。
163    pub name: Option<String>,
164    /// 状态。
165    pub status: Option<String>,
166    /// 最后活跃时间。
167    pub last_active_at: Option<u64>,
168    /// 占用字节数。
169    pub usage_bytes: Option<u64>,
170    /// 文件计数。
171    pub file_counts: Option<VectorStoreFileCounts>,
172    /// 元数据。
173    pub metadata: Option<VectorStoreMetadata>,
174    /// 过期策略。
175    pub expires_after: Option<VectorStoreExpiresAfter>,
176    /// 过期时间。
177    pub expires_at: Option<u64>,
178    /// 额外字段。
179    #[serde(flatten)]
180    pub extra: BTreeMap<String, Value>,
181}
182
183/// 表示 vector store 文件对象。
184#[derive(Debug, Clone, Serialize, Deserialize, Default)]
185pub struct VectorStoreFile {
186    /// 对象 ID。
187    pub id: String,
188    /// 对象类型。
189    #[serde(default)]
190    pub object: String,
191    /// 创建时间戳。
192    pub created_at: Option<u64>,
193    /// 关联的 vector store ID。
194    pub vector_store_id: Option<String>,
195    /// 状态。
196    pub status: Option<String>,
197    /// 最近错误。
198    pub last_error: Option<VectorStoreFileLastError>,
199    /// 占用字节数。
200    pub usage_bytes: Option<u64>,
201    /// 属性。
202    pub attributes: Option<VectorStoreAttributes>,
203    /// 分块策略。
204    pub chunking_strategy: Option<VectorStoreFileChunkingStrategy>,
205    /// 额外字段。
206    #[serde(flatten)]
207    pub extra: BTreeMap<String, Value>,
208}
209
210/// 表示 vector store file batch 对象。
211#[derive(Debug, Clone, Serialize, Deserialize, Default)]
212pub struct VectorStoreFileBatch {
213    /// 对象 ID。
214    pub id: String,
215    /// 对象类型。
216    #[serde(default)]
217    pub object: String,
218    /// 创建时间戳。
219    pub created_at: Option<u64>,
220    /// 关联的 vector store ID。
221    pub vector_store_id: Option<String>,
222    /// 状态。
223    pub status: Option<String>,
224    /// 文件计数。
225    pub file_counts: Option<VectorStoreFileCounts>,
226    /// 额外字段。
227    #[serde(flatten)]
228    pub extra: BTreeMap<String, Value>,
229}
230
231/// 表示 vector store 搜索返回值。
232#[derive(Debug, Clone, Serialize, Deserialize, Default)]
233pub struct VectorStoreSearchResponse {
234    /// 对象类型。
235    #[serde(default)]
236    pub object: String,
237    /// 搜索结果。
238    #[serde(default)]
239    pub data: Vec<VectorStoreSearchResult>,
240    /// 搜索查询。
241    pub search_query: Option<String>,
242    /// 额外字段。
243    #[serde(flatten)]
244    pub extra: BTreeMap<String, Value>,
245}
246
247impl VectorStoresResource {
248    /// 创建 vector store。
249    pub fn create(&self) -> JsonRequestBuilder<VectorStore> {
250        let endpoint = endpoints::vector_stores::VECTOR_STORES_CREATE;
251        vector_store_json(
252            self.client.clone(),
253            endpoint.id,
254            Method::POST,
255            endpoint.template,
256        )
257    }
258
259    /// 获取 vector store。
260    pub fn retrieve(&self, vector_store_id: impl Into<String>) -> JsonRequestBuilder<VectorStore> {
261        let vector_store_id = encode_path_segment(vector_store_id.into());
262        let endpoint = endpoints::vector_stores::VECTOR_STORES_RETRIEVE;
263        vector_store_json(
264            self.client.clone(),
265            endpoint.id,
266            Method::GET,
267            endpoint.render(&[("vector_store_id", &vector_store_id)]),
268        )
269    }
270
271    /// 更新 vector store。
272    pub fn update(&self, vector_store_id: impl Into<String>) -> JsonRequestBuilder<VectorStore> {
273        let vector_store_id = encode_path_segment(vector_store_id.into());
274        let endpoint = endpoints::vector_stores::VECTOR_STORES_UPDATE;
275        vector_store_json(
276            self.client.clone(),
277            endpoint.id,
278            Method::POST,
279            endpoint.render(&[("vector_store_id", &vector_store_id)]),
280        )
281    }
282
283    /// 列出 vector store。
284    pub fn list(&self) -> ListRequestBuilder<VectorStore> {
285        let endpoint = endpoints::vector_stores::VECTOR_STORES_LIST;
286        vector_store_list(self.client.clone(), endpoint.id, endpoint.template)
287    }
288
289    /// 删除 vector store。
290    pub fn delete(&self, vector_store_id: impl Into<String>) -> JsonRequestBuilder<DeleteResponse> {
291        let vector_store_id = encode_path_segment(vector_store_id.into());
292        let endpoint = endpoints::vector_stores::VECTOR_STORES_DELETE;
293        vector_store_json(
294            self.client.clone(),
295            endpoint.id,
296            Method::DELETE,
297            endpoint.render(&[("vector_store_id", &vector_store_id)]),
298        )
299    }
300
301    /// 搜索 vector store。
302    pub fn search(
303        &self,
304        vector_store_id: impl Into<String>,
305    ) -> JsonRequestBuilder<VectorStoreSearchResponse> {
306        let vector_store_id = encode_path_segment(vector_store_id.into());
307        let endpoint = endpoints::vector_stores::VECTOR_STORES_SEARCH;
308        vector_store_json(
309            self.client.clone(),
310            endpoint.id,
311            Method::POST,
312            endpoint.render(&[("vector_store_id", &vector_store_id)]),
313        )
314    }
315
316    /// 返回 files 子资源。
317    pub fn files(&self) -> VectorStoreFilesResource {
318        VectorStoreFilesResource::new(self.client.clone())
319    }
320
321    /// 返回 file_batches 子资源。
322    pub fn file_batches(&self) -> VectorStoreFileBatchesResource {
323        VectorStoreFileBatchesResource::new(self.client.clone())
324    }
325}
326
327impl VectorStoreFilesResource {
328    /// 创建 vector store 文件。
329    pub fn create(
330        &self,
331        vector_store_id: impl Into<String>,
332    ) -> JsonRequestBuilder<VectorStoreFile> {
333        let vector_store_id = encode_path_segment(vector_store_id.into());
334        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILES_CREATE;
335        vector_store_json(
336            self.client.clone(),
337            endpoint.id,
338            Method::POST,
339            endpoint.render(&[("vector_store_id", &vector_store_id)]),
340        )
341    }
342
343    /// 获取 vector store 文件。
344    pub fn retrieve(
345        &self,
346        vector_store_id: impl Into<String>,
347        file_id: impl Into<String>,
348    ) -> JsonRequestBuilder<VectorStoreFile> {
349        let vector_store_id = encode_path_segment(vector_store_id.into());
350        let file_id = encode_path_segment(file_id.into());
351        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILES_RETRIEVE;
352        vector_store_json(
353            self.client.clone(),
354            endpoint.id,
355            Method::GET,
356            endpoint.render(&[("vector_store_id", &vector_store_id), ("file_id", &file_id)]),
357        )
358    }
359
360    /// 更新 vector store 文件。
361    pub fn update(
362        &self,
363        vector_store_id: impl Into<String>,
364        file_id: impl Into<String>,
365    ) -> JsonRequestBuilder<VectorStoreFile> {
366        let vector_store_id = encode_path_segment(vector_store_id.into());
367        let file_id = encode_path_segment(file_id.into());
368        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILES_UPDATE;
369        vector_store_json(
370            self.client.clone(),
371            endpoint.id,
372            Method::POST,
373            endpoint.render(&[("vector_store_id", &vector_store_id), ("file_id", &file_id)]),
374        )
375    }
376
377    /// 列出 vector store 文件。
378    pub fn list(&self, vector_store_id: impl Into<String>) -> ListRequestBuilder<VectorStoreFile> {
379        let vector_store_id = encode_path_segment(vector_store_id.into());
380        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILES_LIST;
381        vector_store_list(
382            self.client.clone(),
383            endpoint.id,
384            endpoint.render(&[("vector_store_id", &vector_store_id)]),
385        )
386    }
387
388    /// 删除 vector store 文件。
389    pub fn delete(
390        &self,
391        vector_store_id: impl Into<String>,
392        file_id: impl Into<String>,
393    ) -> JsonRequestBuilder<DeleteResponse> {
394        let vector_store_id = encode_path_segment(vector_store_id.into());
395        let file_id = encode_path_segment(file_id.into());
396        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILES_DELETE;
397        vector_store_json(
398            self.client.clone(),
399            endpoint.id,
400            Method::DELETE,
401            endpoint.render(&[("vector_store_id", &vector_store_id), ("file_id", &file_id)]),
402        )
403    }
404
405    /// 获取 vector store 文件内容。
406    pub fn content(
407        &self,
408        vector_store_id: impl Into<String>,
409        file_id: impl Into<String>,
410    ) -> JsonRequestBuilder<Page<VectorStoreFileContent>> {
411        let vector_store_id = encode_path_segment(vector_store_id.into());
412        let file_id = encode_path_segment(file_id.into());
413        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILES_CONTENT;
414        vector_store_json(
415            self.client.clone(),
416            endpoint.id,
417            Method::GET,
418            endpoint.render(&[("vector_store_id", &vector_store_id), ("file_id", &file_id)]),
419        )
420    }
421}
422
423impl VectorStoreFileBatchesResource {
424    /// 创建 file batch。
425    pub fn create(
426        &self,
427        vector_store_id: impl Into<String>,
428    ) -> JsonRequestBuilder<VectorStoreFileBatch> {
429        let vector_store_id = encode_path_segment(vector_store_id.into());
430        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILE_BATCHES_CREATE;
431        vector_store_json(
432            self.client.clone(),
433            endpoint.id,
434            Method::POST,
435            endpoint.render(&[("vector_store_id", &vector_store_id)]),
436        )
437    }
438
439    /// 获取 file batch。
440    pub fn retrieve(
441        &self,
442        vector_store_id: impl Into<String>,
443        batch_id: impl Into<String>,
444    ) -> JsonRequestBuilder<VectorStoreFileBatch> {
445        let vector_store_id = encode_path_segment(vector_store_id.into());
446        let batch_id = encode_path_segment(batch_id.into());
447        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILE_BATCHES_RETRIEVE;
448        vector_store_json(
449            self.client.clone(),
450            endpoint.id,
451            Method::GET,
452            endpoint.render(&[
453                ("vector_store_id", &vector_store_id),
454                ("batch_id", &batch_id),
455            ]),
456        )
457    }
458
459    /// 取消 file batch。
460    pub fn cancel(
461        &self,
462        vector_store_id: impl Into<String>,
463        batch_id: impl Into<String>,
464    ) -> JsonRequestBuilder<VectorStoreFileBatch> {
465        let vector_store_id = encode_path_segment(vector_store_id.into());
466        let batch_id = encode_path_segment(batch_id.into());
467        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILE_BATCHES_CANCEL;
468        vector_store_json(
469            self.client.clone(),
470            endpoint.id,
471            Method::POST,
472            endpoint.render(&[
473                ("vector_store_id", &vector_store_id),
474                ("batch_id", &batch_id),
475            ]),
476        )
477    }
478
479    /// 列出 file batch 文件。
480    pub fn list_files(
481        &self,
482        vector_store_id: impl Into<String>,
483        batch_id: impl Into<String>,
484    ) -> ListRequestBuilder<VectorStoreFile> {
485        let vector_store_id = encode_path_segment(vector_store_id.into());
486        let batch_id = encode_path_segment(batch_id.into());
487        let endpoint = endpoints::vector_stores::VECTOR_STORES_FILE_BATCHES_LIST_FILES;
488        vector_store_list(
489            self.client.clone(),
490            endpoint.id,
491            endpoint.render(&[
492                ("vector_store_id", &vector_store_id),
493                ("batch_id", &batch_id),
494            ]),
495        )
496    }
497}
498
499fn vector_store_json<T>(
500    client: crate::Client,
501    endpoint_id: &'static str,
502    method: Method,
503    path: impl Into<String>,
504) -> JsonRequestBuilder<T> {
505    JsonRequestBuilder::new(client, endpoint_id, method, path)
506        .extra_header("openai-beta", "assistants=v2")
507}
508
509fn vector_store_list<T>(
510    client: crate::Client,
511    endpoint_id: &'static str,
512    path: impl Into<String>,
513) -> ListRequestBuilder<T> {
514    ListRequestBuilder::new(client, endpoint_id, path).extra_header("openai-beta", "assistants=v2")
515}