openai-ergonomic 0.5.2

Ergonomic Rust wrapper for OpenAI API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
//! Image-generation API builders.
//!
//! This module offers ergonomic wrappers around `openai-client-base`'s image
//! endpoints. Builders provide fluent setters, lightweight validation, and
//! produce request types that can be supplied directly to the generated client
//! functions.

use std::path::{Path, PathBuf};

pub use openai_client_base::models::create_image_request::{
    Background, Moderation, OutputFormat, Quality, ResponseFormat, Size, Style,
};
pub use openai_client_base::models::{CreateImageRequest, InputFidelity};

/// Backwards-compatible alias for the generated `InputFidelity` enum.
pub type ImageInputFidelity = InputFidelity;

use crate::{Builder, Error, Result};

/// Builder for image generation (`/images/generations`).
#[derive(Debug, Clone)]
pub struct ImageGenerationBuilder {
    prompt: String,
    model: Option<String>,
    n: Option<i32>,
    quality: Option<Quality>,
    response_format: Option<ResponseFormat>,
    output_format: Option<OutputFormat>,
    output_compression: Option<i32>,
    stream: Option<bool>,
    #[allow(clippy::option_option)]
    partial_images: Option<Option<i32>>,
    size: Option<Size>,
    moderation: Option<Moderation>,
    background: Option<Background>,
    style: Option<Style>,
    user: Option<String>,
}

impl ImageGenerationBuilder {
    /// Create a new generation builder with the required prompt text.
    #[must_use]
    pub fn new(prompt: impl Into<String>) -> Self {
        Self {
            prompt: prompt.into(),
            model: None,
            n: None,
            quality: None,
            response_format: None,
            output_format: None,
            output_compression: None,
            stream: None,
            partial_images: None,
            size: None,
            moderation: None,
            background: None,
            style: None,
            user: None,
        }
    }

    /// Override the model (`gpt-image-1`, `dall-e-3`, etc.).
    #[must_use]
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Set how many images to generate (1-10).
    #[must_use]
    pub fn n(mut self, n: i32) -> Self {
        self.n = Some(n);
        self
    }

    /// Select image quality.
    #[must_use]
    pub fn quality(mut self, quality: Quality) -> Self {
        self.quality = Some(quality);
        self
    }

    /// Select the response format for `dall-e-*` models.
    #[must_use]
    pub fn response_format(mut self, format: ResponseFormat) -> Self {
        self.response_format = Some(format);
        self
    }

    /// Choose the binary output format (only supported for `gpt-image-1`).
    #[must_use]
    pub fn output_format(mut self, format: OutputFormat) -> Self {
        self.output_format = Some(format);
        self
    }

    /// Tune image compression (0-100). Only applies to JPEG/WEBP outputs.
    #[must_use]
    pub fn output_compression(mut self, compression: i32) -> Self {
        self.output_compression = Some(compression);
        self
    }

    /// Enable streaming responses.
    #[must_use]
    pub fn stream(mut self, stream: bool) -> Self {
        self.stream = Some(stream);
        self
    }

    /// Configure the number of partial images to emit when streaming (0-3).
    #[must_use]
    pub fn partial_images(mut self, partial_images: Option<i32>) -> Self {
        self.partial_images = Some(partial_images);
        self
    }

    /// Select the output size preset.
    #[must_use]
    pub fn size(mut self, size: Size) -> Self {
        self.size = Some(size);
        self
    }

    /// Control content moderation (`auto`/`low`).
    #[must_use]
    pub fn moderation(mut self, moderation: Moderation) -> Self {
        self.moderation = Some(moderation);
        self
    }

    /// Configure transparent/opaque backgrounds.
    #[must_use]
    pub fn background(mut self, background: Background) -> Self {
        self.background = Some(background);
        self
    }

    /// Select stylistic hints supported by `dall-e-3`.
    #[must_use]
    pub fn style(mut self, style: Style) -> Self {
        self.style = Some(style);
        self
    }

    /// Attach an end-user identifier for abuse monitoring.
    #[must_use]
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Borrow the configured prompt.
    #[must_use]
    pub fn prompt(&self) -> &str {
        &self.prompt
    }
}

