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
use crate::transport::{BodyStream, HttpRequest};
use crate::LingerError;
use crate::RequestId;
use bytes::Bytes;
use serde::{Deserialize, Serialize};

/// EN: Skill metadata returned by the Skills API.
/// 中文:Skills API 返回的 skill 元数据。
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skill {
    /// EN: Unique skill identifier.
    /// 中文:唯一 skill 标识符。
    pub id: String,
    /// EN: API object type, normally `skill`.
    /// 中文:API 对象类型,通常为 `skill`。
    pub object: String,
    /// EN: Skill name.
    /// 中文:Skill 名称。
    pub name: String,
    /// EN: Skill description.
    /// 中文:Skill 描述。
    pub description: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Default skill version.
    /// 中文:默认 skill 版本。
    pub default_version: String,
    /// EN: Latest skill version.
    /// 中文:最新 skill 版本。
    pub latest_version: String,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl Skill {
    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: Page of skills returned by `GET /v1/skills`.
/// 中文:`GET /v1/skills` 返回的 skill 分页。
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Skills on this page.
    /// 中文:本页 skill。
    #[serde(default)]
    pub data: Vec<Skill>,
    /// EN: First skill id on this page.
    /// 中文:本页第一个 skill ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last skill id on this page.
    /// 中文:本页最后一个 skill ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more skills are available.
    /// 中文:是否还有更多 skill。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl SkillPage {
    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: Sort order for skill list pagination.
/// 中文:skill 列表分页的排序方向。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkillListOrder {
    /// EN: Ascending order.
    /// 中文:升序。
    Asc,
    /// EN: Descending order.
    /// 中文:降序。
    Desc,
}

impl SkillListOrder {
    pub(crate) fn as_query_value(self) -> &'static str {
        match self {
            Self::Asc => "asc",
            Self::Desc => "desc",
        }
    }
}

/// EN: Query parameters for `GET /v1/skills`.
/// 中文:`GET /v1/skills` 的查询参数。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillListRequest {
    /// EN: Maximum number of items to retrieve.
    /// 中文:要获取的最大条目数。
    pub limit: Option<u8>,
    /// EN: Sort order by timestamp.
    /// 中文:按时间戳排序的方向。
    pub order: Option<SkillListOrder>,
    /// EN: Cursor after which the next page starts.
    /// 中文:下一页开始位置之前的游标。
    pub after: Option<String>,
}

impl SkillListRequest {
    /// EN: Starts building skill list query parameters.
    /// 中文:开始构建 skill 列表查询参数。
    pub fn builder() -> SkillListRequestBuilder {
        SkillListRequestBuilder::default()
    }

    pub(crate) fn path(&self) -> String {
        path_with_query(
            "/v1/skills",
            ListQuery {
                limit: self.limit,
                order: self.order.map(SkillListOrder::as_query_value),
                after: self.after.as_deref(),
            },
        )
    }
}

/// EN: Builder for skill list query parameters.
/// 中文:skill 列表查询参数构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct SkillListRequestBuilder {
    limit: Option<u8>,
    order: Option<SkillListOrder>,
    after: Option<String>,
}

impl SkillListRequestBuilder {
    /// EN: Sets the maximum number of items to retrieve.
    /// 中文:设置要获取的最大条目数。
    pub fn limit(mut self, limit: u8) -> Self {
        self.limit = Some(limit);
        self
    }

    /// EN: Sets the sort order by timestamp.
    /// 中文:设置按时间戳排序的方向。
    pub fn order(mut self, order: SkillListOrder) -> Self {
        self.order = Some(order);
        self
    }

    /// EN: Sets the cursor after which the next page starts.
    /// 中文:设置下一页开始位置之前的游标。
    pub fn after(mut self, after: impl Into<String>) -> Self {
        self.after = Some(after.into());
        self
    }

    /// EN: Builds and validates the query parameters.
    /// 中文:构建并校验查询参数。
    pub fn build(self) -> Result<SkillListRequest, LingerError> {
        if let Some(limit) = self.limit {
            if limit == 0 || limit > 100 {
                return Err(LingerError::invalid_config(
                    "limit must be between 1 and 100",
                ));
            }
        }
        if let Some(after) = &self.after {
            if after.trim().is_empty() {
                return Err(LingerError::invalid_config("after must not be empty"));
            }
        }
        Ok(SkillListRequest {
            limit: self.limit,
            order: self.order,
            after: self.after,
        })
    }
}

