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
use crate::error::LingerError;
use crate::transport::HttpRequest;
use crate::RequestId;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

/// EN: Request body for `POST /v1/images/generations`.
/// 中文:`POST /v1/images/generations` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateImageRequest {
    /// EN: Text prompt describing the image to generate.
    /// 中文:描述要生成图像的文本提示。
    pub prompt: String,
    /// EN: Optional image generation model id.
    /// 中文:可选的图像生成模型 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// EN: Optional number of images to generate.
    /// 中文:可选的生成图像数量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,
    /// EN: Optional background mode.
    /// 中文:可选的背景模式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<String>,
    /// EN: Optional image moderation level.
    /// 中文:可选的图像审核级别。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub moderation: Option<String>,
    /// EN: Optional output image format.
    /// 中文:可选的输出图像格式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_format: Option<String>,
    /// EN: Optional output compression percentage.
    /// 中文:可选的输出压缩百分比。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_compression: Option<u8>,
    /// EN: Optional output quality.
    /// 中文:可选的输出质量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<String>,
    /// EN: Optional response format for supported models.
    /// 中文:受支持模型的可选响应格式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<String>,
    /// EN: Optional generated image size.
    /// 中文:可选的生成图像尺寸。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<String>,
    /// EN: Optional style for supported models.
    /// 中文:受支持模型的可选风格。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<String>,
    /// EN: Optional end-user identifier.
    /// 中文:可选的终端用户标识。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateImageRequest {
    /// EN: Starts building an image generation request.
    /// 中文:开始构建图像生成请求。
    pub fn builder() -> CreateImageRequestBuilder {
        CreateImageRequestBuilder::default()
    }
}

/// EN: Builder for image generation requests.
/// 中文:图像生成请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateImageRequestBuilder {
    prompt: Option<String>,
    model: Option<String>,
    n: Option<u32>,
    background: Option<String>,
    moderation: Option<String>,
    output_format: Option<String>,
    output_compression: Option<u8>,
    quality: Option<String>,
    response_format: Option<String>,
    size: Option<String>,
    style: Option<String>,
    user: Option<String>,
    extra: BTreeMap<String, Value>,
}

impl CreateImageRequestBuilder {
    /// EN: Sets the image prompt.
    /// 中文:设置图像提示。
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// EN: Sets the optional image model id.
    /// 中文:设置可选的图像模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets the optional generated image count.
    /// 中文:设置可选的生成图像数量。
    pub fn n(mut self, n: u32) -> Self {
        self.n = Some(n);
        self
    }

    /// EN: Sets the optional background mode.
    /// 中文:设置可选的背景模式。
    pub fn background(mut self, background: impl Into<String>) -> Self {
        self.background = Some(background.into());
        self
    }

    /// EN: Sets the optional image moderation level.
    /// 中文:设置可选的图像审核级别。
    pub fn moderation(mut self, moderation: impl Into<String>) -> Self {
        self.moderation = Some(moderation.into());
        self
    }

    /// EN: Sets the optional output image format.
    /// 中文:设置可选的输出图像格式。
    pub fn output_format(mut self, output_format: impl Into<String>) -> Self {
        self.output_format = Some(output_format.into());
        self
    }

    /// EN: Sets the optional output compression percentage.
    /// 中文:设置可选的输出压缩百分比。
    pub fn output_compression(mut self, output_compression: u8) -> Self {
        self.output_compression = Some(output_compression);
        self
    }

    /// EN: Sets the optional output quality.
    /// 中文:设置可选的输出质量。
    pub fn quality(mut self, quality: impl Into<String>) -> Self {
        self.quality = Some(quality.into());
        self
    }

    /// EN: Sets the optional response format.
    /// 中文:设置可选的响应格式。
    pub fn response_format(mut self, response_format: impl Into<String>) -> Self {
        self.response_format = Some(response_format.into());
        self
    }

    /// EN: Sets the optional generated image size.
    /// 中文:设置可选的生成图像尺寸。
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// EN: Sets the optional style.
    /// 中文:设置可选的风格。
    pub fn style(mut self, style: impl Into<String>) -> Self {
        self.style = Some(style.into());
        self
    }