impl Builder<CreateImageRequest> for ImageGenerationBuilder {
    fn build(self) -> Result<CreateImageRequest> {
        if let Some(n) = self.n {
            if !(1..=10).contains(&n) {
                return Err(Error::InvalidRequest(format!(
                    "Image generation `n` must be between 1 and 10 (got {n})"
                )));
            }
        }

        if let Some(Some(partial)) = self.partial_images {
            if !(0..=3).contains(&partial) {
                return Err(Error::InvalidRequest(format!(
                    "Partial image count must be between 0 and 3 (got {partial})"
                )));
            }
        }

        if let Some(compression) = self.output_compression {
            if !(0..=100).contains(&compression) {
                return Err(Error::InvalidRequest(format!(
                    "Output compression must be between 0 and 100 (got {compression})"
                )));
            }
        }

        Ok(CreateImageRequest {
            prompt: self.prompt,
            model: self.model,
            n: self.n,
            quality: self.quality,
            response_format: self.response_format,
            output_format: self.output_format,
            output_compression: self.output_compression,
            stream: self.stream,
            partial_images: self.partial_images,
            size: self.size,
            moderation: self.moderation,
            background: self.background,
            style: self.style,
            user: self.user,
        })
    }
}

/// Builder describing an image edit request (`/images/edits`).
#[derive(Debug, Clone)]
pub struct ImageEditBuilder {
    image: PathBuf,
    prompt: String,
    mask: Option<PathBuf>,
    background: Option<String>,
    model: Option<String>,
    n: Option<i32>,
    size: Option<String>,
    response_format: Option<String>,
    output_format: Option<String>,
    output_compression: Option<i32>,
    user: Option<String>,
    input_fidelity: Option<ImageInputFidelity>,
    stream: Option<bool>,
    partial_images: Option<i32>,
    quality: Option<String>,
}

impl ImageEditBuilder {
    /// Create a new edit request using a base image and prompt.
    #[must_use]
    pub fn new(image: impl AsRef<Path>, prompt: impl Into<String>) -> Self {
        Self {
            image: image.as_ref().to_path_buf(),
            prompt: prompt.into(),
            mask: None,
            background: None,
            model: None,
            n: None,
            size: None,
            response_format: None,
            output_format: None,
            output_compression: None,
            user: None,
            input_fidelity: None,
            stream: None,
            partial_images: None,
            quality: None,
        }
    }

    /// Supply a mask file that indicates editable regions.
    #[must_use]
    pub fn mask(mut self, mask: impl AsRef<Path>) -> Self {
        self.mask = Some(mask.as_ref().to_path_buf());
        self
    }

    /// Control the generated background (`transparent`, `opaque`, ... as string).
    #[must_use]
    pub fn background(mut self, background: impl Into<String>) -> Self {
        self.background = Some(background.into());
        self
    }

    /// Override the model (defaults to `gpt-image-1`).
    #[must_use]
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Configure the number of images to generate (1-10).
    #[must_use]
    pub fn n(mut self, n: i32) -> Self {
        self.n = Some(n);
        self
    }

    /// Set the output size (e.g. `1024x1024`).
    #[must_use]
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// Choose the response format (`url`, `b64_json`).
    #[must_use]
    pub fn response_format(mut self, format: impl Into<String>) -> Self {
        self.response_format = Some(format.into());
        self
    }

    /// Choose the binary output format (`png`, `jpeg`, `webp`).
    #[must_use]
    pub fn output_format(mut self, format: impl Into<String>) -> Self {
        self.output_format = Some(format.into());
        self
    }

    /// Configure output compression (0-100).
    #[must_use]
    pub fn output_compression(mut self, compression: i32) -> Self {
        self.output_compression = Some(compression);
        self
    }

    /// Attach an end-user identifier.
    #[must_use]
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Control fidelity for the input image (`low`/`high`).
    #[must_use]
    pub fn input_fidelity(mut self, fidelity: ImageInputFidelity) -> Self {
        self.input_fidelity = Some(fidelity);
        self
    }

    /// Enable streaming responses for edits.
    #[must_use]
    pub fn stream(mut self, stream: bool) -> Self {
        self.stream = Some(stream);
        self
    }

    /// Configure partial image count when streaming (0-3).
    #[must_use]
    pub fn partial_images(mut self, value: i32) -> Self {
        self.partial_images = Some(value);
        self
    }

    /// Provide quality hints (`low`, `medium`, `high`, ...).
    #[must_use]
    pub fn quality(mut self, quality: impl Into<String>) -> Self {
        self.quality = Some(quality.into());
        self
    }

    /// Borrow the underlying image path.
    #[must_use]
    pub fn image(&self) -> &Path {
        &self.image
    }

    /// Borrow the edit prompt.
    #[must_use]
    pub fn prompt(&self) -> &str {
        &self.prompt
    }
}