/// EN: Sort order for skill version list pagination.
/// 中文:skill version 列表分页的排序方向。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkillVersionListOrder {
    /// EN: Ascending order.
    /// 中文:升序。
    Asc,
    /// EN: Descending order.
    /// 中文:降序。
    Desc,
}

impl SkillVersionListOrder {
    pub(crate) fn as_query_value(self) -> &'static str {
        match self {
            Self::Asc => "asc",
            Self::Desc => "desc",
        }
    }
}

/// EN: Query parameters for `GET /v1/skills/{skill_id}/versions`.
/// 中文:`GET /v1/skills/{skill_id}/versions` 的查询参数。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillVersionListRequest {
    /// EN: Maximum number of versions to retrieve.
    /// 中文:要获取的最大版本数量。
    pub limit: Option<u8>,
    /// EN: Sort order by version number.
    /// 中文:按版本号排序的方向。
    pub order: Option<SkillVersionListOrder>,
    /// EN: Skill version ID after which the next page starts.
    /// 中文:下一页开始位置之前的 skill version ID。
    pub after: Option<String>,
}

impl SkillVersionListRequest {
    /// EN: Starts building skill version list query parameters.
    /// 中文:开始构建 skill version 列表查询参数。
    pub fn builder() -> SkillVersionListRequestBuilder {
        SkillVersionListRequestBuilder::default()
    }

    pub(crate) fn path(&self, skill_id: &str) -> String {
        let base = format!("/v1/skills/{skill_id}/versions");
        path_with_query(
            &base,
            ListQuery {
                limit: self.limit,
                order: self.order.map(SkillVersionListOrder::as_query_value),
                after: self.after.as_deref(),
            },
        )
    }
}

/// EN: Builder for skill version list query parameters.
/// 中文:skill version 列表查询参数构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct SkillVersionListRequestBuilder {
    limit: Option<u8>,
    order: Option<SkillVersionListOrder>,
    after: Option<String>,
}

impl SkillVersionListRequestBuilder {
    /// EN: Sets the maximum number of versions to retrieve.
    /// 中文:设置要获取的最大版本数量。
    pub fn limit(mut self, limit: u8) -> Self {
        self.limit = Some(limit);
        self
    }

    /// EN: Sets the sort order by version number.
    /// 中文:设置按版本号排序的方向。
    pub fn order(mut self, order: SkillVersionListOrder) -> Self {
        self.order = Some(order);
        self
    }

    /// EN: Sets the skill version ID after which the next page starts.
    /// 中文:设置下一页开始位置之前的 skill version ID。
    pub fn after(mut self, after: impl Into<String>) -> Self {
        self.after = Some(after.into());
        self
    }

    /// EN: Builds and validates the query parameters.
    /// 中文:构建并校验查询参数。
    pub fn build(self) -> Result<SkillVersionListRequest, LingerError> {
        if let Some(limit) = self.limit {
            if limit == 0 || limit > 100 {
                return Err(LingerError::invalid_config(
                    "limit must be between 1 and 100",
                ));
            }
        }
        if let Some(after) = &self.after {
            if after.trim().is_empty() {
                return Err(LingerError::invalid_config("after must not be empty"));
            }
        }
        Ok(SkillVersionListRequest {
            limit: self.limit,
            order: self.order,
            after: self.after,
        })
    }
}

/// EN: Request body descriptor for `POST /v1/skills`.
/// 中文:`POST /v1/skills` 的请求体描述。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateSkillRequest {
    /// EN: Skill bundle file sent as the multipart `files` field.
    /// 中文:作为 multipart `files` 字段发送的 skill bundle 文件。
    pub file: SkillUpload,
}

impl CreateSkillRequest {
    /// EN: Starts building a skill creation request.
    /// 中文:开始构建 skill 创建请求。
    pub fn builder() -> CreateSkillRequestBuilder {
        CreateSkillRequestBuilder::default()
    }

    pub(crate) fn apply_multipart_body(&self, request: &mut HttpRequest) {
        let boundary = multipart_boundary(&self.file.content);
        request.insert_header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        );
        request.set_body_stream(self.multipart_stream(boundary));
    }

    fn multipart_stream(
        &self,
        boundary: String,
    ) -> impl futures_core::Stream<Item = Result<Bytes, LingerError>> {
        let mut chunks = Vec::new();
        push_file_field(&mut chunks, &boundary, "files", &self.file);
        chunks.push(Ok(Bytes::from(format!("--{boundary}--\r\n"))));
        futures_util::stream::iter(chunks)
    }
}