    /// EN: Sets the optional end-user identifier.
    /// 中文:设置可选的终端用户标识。
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.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<CreateImageRequest, LingerError> {
        let prompt = self
            .prompt
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| LingerError::invalid_config("prompt is required"))?;
        validate_optional_string("model", self.model.as_deref())?;
        validate_optional_string("background", self.background.as_deref())?;
        validate_optional_string("moderation", self.moderation.as_deref())?;
        validate_optional_string("output_format", self.output_format.as_deref())?;
        validate_optional_string("quality", self.quality.as_deref())?;
        validate_optional_string("response_format", self.response_format.as_deref())?;
        validate_optional_string("size", self.size.as_deref())?;
        validate_optional_string("style", self.style.as_deref())?;
        validate_optional_string("user", self.user.as_deref())?;
        if self.n.is_some_and(|n| !(1..=10).contains(&n)) {
            return Err(LingerError::invalid_config("n must be between 1 and 10"));
        }
        if self
            .output_compression
            .is_some_and(|output_compression| output_compression > 100)
        {
            return Err(LingerError::invalid_config(
                "output_compression must be between 0 and 100",
            ));
        }
        Ok(CreateImageRequest {
            prompt,
            model: self.model,
            n: self.n,
            background: self.background,
            moderation: self.moderation,
            output_format: self.output_format,
            output_compression: self.output_compression,
            quality: self.quality,
            response_format: self.response_format,
            size: self.size,
            style: self.style,
            user: self.user,
            extra: self.extra,
        })
    }
}

/// EN: JSON image reference accepted by `POST /v1/images/edits`.
/// 中文:`POST /v1/images/edits` 接受的 JSON 图像引用。
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum ImageInput {
    /// EN: References an uploaded OpenAI file id.
    /// 中文:引用已上传的 OpenAI 文件 ID。
    FileId {
        /// EN: Uploaded file id.
        /// 中文:已上传文件 ID。
        file_id: String,
    },
    /// EN: References an image by URL.
    /// 中文:通过 URL 引用图像。
    ImageUrl {
        /// EN: Image URL.
        /// 中文:图像 URL。
        image_url: String,
    },
}

impl ImageInput {
    /// EN: Creates an image input from an uploaded file id.
    /// 中文:通过已上传文件 ID 创建图像输入。
    pub fn file_id(file_id: impl Into<String>) -> Self {
        Self::FileId {
            file_id: file_id.into(),
        }
    }

    /// EN: Creates an image input from an image URL.
    /// 中文:通过图像 URL 创建图像输入。
    pub fn image_url(image_url: impl Into<String>) -> Self {
        Self::ImageUrl {
            image_url: image_url.into(),
        }
    }

    fn validate(&self) -> Result<(), LingerError> {
        let (name, value) = match self {
            Self::FileId { file_id } => ("file_id", file_id),
            Self::ImageUrl { image_url } => ("image_url", image_url),
        };
        if value.trim().is_empty() {
            return Err(LingerError::invalid_config(format!("{name} is required")));
        }
        Ok(())
    }
}

/// EN: Request body for `POST /v1/images/edits`.
/// 中文:`POST /v1/images/edits` 的请求体。
#[derive(Clone, Debug, Serialize, PartialEq)]
#[non_exhaustive]
pub struct CreateImageEditRequest {
    /// EN: Source images to edit.
    /// 中文:要编辑的源图像。
    pub images: Vec<ImageInput>,
    /// EN: Text prompt describing the requested edit.
    /// 中文:描述编辑要求的文本提示。
    pub prompt: String,
    /// EN: Optional image edit model id.
    /// 中文:可选的图像编辑模型 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// EN: Optional number of images to generate.
    /// 中文:可选的生成图像数量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,
    /// EN: Optional output image size.
    /// 中文:可选的输出图像尺寸。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<String>,
    /// EN: Optional background mode.
    /// 中文:可选的背景模式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<String>,
    /// EN: Optional input fidelity for matching source image style and features.
    /// 中文:用于匹配源图像风格和特征的可选输入保真度。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_fidelity: Option<String>,
    /// EN: Optional image moderation level.
    /// 中文:可选的图像审核级别。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub moderation: Option<String>,
    /// EN: Optional output quality.
    /// 中文:可选的输出质量。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<String>,
    /// EN: Optional output compression percentage.
    /// 中文:可选的输出压缩百分比。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_compression: Option<u8>,
    /// EN: Optional response format for supported models.
    /// 中文:受支持模型的可选响应格式。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<String>,
    /// EN: Optional end-user identifier.
    /// 中文:可选的终端用户标识。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// EN: Forward-compatible optional fields not yet covered by handwritten types.
    /// 中文:手写类型尚未覆盖的前向兼容可选字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl CreateImageEditRequest {
    /// EN: Starts building an image edit request.
    /// 中文:开始构建图像编辑请求。
    pub fn builder() -> CreateImageEditRequestBuilder {
        CreateImageEditRequestBuilder::default()
    }
}