/// Fully prepared payload for the edit endpoint.
#[derive(Debug, Clone)]
pub struct ImageEditRequest {
    /// Path to the original image that will be edited.
    pub image: PathBuf,
    /// Natural-language instructions describing the edit.
    pub prompt: String,
    /// Optional mask describing editable regions.
    pub mask: Option<PathBuf>,
    /// Optional background mode (`transparent`, `opaque`, ...).
    pub background: Option<String>,
    /// Model identifier to use for the edit operation.
    pub model: Option<String>,
    /// Number of images to generate (1-10).
    pub n: Option<i32>,
    /// Requested output size (e.g. `1024x1024`).
    pub size: Option<String>,
    /// Response format for non-streaming outputs (`url`, `b64_json`).
    pub response_format: Option<String>,
    /// Binary output format (`png`, `jpeg`, `webp`).
    pub output_format: Option<String>,
    /// Compression level for JPEG/WEBP outputs (0-100).
    pub output_compression: Option<i32>,
    /// End-user identifier for abuse monitoring.
    pub user: Option<String>,
    /// Fidelity configuration for how closely to follow the input image.
    pub input_fidelity: Option<ImageInputFidelity>,
    /// Whether to stream incremental results.
    pub stream: Option<bool>,
    /// Number of partial images to emit while streaming.
    pub partial_images: Option<i32>,
    /// Additional quality hints accepted by the service.
    pub quality: Option<String>,
}

impl Builder<ImageEditRequest> for ImageEditBuilder {
    fn build(self) -> Result<ImageEditRequest> {
        if let Some(n) = self.n {
            if !(1..=10).contains(&n) {
                return Err(Error::InvalidRequest(format!(
                    "Image edit `n` must be between 1 and 10 (got {n})"
                )));
            }
        }

        if let Some(compression) = self.output_compression {
            if !(0..=100).contains(&compression) {
                return Err(Error::InvalidRequest(format!(
                    "Output compression must be between 0 and 100 (got {compression})"
                )));
            }
        }

        if let Some(partial) = self.partial_images {
            if !(0..=3).contains(&partial) {
                return Err(Error::InvalidRequest(format!(
                    "Partial image count must be between 0 and 3 (got {partial})"
                )));
            }
        }

        Ok(ImageEditRequest {
            image: self.image,
            prompt: self.prompt,
            mask: self.mask,
            background: self.background,
            model: self.model,
            n: self.n,
            size: self.size,
            response_format: self.response_format,
            output_format: self.output_format,
            output_compression: self.output_compression,
            user: self.user,
            input_fidelity: self.input_fidelity,
            stream: self.stream,
            partial_images: self.partial_images,
            quality: self.quality,
        })
    }
}

/// Builder describing an image variation request (`/images/variations`).
#[derive(Debug, Clone)]
pub struct ImageVariationBuilder {
    image: PathBuf,
    model: Option<String>,
    n: Option<i32>,
    response_format: Option<String>,
    size: Option<String>,
    user: Option<String>,
}

impl ImageVariationBuilder {
    /// Create a variation builder for the provided image file.
    #[must_use]
    pub fn new(image: impl AsRef<Path>) -> Self {
        Self {
            image: image.as_ref().to_path_buf(),
            model: None,
            n: None,
            response_format: None,
            size: None,
            user: None,
        }
    }

    /// Override the variation model.
    #[must_use]
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Number of variations to generate (1-10).
    #[must_use]
    pub fn n(mut self, n: i32) -> Self {
        self.n = Some(n);
        self
    }

    /// Choose the response format (`url`, `b64_json`).
    #[must_use]
    pub fn response_format(mut self, format: impl Into<String>) -> Self {
        self.response_format = Some(format.into());
        self
    }

    /// Select the image size preset.
    #[must_use]
    pub fn size(mut self, size: impl Into<String>) -> Self {
        self.size = Some(size.into());
        self
    }

    /// Attach an end-user identifier.
    #[must_use]
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Borrow the base image path.
    #[must_use]
    pub fn image(&self) -> &Path {
        &self.image
    }
}

/// Fully prepared payload for the variation endpoint.
#[derive(Debug, Clone)]
pub struct ImageVariationRequest {
    /// Path to the source image to transform.
    pub image: PathBuf,
    /// Optional model override.
    pub model: Option<String>,
    /// Number of variations to create (1-10).
    pub n: Option<i32>,
    /// Response format (`url`, `b64_json`).
    pub response_format: Option<String>,
    /// Output size (e.g. `512x512`).
    pub size: Option<String>,
    /// End-user identifier for abuse monitoring.
    pub user: Option<String>,
}