/// EN: Builder for skill creation requests.
/// 中文:skill 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateSkillRequestBuilder {
    file: Option<SkillUpload>,
}

impl CreateSkillRequestBuilder {
    /// EN: Sets the skill bundle file to upload.
    /// 中文:设置要上传的 skill bundle 文件。
    pub fn file(mut self, file: SkillUpload) -> Self {
        self.file = Some(file);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateSkillRequest, LingerError> {
        let file = self
            .file
            .ok_or_else(|| LingerError::invalid_config("file is required"))?;
        Ok(CreateSkillRequest { file })
    }
}

/// EN: Request body for `POST /v1/skills/{skill_id}`.
/// 中文:`POST /v1/skills/{skill_id}` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct UpdateSkillRequest {
    /// EN: Skill version number to set as the default.
    /// 中文:要设置为默认版本的 skill version 编号。
    pub default_version: String,
}

impl UpdateSkillRequest {
    /// EN: Returns a builder for skill update requests.
    /// 中文:返回 skill update 请求的构建器。
    pub fn builder() -> UpdateSkillRequestBuilder {
        UpdateSkillRequestBuilder::default()
    }
}

/// EN: Builder for `UpdateSkillRequest`.
/// 中文:`UpdateSkillRequest` 的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct UpdateSkillRequestBuilder {
    default_version: Option<String>,
}

impl UpdateSkillRequestBuilder {
    /// EN: Sets the skill version number to make default.
    /// 中文:设置要作为默认版本的 skill version 编号。
    pub fn default_version(mut self, default_version: impl Into<String>) -> Self {
        self.default_version = Some(default_version.into());
        self
    }

    /// EN: Builds a validated skill update request.
    /// 中文:构建经过校验的 skill update 请求。
    pub fn build(self) -> Result<UpdateSkillRequest, LingerError> {
        let default_version = self
            .default_version
            .ok_or_else(|| LingerError::invalid_config("default_version is required"))?;
        if default_version.trim().is_empty() {
            return Err(LingerError::invalid_config(
                "default_version must not be empty",
            ));
        }
        Ok(UpdateSkillRequest { default_version })
    }
}

/// EN: Request body descriptor for `POST /v1/skills/{skill_id}/versions`.
/// 中文:`POST /v1/skills/{skill_id}/versions` 的请求体描述。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateSkillVersionRequest {
    /// EN: Skill bundle file sent as the multipart `files` field.
    /// 中文:作为 multipart `files` 字段发送的 skill bundle 文件。
    pub file: SkillUpload,
    /// EN: Whether the uploaded version should become the default version.
    /// 中文:上传后的版本是否应设为默认版本。
    pub default: Option<bool>,
}

impl CreateSkillVersionRequest {
    /// EN: Starts building a skill version creation request.
    /// 中文:开始构建 skill version 创建请求。
    pub fn builder() -> CreateSkillVersionRequestBuilder {
        CreateSkillVersionRequestBuilder::default()
    }

    pub(crate) fn apply_multipart_body(&self, request: &mut HttpRequest) {
        let boundary = multipart_boundary(&self.file.content);
        request.insert_header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        );
        request.set_body_stream(self.multipart_stream(boundary));
    }

    fn multipart_stream(
        &self,
        boundary: String,
    ) -> impl futures_core::Stream<Item = Result<Bytes, LingerError>> {
        let mut chunks = Vec::new();
        if let Some(default) = self.default {
            push_text_field(&mut chunks, &boundary, "default", bool_field(default));
        }
        push_file_field(&mut chunks, &boundary, "files", &self.file);
        chunks.push(Ok(Bytes::from(format!("--{boundary}--\r\n"))));
        futures_util::stream::iter(chunks)
    }
}

/// EN: Builder for skill version creation requests.
/// 中文:skill version 创建请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateSkillVersionRequestBuilder {
    file: Option<SkillUpload>,
    default: Option<bool>,
}

impl CreateSkillVersionRequestBuilder {
    /// EN: Sets the skill bundle file to upload.
    /// 中文:设置要上传的 skill bundle 文件。
    pub fn file(mut self, file: SkillUpload) -> Self {
        self.file = Some(file);
        self
    }

