linger-openai-sdk 0.1.1

Rust-native async SDK for OpenAI APIs with typed requests, streaming, uploads, retries, and pluggable transports.
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
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
use crate::error::LingerError;
use crate::RequestId;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

/// EN: Request body for `POST /v1/vector_stores`.
/// 中文:`POST /v1/vector_stores` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateVectorStoreRequest {
    /// EN: Optional vector store name.
    /// 中文:可选的向量存储名称。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// EN: Initial file ids to attach to the vector store.
    /// 中文:要附加到向量存储的初始文件 ID。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub file_ids: Vec<String>,
    /// EN: Optional metadata.
    /// 中文:可选元数据。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreRequest {
    /// EN: Starts building a vector store creation request.
    /// 中文:开始构建向量存储创建请求。
    pub fn builder() -> CreateVectorStoreRequestBuilder {
        CreateVectorStoreRequestBuilder::default()
    }
}

/// EN: Builder for vector store creation requests.
/// 中文:向量存储创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVectorStoreRequestBuilder {
    name: Option<String>,
    file_ids: Vec<String>,
    metadata: BTreeMap<String, String>,
    extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreRequestBuilder {
    /// EN: Sets the optional vector store name.
    /// 中文:设置可选的向量存储名称。
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// EN: Adds an initial file id.
    /// 中文:添加一个初始文件 ID。
    pub fn file_id(mut self, file_id: impl Into<String>) -> Self {
        self.file_ids.push(file_id.into());
        self
    }

    /// EN: Replaces the initial file id list.
    /// 中文:替换初始文件 ID 列表。
    pub fn file_ids(mut self, file_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.file_ids = file_ids.into_iter().map(Into::into).collect();
        self
    }

    /// EN: Adds a metadata key/value pair.
    /// 中文:添加一个元数据键值对。
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateVectorStoreRequest, LingerError> {
        validate_optional_string("name", self.name.as_deref())?;
        for file_id in &self.file_ids {
            if file_id.trim().is_empty() {
                return Err(LingerError::invalid_config(
                    "file_ids must not contain empty values",
                ));
            }
        }
        for key in self.metadata.keys() {
            if key.trim().is_empty() {
                return Err(LingerError::invalid_config(
                    "metadata keys must not be empty",
                ));
            }
        }
        Ok(CreateVectorStoreRequest {
            name: self.name,
            file_ids: self.file_ids,
            metadata: self.metadata,
            extra: self.extra,
        })
    }
}

/// EN: Request body for `POST /v1/vector_stores/{vector_store_id}`.
/// 中文:`POST /v1/vector_stores/{vector_store_id}` 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ModifyVectorStoreRequest {
    /// EN: Updated vector store name.
    /// 中文:更新后的向量存储名称。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// EN: Updated metadata.
    /// 中文:更新后的元数据。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, String>,
    /// EN: Updated expiration policy.
    /// 中文:更新后的过期策略。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_after: Option<Value>,
}

impl ModifyVectorStoreRequest {
    /// EN: Starts building a vector store modification request.
    /// 中文:开始构建向量存储修改请求。
    pub fn builder() -> ModifyVectorStoreRequestBuilder {
        ModifyVectorStoreRequestBuilder::default()
    }
}

/// EN: Builder for vector store modification requests.
/// 中文:向量存储修改请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ModifyVectorStoreRequestBuilder {
    name: Option<String>,
    metadata: BTreeMap<String, String>,
    expires_after: Option<Value>,
}