/// EN: Builder for image edit requests.
/// 中文:图像编辑请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateImageEditRequestBuilder {
    images: Vec<ImageInput>,
    prompt: Option<String>,
    model: Option<String>,
    n: Option<u32>,
    size: Option<String>,
    background: Option<String>,
    input_fidelity: Option<String>,
    moderation: Option<String>,
    quality: Option<String>,
    output_compression: Option<u8>,
    response_format: Option<String>,
    user: Option<String>,
    extra: BTreeMap<String, Value>,
}

impl CreateImageEditRequestBuilder {
    /// EN: Adds a source image reference.
    /// 中文:添加一个源图像引用。
    pub fn image(mut self, image: ImageInput) -> Self {
        self.images.push(image);
        self
    }

    /// EN: Replaces the source image list.
    /// 中文:替换源图像列表。
    pub fn images(mut self, images: impl IntoIterator<Item = ImageInput>) -> Self {
        self.images = images.into_iter().collect();
        self
    }

    /// EN: Sets the edit prompt.
    /// 中文:设置编辑提示。
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// EN: Sets the optional image edit model id.
    /// 中文:设置可选的图像编辑模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets the optional generated image count.
    /// 中文:设置可选的生成图像数量。
    pub fn n(mut self, n: u32) -> Self {
        self.n = Some(n);
        self
    }

    /// EN: Sets the optional output image size.
    /// 中文:设置可选的输出图像尺寸。
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// EN: Sets the optional background mode.
    /// 中文:设置可选的背景模式。
    pub fn background(mut self, background: impl Into<String>) -> Self {
        self.background = Some(background.into());
        self
    }

    /// EN: Sets the optional input fidelity.
    /// 中文:设置可选的输入保真度。
    pub fn input_fidelity(mut self, input_fidelity: impl Into<String>) -> Self {
        self.input_fidelity = Some(input_fidelity.into());
        self
    }

    /// EN: Sets the optional image moderation level.
    /// 中文:设置可选的图像审核级别。
    pub fn moderation(mut self, moderation: impl Into<String>) -> Self {
        self.moderation = Some(moderation.into());
        self
    }

    /// EN: Sets the optional output quality.
    /// 中文:设置可选的输出质量。
    pub fn quality(mut self, quality: impl Into<String>) -> Self {
        self.quality = Some(quality.into());
        self
    }

    /// EN: Sets the optional output compression percentage.
    /// 中文:设置可选的输出压缩百分比。
    pub fn output_compression(mut self, output_compression: u8) -> Self {
        self.output_compression = Some(output_compression);
        self
    }

    /// EN: Sets the optional response format.
    /// 中文:设置可选的响应格式。
    pub fn response_format(mut self, response_format: impl Into<String>) -> Self {
        self.response_format = Some(response_format.into());
        self
    }

    /// EN: Sets the optional end-user identifier.
    /// 中文:设置可选的终端用户标识。
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.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<CreateImageEditRequest, LingerError> {
        if self.images.is_empty() {
            return Err(LingerError::invalid_config("images is required"));
        }
        for image in &self.images {
            image.validate()?;
        }
        let prompt = self
            .prompt
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| LingerError::invalid_config("prompt is required"))?;
        validate_optional_string("model", self.model.as_deref())?;
        validate_optional_string("size", self.size.as_deref())?;
        validate_optional_string("background", self.background.as_deref())?;
        validate_optional_string("input_fidelity", self.input_fidelity.as_deref())?;
        validate_optional_string("moderation", self.moderation.as_deref())?;
        validate_optional_string("quality", self.quality.as_deref())?;
        validate_optional_string("response_format", self.response_format.as_deref())?;
        validate_optional_string("user", self.user.as_deref())?;
        if self.n.is_some_and(|n| !(1..=10).contains(&n)) {
            return Err(LingerError::invalid_config("n must be between 1 and 10"));
        }
        if self
            .output_compression
            .is_some_and(|output_compression| output_compression > 100)
        {
            return Err(LingerError::invalid_config(
                "output_compression must be between 0 and 100",
            ));
        }
        Ok(CreateImageEditRequest {
            images: self.images,
            prompt,
            model: self.model,
            n: self.n,
            size: self.size,
            background: self.background,
            input_fidelity: self.input_fidelity,
            moderation: self.moderation,
            quality: self.quality,
            output_compression: self.output_compression,
            response_format: self.response_format,
            user: self.user,
            extra: self.extra,
        })
    }
}

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