    /// EN: Sets whether the uploaded version should become the default version.
    /// 中文:设置上传后的版本是否应设为默认版本。
    pub fn default_version(mut self, default: bool) -> Self {
        self.default = Some(default);
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateSkillVersionRequest, LingerError> {
        let file = self
            .file
            .ok_or_else(|| LingerError::invalid_config("file is required"))?;
        Ok(CreateSkillVersionRequest {
            file,
            default: self.default,
        })
    }
}

/// EN: Uploadable skill bundle bytes and multipart metadata.
/// 中文:可上传的 skill bundle 字节及 multipart 元数据。
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillUpload {
    /// EN: Filename sent in the multipart part.
    /// 中文:multipart 分段中发送的文件名。
    pub filename: String,
    /// EN: Content type sent for the skill bundle part.
    /// 中文:skill bundle 分段发送的内容类型。
    pub content_type: String,
    content: Bytes,
}

impl SkillUpload {
    /// EN: Creates an upload from already available bytes without copying them.
    /// 中文:通过已可用字节创建上传对象,不复制这些字节。
    pub fn from_bytes(
        filename: impl Into<String>,
        content: impl Into<Bytes>,
    ) -> Result<Self, LingerError> {
        let filename = filename.into();
        validate_header_param("filename", &filename)?;
        Ok(Self {
            filename,
            content_type: "application/zip".to_string(),
            content: content.into(),
        })
    }

    /// EN: Sets the skill bundle part content type.
    /// 中文:设置 skill bundle 分段的内容类型。
    pub fn content_type(mut self, content_type: impl Into<String>) -> Result<Self, LingerError> {
        let content_type = content_type.into();
        validate_header_value("content_type", &content_type)?;
        self.content_type = content_type;
        Ok(self)
    }