impl Builder<ImageVariationRequest> for ImageVariationBuilder {
    fn build(self) -> Result<ImageVariationRequest> {
        if let Some(n) = self.n {
            if !(1..=10).contains(&n) {
                return Err(Error::InvalidRequest(format!(
                    "Image variation `n` must be between 1 and 10 (got {n})"
                )));
            }
        }

        Ok(ImageVariationRequest {
            image: self.image,
            model: self.model,
            n: self.n,
            response_format: self.response_format,
            size: self.size,
            user: self.user,
        })
    }
}

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

    #[test]
    fn builds_image_generation_request() {
        let request = ImageGenerationBuilder::new("A scenic valley at sunrise")
            .model("gpt-image-1")
            .n(2)
            .quality(Quality::High)
            .response_format(ResponseFormat::B64Json)
            .output_format(OutputFormat::Webp)
            .output_compression(80)
            .stream(true)
            .partial_images(Some(2))
            .size(Size::Variant1536x1024)
            .moderation(Moderation::Auto)
            .background(Background::Transparent)
            .style(Style::Vivid)
            .user("example-user")
            .build()
            .expect("valid generation builder");

        assert_eq!(request.prompt, "A scenic valley at sunrise");
        assert_eq!(request.model.as_deref(), Some("gpt-image-1"));
        assert_eq!(request.n, Some(2));
        assert_eq!(request.quality, Some(Quality::High));
        assert_eq!(request.response_format, Some(ResponseFormat::B64Json));
        assert_eq!(request.output_format, Some(OutputFormat::Webp));
        assert_eq!(request.output_compression, Some(80));
        assert_eq!(request.stream, Some(true));
        assert_eq!(request.partial_images, Some(Some(2)));
        assert_eq!(request.size, Some(Size::Variant1536x1024));
        assert_eq!(request.moderation, Some(Moderation::Auto));
        assert_eq!(request.background, Some(Background::Transparent));
        assert_eq!(request.style, Some(Style::Vivid));
        assert_eq!(request.user.as_deref(), Some("example-user"));
    }

    #[test]
    fn generation_validates_ranges() {
        let err = ImageGenerationBuilder::new("Prompt")
            .n(0)
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));

        let err = ImageGenerationBuilder::new("Prompt")
            .output_compression(150)
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));

        let err = ImageGenerationBuilder::new("Prompt")
            .partial_images(Some(5))
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));
    }

    #[test]
    fn builds_image_edit_request() {
        let request = ImageEditBuilder::new("image.png", "Remove the background")
            .mask("mask.png")
            .background("transparent")
            .model("gpt-image-1")
            .n(1)
            .size("1024x1024")
            .response_format("b64_json")
            .output_format("png")
            .output_compression(90)
            .user("user-1")
            .input_fidelity(ImageInputFidelity::High)
            .stream(true)
            .partial_images(1)
            .quality("standard")
            .build()
            .expect("valid edit builder");

        assert_eq!(request.image, PathBuf::from("image.png"));
        assert_eq!(request.prompt, "Remove the background");
        assert_eq!(request.mask, Some(PathBuf::from("mask.png")));
        assert_eq!(request.background.as_deref(), Some("transparent"));
        assert_eq!(request.model.as_deref(), Some("gpt-image-1"));
        assert_eq!(request.size.as_deref(), Some("1024x1024"));
        assert_eq!(request.response_format.as_deref(), Some("b64_json"));
        assert_eq!(request.output_format.as_deref(), Some("png"));
        assert_eq!(request.output_compression, Some(90));
        assert_eq!(request.stream, Some(true));
        assert_eq!(request.partial_images, Some(1));
    }

    #[test]
    fn edit_validates_ranges() {
        let err = ImageEditBuilder::new("image.png", "Prompt")
            .n(20)
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));

        let err = ImageEditBuilder::new("image.png", "Prompt")
            .output_compression(150)
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));

        let err = ImageEditBuilder::new("image.png", "Prompt")
            .partial_images(5)
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));
    }

    #[test]
    fn builds_image_variation_request() {
        let request = ImageVariationBuilder::new("image.png")
            .model("dall-e-2")
            .n(3)
            .response_format("url")
            .size("512x512")
            .user("user-123")
            .build()
            .expect("valid variation builder");

        assert_eq!(request.image, PathBuf::from("image.png"));
        assert_eq!(request.model.as_deref(), Some("dall-e-2"));
        assert_eq!(request.n, Some(3));
        assert_eq!(request.response_format.as_deref(), Some("url"));
        assert_eq!(request.size.as_deref(), Some("512x512"));
    }

    #[test]
    fn variation_validates_n() {
        let err = ImageVariationBuilder::new("image.png")
            .n(0)
            .build()
            .unwrap_err();
        assert!(matches!(err, Error::InvalidRequest(_)));
    }
}