impl ModifyVectorStoreRequestBuilder {
    /// EN: Sets the updated vector store name.
    /// 中文:设置更新后的向量存储名称。
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// EN: Adds an updated metadata key/value pair.
    /// 中文:添加一个更新后的元数据键值对。
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// EN: Sets the updated expiration policy.
    /// 中文:设置更新后的过期策略。
    pub fn expires_after(mut self, expires_after: Value) -> Self {
        self.expires_after = Some(expires_after);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<ModifyVectorStoreRequest, LingerError> {
        validate_optional_string("name", self.name.as_deref())?;
        validate_metadata(&self.metadata)?;
        validate_optional_json_value("expires_after", self.expires_after.as_ref())?;
        Ok(ModifyVectorStoreRequest {
            name: self.name,
            metadata: self.metadata,
            expires_after: self.expires_after,
        })
    }
}

/// EN: Request body for `POST /v1/vector_stores/{vector_store_id}/files`.
/// 中文:`POST /v1/vector_stores/{vector_store_id}/files` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateVectorStoreFileRequest {
    /// EN: File id to attach to the vector store.
    /// 中文:要附加到向量存储的文件 ID。
    pub file_id: String,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreFileRequest {
    /// EN: Starts building a vector store file request.
    /// 中文:开始构建向量存储文件请求。
    pub fn builder() -> CreateVectorStoreFileRequestBuilder {
        CreateVectorStoreFileRequestBuilder::default()
    }
}

/// EN: Builder for vector store file requests.
/// 中文:向量存储文件请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVectorStoreFileRequestBuilder {
    file_id: Option<String>,
    extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreFileRequestBuilder {
    /// EN: Sets the file id to attach.
    /// 中文:设置要附加的文件 ID。
    pub fn file_id(mut self, file_id: impl Into<String>) -> Self {
        self.file_id = Some(file_id.into());
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateVectorStoreFileRequest, LingerError> {
        Ok(CreateVectorStoreFileRequest {
            file_id: required_string("file_id", self.file_id)?,
            extra: self.extra,
        })
    }
}

/// EN: Request body for `POST /v1/vector_stores/{vector_store_id}/files/{file_id}`.
/// 中文:`POST /v1/vector_stores/{vector_store_id}/files/{file_id}` 的请求体。
#[derive(Clone, Debug, Default, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ModifyVectorStoreFileRequest {
    /// EN: Updated file attributes.
    /// 中文:更新后的文件属性。
    pub attributes: BTreeMap<String, Value>,
}

impl ModifyVectorStoreFileRequest {
    /// EN: Starts building a vector store file modification request.
    /// 中文:开始构建向量存储文件修改请求。
    pub fn builder() -> ModifyVectorStoreFileRequestBuilder {
        ModifyVectorStoreFileRequestBuilder::default()
    }
}

/// EN: Builder for vector store file modification requests.
/// 中文:向量存储文件修改请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ModifyVectorStoreFileRequestBuilder {
    attributes: BTreeMap<String, Value>,
}

impl ModifyVectorStoreFileRequestBuilder {
    /// EN: Adds an updated file attribute.
    /// 中文:添加一个更新后的文件属性。
    pub fn attribute(mut self, key: impl Into<String>, value: Value) -> Self {
        self.attributes.insert(key.into(), value);
        self
    }

    /// EN: Replaces all updated file attributes.
    /// 中文:替换全部更新后的文件属性。
    pub fn attributes(mut self, attributes: BTreeMap<String, Value>) -> Self {
        self.attributes = attributes;
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<ModifyVectorStoreFileRequest, LingerError> {
        validate_attributes(&self.attributes, true)?;
        Ok(ModifyVectorStoreFileRequest {
            attributes: self.attributes,
        })
    }
}

/// EN: Request body for `POST /v1/vector_stores/{vector_store_id}/file_batches`.
/// 中文:`POST /v1/vector_stores/{vector_store_id}/file_batches` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateVectorStoreFileBatchRequest {
    /// EN: File ids to add to the vector store.
    /// 中文:要添加到向量存储的文件 ID。
    pub file_ids: Vec<String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreFileBatchRequest {
    /// EN: Starts building a vector store file batch request.
    /// 中文:开始构建向量存储文件批量请求。
    pub fn builder() -> CreateVectorStoreFileBatchRequestBuilder {
        CreateVectorStoreFileBatchRequestBuilder::default()
    }
}

/// EN: Builder for vector store file batch requests.
/// 中文:向量存储文件批量请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVectorStoreFileBatchRequestBuilder {
    file_ids: Vec<String>,
    extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreFileBatchRequestBuilder {
    /// EN: Adds a file id to the batch.
    /// 中文:向批量请求添加文件 ID。
    pub fn file_id(mut self, file_id: impl Into<String>) -> Self {
        self.file_ids.push(file_id.into());
        self
    }

    /// EN: Replaces the file id list.
    /// 中文:替换文件 ID 列表。
    pub fn file_ids(mut self, file_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.file_ids = file_ids.into_iter().map(Into::into).collect();
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateVectorStoreFileBatchRequest, LingerError> {
        validate_non_empty_values("file_ids", &self.file_ids)?;
        Ok(CreateVectorStoreFileBatchRequest {
            file_ids: self.file_ids,
            extra: self.extra,
        })
    }
}

/// EN: Request body for `POST /v1/vector_stores/{vector_store_id}/search`.
/// 中文:`POST /v1/vector_stores/{vector_store_id}/search` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateVectorStoreSearchRequest {
    /// EN: Search query text.
    /// 中文:搜索查询文本。
    pub query: String,
    /// EN: Optional maximum number of search results.
    /// 中文:可选的最大搜索结果数量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_num_results: Option<u32>,
    /// EN: Optional metadata filter expression.
    /// 中文:可选的元数据过滤表达式。
    #[serde(rename = "filters", skip_serializing_if = "Option::is_none")]
    pub filter: Option<Value>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreSearchRequest {
    /// EN: Starts building a vector store search request.
    /// 中文:开始构建向量存储搜索请求。
    pub fn builder() -> CreateVectorStoreSearchRequestBuilder {
        CreateVectorStoreSearchRequestBuilder::default()
    }
}

/// EN: Builder for vector store search requests.
/// 中文:向量存储搜索请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateVectorStoreSearchRequestBuilder {
    query: Option<String>,
    max_num_results: Option<u32>,
    filter: Option<Value>,
    extra: BTreeMap<String, Value>,
}

impl CreateVectorStoreSearchRequestBuilder {
    /// EN: Sets the search query.
    /// 中文:设置搜索查询。
    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// EN: Sets the maximum number of search results.
    /// 中文:设置最大搜索结果数量。
    pub fn max_num_results(mut self, max_num_results: u32) -> Self {
        self.max_num_results = Some(max_num_results);
        self
    }