    /// EN: Returns the skill bundle bytes as a cheap `Bytes` clone.
    /// 中文:以廉价 `Bytes` 克隆返回 skill bundle 字节。
    pub fn bytes(&self) -> Bytes {
        self.content.clone()
    }
}

/// EN: Deletion result returned by `DELETE /v1/skills/{skill_id}`.
/// 中文:`DELETE /v1/skills/{skill_id}` 返回的删除结果。
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillDeletion {
    /// EN: API object type, normally `skill.deleted`.
    /// 中文:API 对象类型,通常为 `skill.deleted`。
    pub object: String,
    /// EN: Whether the skill was deleted.
    /// 中文:skill 是否已删除。
    pub deleted: bool,
    /// EN: Deleted skill id.
    /// 中文:已删除的 skill ID。
    pub id: String,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl SkillDeletion {
    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: Incremental skill bundle content response.
/// 中文:增量 skill bundle 内容响应。
pub struct SkillContent {
    request_id: Option<RequestId>,
    body: BodyStream,
}

impl SkillContent {
    pub(crate) fn new(request_id: Option<RequestId>, body: BodyStream) -> Self {
        Self { request_id, body }
    }

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

    /// EN: Consumes this response and returns the incremental content stream.
    /// 中文:消耗此响应并返回增量内容流。
    pub fn into_stream(self) -> BodyStream {
        self.body
    }
}

/// EN: Immutable skill version metadata returned by the Skills API.
/// 中文:Skills API 返回的不可变 skill version 元数据。
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillVersion {
    /// EN: API object type, normally `skill.version`.
    /// 中文:API 对象类型,通常为 `skill.version`。
    pub object: String,
    /// EN: Unique skill version identifier.
    /// 中文:唯一 skill version 标识符。
    pub id: String,
    /// EN: Parent skill identifier.
    /// 中文:父级 skill 标识符。
    pub skill_id: String,
    /// EN: Version number for this skill version.
    /// 中文:此 skill version 的版本号。
    pub version: String,
    /// EN: Unix timestamp for creation.
    /// 中文:创建时间的 Unix 时间戳。
    pub created_at: u64,
    /// EN: Skill version name.
    /// 中文:Skill version 名称。
    pub name: String,
    /// EN: Skill version description.
    /// 中文:Skill version 描述。
    pub description: String,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl SkillVersion {
    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: Page of skill versions returned by `GET /v1/skills/{skill_id}/versions`.
/// 中文:`GET /v1/skills/{skill_id}/versions` 返回的 skill version 分页。
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillVersionPage {
    /// EN: API list object type.
    /// 中文:API 列表对象类型。
    pub object: String,
    /// EN: Skill versions on this page.
    /// 中文:本页 skill version。
    #[serde(default)]
    pub data: Vec<SkillVersion>,
    /// EN: First skill version id on this page.
    /// 中文:本页第一个 skill version ID。
    #[serde(default)]
    pub first_id: Option<String>,
    /// EN: Last skill version id on this page.
    /// 中文:本页最后一个 skill version ID。
    #[serde(default)]
    pub last_id: Option<String>,
    /// EN: Whether more skill versions are available.
    /// 中文:是否还有更多 skill version。
    pub has_more: bool,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl SkillVersionPage {
    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 `DELETE /v1/skills/{skill_id}/versions/{version}`.
/// 中文:`DELETE /v1/skills/{skill_id}/versions/{version}` 返回的删除结果。
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkillVersionDeletion {
    /// EN: API object type, normally `skill.version.deleted`.
    /// 中文:API 对象类型,通常为 `skill.version.deleted`。
    pub object: String,
    /// EN: Whether the skill version was deleted.
    /// 中文:skill version 是否已删除。
    pub deleted: bool,
    /// EN: Deleted skill version id.
    /// 中文:已删除的 skill version ID。
    pub id: String,
    /// EN: Deleted skill version number.
    /// 中文:已删除的 skill version 版本号。
    pub version: String,
    /// EN: OpenAI request id from response headers.
    /// 中文:响应头中的 OpenAI 请求 ID。
    #[serde(skip)]
    request_id: Option<RequestId>,
}

impl SkillVersionDeletion {
    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 push_text_field(
    chunks: &mut Vec<Result<Bytes, LingerError>>,
    boundary: &str,
    name: &str,
    value: &str,
) {
    chunks.push(Ok(Bytes::from(format!(
        "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
    ))));
}

fn push_file_field(
    chunks: &mut Vec<Result<Bytes, LingerError>>,
    boundary: &str,
    field: &str,
    file: &SkillUpload,
) {
    chunks.push(Ok(Bytes::from(format!(
        "--{boundary}\r\nContent-Disposition: form-data; name=\"{field}\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
        escape_multipart_param(&file.filename),
        file.content_type
    ))));
    chunks.push(Ok(file.content.clone()));
    chunks.push(Ok(Bytes::from("\r\n")));
}

fn bool_field(value: bool) -> &'static str {
    if value {
        "true"
    } else {
        "false"
    }
}

fn multipart_boundary(content: &Bytes) -> String {
    for counter in 0.. {
        let boundary = format!("linger-openai-sdk-skill-boundary-{counter}");
        if !contains_bytes(content, boundary.as_bytes()) {
            return boundary;
        }
    }
    unreachable!("unbounded boundary counter")
}

fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() {
        return true;
    }
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

fn validate_header_param(name: &str, value: &str) -> Result<(), LingerError> {
    if value.trim().is_empty() {
        return Err(LingerError::invalid_config(format!("{name} is required")));
    }
    validate_header_value(name, value)
}

fn validate_header_value(name: &str, value: &str) -> Result<(), LingerError> {
    if value.contains('\r') || value.contains('\n') {
        return Err(LingerError::invalid_config(format!(
            "{name} must not contain CR or LF"
        )));
    }
    Ok(())
}

fn escape_multipart_param(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

fn encode_query_value(value: &str) -> String {
    let mut encoded = String::new();
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                encoded.push(byte as char);
            }
            _ => {
                const HEX: &[u8; 16] = b"0123456789ABCDEF";
                encoded.push('%');
                encoded.push(HEX[(byte >> 4) as usize] as char);
                encoded.push(HEX[(byte & 0x0F) as usize] as char);
            }
        }
    }
    encoded
}

struct ListQuery<'a> {
    limit: Option<u8>,
    order: Option<&'static str>,
    after: Option<&'a str>,
}

fn path_with_query(base: &str, params: ListQuery<'_>) -> String {
    let mut query = Vec::new();
    if let Some(limit) = params.limit {
        query.push(format!("limit={limit}"));
    }
    if let Some(order) = params.order {
        query.push(format!("order={order}"));
    }
    if let Some(after) = params.after {
        query.push(format!("after={}", encode_query_value(after)));
    }
    if query.is_empty() {
        base.to_string()
    } else {
        format!("{base}?{}", query.join("&"))
    }
}