impl ImageUpload {
    /// 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/octet-stream".to_string(),
            content: content.into(),
        })
    }

    /// EN: Sets the image part content type.
    /// 中文:设置图像分段的内容类型。
    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 image bytes as a cheap `Bytes` clone.
    /// 中文:以廉价 `Bytes` 克隆返回图像字节。
    pub fn bytes(&self) -> Bytes {
        self.content.clone()
    }
}

/// EN: Request body descriptor for `POST /v1/images/variations`.
/// 中文:`POST /v1/images/variations` 的请求体描述。
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct CreateImageVariationRequest {
    /// EN: Source image to vary.
    /// 中文:要生成变体的源图像。
    pub image: ImageUpload,
    /// EN: Optional image variation model id.
    /// 中文:可选的图像变体模型 ID。
    pub model: Option<String>,
    /// EN: Optional number of images to generate.
    /// 中文:可选的生成图像数量。
    pub n: Option<u32>,
    /// EN: Optional response format.
    /// 中文:可选的响应格式。
    pub response_format: Option<String>,
    /// EN: Optional generated image size.
    /// 中文:可选的生成图像尺寸。
    pub size: Option<String>,
    /// EN: Optional end-user identifier.
    /// 中文:可选的终端用户标识。
    pub user: Option<String>,
}

impl CreateImageVariationRequest {
    /// EN: Starts building an image variation request.
    /// 中文:开始构建图像变体请求。
    pub fn builder() -> CreateImageVariationRequestBuilder {
        CreateImageVariationRequestBuilder::default()
    }

    pub(crate) fn apply_multipart_body(&self, request: &mut HttpRequest) {
        let boundary = multipart_boundary(&self.image.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_optional_text_field(&mut chunks, &boundary, "model", self.model.as_deref());
        push_optional_text_field(&mut chunks, &boundary, "size", self.size.as_deref());
        push_optional_text_field(
            &mut chunks,
            &boundary,
            "response_format",
            self.response_format.as_deref(),
        );
        push_optional_text_field(&mut chunks, &boundary, "user", self.user.as_deref());
        if let Some(n) = self.n {
            push_text_field(&mut chunks, &boundary, "n", &n.to_string());
        }
        chunks.push(Ok(Bytes::from(format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
            escape_multipart_param(&self.image.filename),
            self.image.content_type
        ))));
        chunks.push(Ok(self.image.content.clone()));
        chunks.push(Ok(Bytes::from(format!("\r\n--{boundary}--\r\n"))));
        futures_util::stream::iter(chunks)
    }
}

/// EN: Builder for image variation requests.
/// 中文:图像变体请求的构建器。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct CreateImageVariationRequestBuilder {
    image: Option<ImageUpload>,
    model: Option<String>,
    n: Option<u32>,
    response_format: Option<String>,
    size: Option<String>,
    user: Option<String>,
}

impl CreateImageVariationRequestBuilder {
    /// EN: Sets the image to vary.
    /// 中文:设置要生成变体的图像。
    pub fn image(mut self, image: ImageUpload) -> Self {
        self.image = Some(image);
        self
    }

    /// EN: Sets the optional variation model id.
    /// 中文:设置可选的图像变体模型 ID。
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// EN: Sets the optional generated image count.
    /// 中文:设置可选的生成图像数量。
    pub fn n(mut self, n: u32) -> Self {
        self.n = Some(n);
        self
    }

    /// EN: Sets the optional response format.
    /// 中文:设置可选的响应格式。
    pub fn response_format(mut self, response_format: impl Into<String>) -> Self {
        self.response_format = Some(response_format.into());
        self
    }