    /// EN: Sets a metadata filter expression.
    /// 中文:设置元数据过滤表达式。
    pub fn filter(mut self, filter: Value) -> Self {
        self.filter = Some(filter);
        self
    }

    /// EN: Adds a forward-compatible JSON field.
    /// 中文:添加前向兼容的 JSON 字段。
    pub fn extra(mut self, name: impl Into<String>, value: Value) -> Self {
        self.extra.insert(name.into(), value);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateVectorStoreSearchRequest, LingerError> {
        let query = required_string("query", self.query)?;
        if self
            .max_num_results
            .is_some_and(|value| !(1..=50).contains(&value))
        {
            return Err(LingerError::invalid_config(
                "max_num_results must be between 1 and 50",
            ));
        }
        if self.filter.as_ref().is_some_and(Value::is_null) {
            return Err(LingerError::invalid_config("filters must not be null"));
        }
        validate_extra_fields(&self.extra)?;
        Ok(CreateVectorStoreSearchRequest {
            query,
            max_num_results: self.max_num_results,
            filter: self.filter,
            extra: self.extra,
        })
    }
}

/// EN: Vector store object returned by the Vector Stores API.
/// 中文:Vector Stores API 返回的向量存储对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStore {
    /// EN: Vector store id.
    /// 中文:向量存储 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Vector store name, when returned.
    /// 中文:向量存储名称,如响应中存在。
    #[serde(default)]
    pub name: Option<String>,
    /// EN: Bytes used by the vector store.
    /// 中文:向量存储使用的字节数。
    #[serde(default, alias = "usage_bytes")]
    pub bytes: u64,
    /// EN: File count summary.
    /// 中文:文件数量汇总。
    pub file_counts: VectorStoreFileCounts,
    /// EN: Vector store status.
    /// 中文:向量存储状态。
    pub status: String,
    /// EN: Expiration policy, when returned.
    /// 中文:过期策略,如响应中存在。
    #[serde(default)]
    pub expires_after: Option<Value>,
    /// EN: Unix timestamp for expiration, when returned.
    /// 中文:过期时间的 Unix 时间戳,如响应中存在。
    #[serde(default)]
    pub expires_at: Option<u64>,
    /// EN: Last active timestamp, when returned.
    /// 中文:最后活跃时间戳,如响应中存在。
    #[serde(default)]
    pub last_active_at: Option<u64>,
    /// EN: Metadata returned by the API.
    /// 中文:API 返回的元数据。
    #[serde(default)]
    pub metadata: BTreeMap<String, String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStore {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: File count summary for a vector store.
/// 中文:向量存储的文件数量汇总。
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VectorStoreFileCounts {
    /// EN: Number of files still processing.
    /// 中文:仍在处理的文件数量。
    pub in_progress: u64,
    /// EN: Number of completed files.
    /// 中文:已完成文件数量。
    pub completed: u64,
    /// EN: Number of failed files.
    /// 中文:失败文件数量。
    pub failed: u64,
    /// EN: Number of cancelled files.
    /// 中文:已取消文件数量。
    pub cancelled: u64,
    /// EN: Total file count.
    /// 中文:文件总数。
    pub total: u64,
}

/// EN: Vector store file object returned by the Vector Store Files API.
/// 中文:Vector Store Files API 返回的向量存储文件对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreFile {
    /// EN: File id.
    /// 中文:文件 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Parent vector store id.
    /// 中文:父向量存储 ID。
    pub vector_store_id: String,
    /// EN: File status in the vector store.
    /// 中文:文件在向量存储中的状态。
    pub status: String,
    /// EN: Last file processing error, when returned.
    /// 中文:最后一次文件处理错误,如响应中存在。
    #[serde(default)]
    pub last_error: Option<Value>,
    /// EN: Bytes used by this vector store file.
    /// 中文:此向量存储文件使用的字节数。
    #[serde(default)]
    pub usage_bytes: u64,
    /// EN: Chunking strategy returned by the API, when present.
    /// 中文:API 返回的分块策略,如存在。
    #[serde(default)]
    pub chunking_strategy: Option<Value>,
    /// EN: File attributes returned by the API.
    /// 中文:API 返回的文件属性。
    #[serde(default)]
    pub attributes: BTreeMap<String, Value>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreFile {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Paginated vector store file list.
/// 中文:分页向量存储文件列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreFilePage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Files on this page.
    /// 中文:本页文件。
    #[serde(default)]
    pub data: Vec<VectorStoreFile>,
    /// EN: First file id on this page.
    /// 中文:本页第一个文件 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last file id on this page.
    /// 中文:本页最后一个文件 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more files are available.
    /// 中文:是否还有更多文件。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreFilePage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Parsed content block returned for a vector store file.
/// 中文:向量存储文件返回的已解析内容块。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreFileContent {
    /// EN: Content type, currently usually `text`.
    /// 中文:内容类型,目前通常为 `text`。
    #[serde(default)]
    pub r#type: Option<String>,
    /// EN: Text content, when returned.
    /// 中文:文本内容,如响应中存在。
    #[serde(default)]
    pub text: Option<String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Page of parsed vector store file content blocks.
/// 中文:向量存储文件已解析内容块的分页结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreFileContentPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Parsed content blocks on this page.
    /// 中文:本页中的已解析内容块。
    #[serde(default)]
    pub data: Vec<VectorStoreFileContent>,
    /// EN: Whether more content blocks are available.
    /// 中文:是否还有更多内容块。
    #[serde(default)]
    pub has_more: bool,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreFileContentPage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Single vector store search result.
/// 中文:单个向量存储搜索结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreSearchResult {
    /// EN: File id that produced the result.
    /// 中文:产生该结果的文件 ID。
    pub file_id: String,
    /// EN: File name, when returned.
    /// 中文:文件名,如响应中存在。
    #[serde(default)]
    pub filename: Option<String>,
    /// EN: Search relevance score, when returned.
    /// 中文:搜索相关性分数,如响应中存在。
    #[serde(default)]
    pub score: Option<f64>,
    /// EN: Result content blocks returned by the API.
    /// 中文:API 返回的结果内容块。
    #[serde(default)]
    pub content: Vec<Value>,
    /// EN: File attributes returned with the result.
    /// 中文:结果附带的文件属性。
    #[serde(default)]
    pub attributes: BTreeMap<String, Value>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Paginated vector store search results.
/// 中文:分页向量存储搜索结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreSearchPage {
    /// EN: API page object type.
    /// 中文:API 分页对象类型。
    pub object: String,
    /// EN: Search results on this page.
    /// 中文:本页搜索结果。
    #[serde(default)]
    pub data: Vec<VectorStoreSearchResult>,
    /// EN: Whether more search results are available.
    /// 中文:是否还有更多搜索结果。
    pub has_more: bool,
    /// EN: Cursor for the next page, when returned.
    /// 中文:下一页游标,如响应中存在。
    #[serde(default)]
    pub next_page: Option<String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreSearchPage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Deletion result returned by the Vector Store Files API.
/// 中文:Vector Store Files API 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VectorStoreFileDeletion {
    /// EN: Deleted file id.
    /// 中文:已删除的文件 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Whether the vector store file was deleted.
    /// 中文:向量存储文件是否已删除。
    pub deleted: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreFileDeletion {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Vector store file batch object returned by the File Batches API.
/// 中文:File Batches API 返回的向量存储文件批量对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStoreFileBatch {
    /// EN: File batch id.
    /// 中文:文件批量 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Parent vector store id.
    /// 中文:父向量存储 ID。
    pub vector_store_id: String,
    /// EN: File batch status.
    /// 中文:文件批量状态。
    pub status: String,
    /// EN: File count summary.
    /// 中文:文件数量汇总。
    pub file_counts: VectorStoreFileCounts,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreFileBatch {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Paginated vector store list returned by the Vector Stores API.
/// 中文:Vector Stores API 返回的分页向量存储列表。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct VectorStorePage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Vector stores on this page.
    /// 中文:本页向量存储。
    #[serde(default)]
    pub data: Vec<VectorStore>,
    /// EN: First vector store id on this page.
    /// 中文:本页第一个向量存储 ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last vector store id on this page.
    /// 中文:本页最后一个向量存储 ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more vector stores are available.
    /// 中文:是否还有更多向量存储。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStorePage {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

/// EN: Deletion result returned by the Vector Stores API.
/// 中文:Vector Stores API 返回的删除结果。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct VectorStoreDeletion {
    /// EN: Deleted vector store id.
    /// 中文:已删除的向量存储 ID。
    pub id: String,
    /// EN: API object type.
    /// 中文:API 对象类型。
    pub object: String,
    /// EN: Whether the vector store was deleted.
    /// 中文:向量存储是否已删除。
    pub deleted: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl VectorStoreDeletion {
    pub(crate) fn with_request_id(mut self, request_id: Option<RequestId>) -> Self {
        self.request_id = request_id;
        self
    }

    /// EN: Returns the OpenAI request id, when present.
    /// 中文:返回 OpenAI 请求 ID,如存在。
    pub fn request_id(&self) -> Option<&RequestId> {
        self.request_id.as_ref()
    }
}

fn validate_optional_string(name: &str, value: Option<&str>) -> Result<(), LingerError> {
    if value.is_some_and(|value| value.trim().is_empty()) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not be empty"
        )));
    }
    Ok(())
}

fn validate_metadata(metadata: &BTreeMap<String, String>) -> Result<(), LingerError> {
    for key in metadata.keys() {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "metadata keys must not be empty",
            ));
        }
    }
    Ok(())
}