    /// EN: Sets the optional generated image size.
    /// 中文:设置可选的生成图像尺寸。
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// EN: Sets the optional end-user identifier.
    /// 中文:设置可选的终端用户标识。
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// EN: Builds and validates the request.
    /// 中文:构建并校验请求。
    pub fn build(self) -> Result<CreateImageVariationRequest, LingerError> {
        let image = self
            .image
            .ok_or_else(|| LingerError::invalid_config("image is required"))?;
        validate_optional_string("model", self.model.as_deref())?;
        validate_optional_string("response_format", self.response_format.as_deref())?;
        validate_optional_string("size", self.size.as_deref())?;
        validate_optional_string("user", self.user.as_deref())?;
        if self.n.is_some_and(|n| !(1..=10).contains(&n)) {
            return Err(LingerError::invalid_config("n must be between 1 and 10"));
        }
        Ok(CreateImageVariationRequest {
            image,
            model: self.model,
            n: self.n,
            response_format: self.response_format,
            size: self.size,
            user: self.user,
        })
    }
}

/// EN: Response object returned by the Images API.
/// 中文:Images API 返回的响应对象。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct ImagesResponse {
    /// EN: Unix timestamp for response creation.
    /// 中文:响应创建时间的 Unix 时间戳。
    pub created: u64,
    /// EN: Generated image items.
    /// 中文:生成的图像项。
    #[serde(default)]
    pub data: Vec<Image>,
    /// EN: Background mode returned by the API.
    /// 中文:API 返回的背景模式。
    #[serde(default)]
    pub background: Option<String>,
    /// EN: Output image format returned by the API.
    /// 中文:API 返回的输出图像格式。
    #[serde(default)]
    pub output_format: Option<String>,
    /// EN: Output quality returned by the API.
    /// 中文:API 返回的输出质量。
    #[serde(default)]
    pub quality: Option<String>,
    /// EN: Image size returned by the API.
    /// 中文:API 返回的图像尺寸。
    #[serde(default)]
    pub size: Option<String>,
    /// EN: Token usage, when returned.
    /// 中文:token 用量,如响应中存在。
    #[serde(default)]
    pub usage: Option<ImageUsage>,
    /// 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 ImagesResponse {
    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 image item returned by the Images API.
/// 中文:Images API 返回的单个图像项。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[non_exhaustive]
pub struct Image {
    /// EN: Image URL, when returned.
    /// 中文:图像 URL,如响应中存在。
    #[serde(default)]
    pub url: Option<String>,
    /// EN: Base64 encoded image, when returned.
    /// 中文:Base64 编码图像,如响应中存在。
    #[serde(default)]
    pub b64_json: Option<String>,
    /// EN: Revised prompt, when returned.
    /// 中文:修订后的提示,如响应中存在。
    #[serde(default)]
    pub revised_prompt: Option<String>,
    /// EN: Additional fields preserved for forward compatibility.
    /// 中文:为前向兼容保留的额外字段。
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// EN: Image generation usage details.
/// 中文:图像生成用量详情。
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImageUsage {
    /// EN: Input token count.
    /// 中文:输入 token 数。
    pub input_tokens: u64,
    /// EN: Output token count.
    /// 中文:输出 token 数。
    pub output_tokens: u64,
    /// EN: Total token count.
    /// 中文:总 token 数。
    pub total_tokens: u64,
    /// EN: Input token details.
    /// 中文:输入 token 详情。
    #[serde(default)]
    pub input_tokens_details: ImageTokenDetails,
    /// EN: Output token details.
    /// 中文:输出 token 详情。
    #[serde(default)]
    pub output_tokens_details: ImageTokenDetails,
}

/// EN: Token details for image generation usage.
/// 中文:图像生成用量的 token 详情。
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImageTokenDetails {
    /// EN: Text token count, when returned.
    /// 中文:文本 token 数,如响应中存在。
    #[serde(default)]
    pub text_tokens: Option<u64>,
    /// EN: Image token count, when returned.
    /// 中文:图像 token 数,如响应中存在。
    #[serde(default)]
    pub image_tokens: Option<u64>,
}

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 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_optional_text_field(
    chunks: &mut Vec<Result<Bytes, LingerError>>,
    boundary: &str,
    name: &str,
    value: Option<&str>,
) {
    if let Some(value) = value {
        push_text_field(chunks, boundary, name, value);
    }
}

fn multipart_boundary(content: &Bytes) -> String {
    for counter in 0.. {
        let boundary = format!("linger-openai-sdk-image-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('"', "\\\"")
}