fn validate_optional_json_value(name: &str, value: Option<&Value>) -> Result<(), LingerError> {
    if value.is_some_and(Value::is_null) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not be null"
        )));
    }
    Ok(())
}

fn validate_attributes(
    attributes: &BTreeMap<String, Value>,
    require_non_empty: bool,
) -> Result<(), LingerError> {
    if require_non_empty && attributes.is_empty() {
        return Err(LingerError::invalid_config("attributes are required"));
    }
    for (key, value) in attributes {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "attribute names must not be empty",
            ));
        }
        if !(value.is_string() || value.is_number() || value.is_boolean()) {
            return Err(LingerError::invalid_config(format!(
                "attribute {key} must be a string, number, or boolean"
            )));
        }
    }
    Ok(())
}

fn required_string(name: &str, value: Option<String>) -> Result<String, LingerError> {
    value
        .filter(|value| !value.trim().is_empty())
        .ok_or_else(|| LingerError::invalid_config(format!("{name} is required")))
}

fn validate_non_empty_values(name: &str, values: &[String]) -> Result<(), LingerError> {
    if values.is_empty() {
        return Err(LingerError::invalid_config(format!("{name} is required")));
    }
    if values.iter().any(|value| value.trim().is_empty()) {
        return Err(LingerError::invalid_config(format!(
            "{name} must not contain empty values"
        )));
    }
    Ok(())
}

fn validate_extra_fields(extra: &BTreeMap<String, Value>) -> Result<(), LingerError> {
    for (key, value) in extra {
        if key.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "extra field names must not be empty",
            ));
        }
        if value.is_null() {
            return Err(LingerError::invalid_config(format!(
                "extra field {key} must not be null"
            )));
        }
    }
    Ok(())
}