Skip to main content

gptimage_2_5_client/
lib.rs

1//! Lightweight helpers for GPT Image 2.5-style AI image generation workflows.
2//!
3//! This crate provides request, aspect-ratio, resolution, and reference-image
4//! types for Rust applications that need to organize image generation prompts
5//! before handing them to a backend or HTTP client.
6//!
7//! ```
8//! use gptimage_2_5_client::{AspectRatio, ImageRequest, Resolution};
9//!
10//! let request = ImageRequest::new("A product poster with the headline SPRING SALE")
11//!     .aspect_ratio(AspectRatio::Widescreen)
12//!     .resolution(Resolution::TwoK);
13//!
14//! assert_eq!(request.resolution, Resolution::TwoK);
15//! assert!(request.validate().is_ok());
16//! ```
17
18use std::error::Error;
19use std::fmt;
20
21#[cfg(feature = "serde")]
22use serde::{Deserialize, Serialize};
23
24/// Maximum number of reference images accepted by an image-to-image edit.
25pub const MAX_REFERENCE_IMAGES: usize = 16;
26
27/// Maximum prompt length in characters.
28pub const MAX_PROMPT_CHARS: usize = 5000;
29
30/// Common image aspect ratios.
31#[derive(Debug, Clone, PartialEq, Eq)]
32#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
33pub enum AspectRatio {
34    /// 1:1 square image.
35    Square,
36    /// 16:9 widescreen image.
37    Widescreen,
38    /// 9:16 vertical image for short-form platforms.
39    Vertical,
40    /// 3:2 landscape image.
41    Landscape,
42    /// 2:3 portrait image.
43    Portrait,
44    /// Let the model choose the frame that fits the prompt.
45    Auto,
46    /// Custom aspect ratio, such as "4:3" or "21:9".
47    Custom(String),
48}
49
50impl AspectRatio {
51    /// Returns the ratio in `width:height` form, or `"auto"` for [`AspectRatio::Auto`].
52    pub fn as_str(&self) -> &str {
53        match self {
54            Self::Square => "1:1",
55            Self::Widescreen => "16:9",
56            Self::Vertical => "9:16",
57            Self::Landscape => "3:2",
58            Self::Portrait => "2:3",
59            Self::Auto => "auto",
60            Self::Custom(value) => value,
61        }
62    }
63}
64
65impl fmt::Display for AspectRatio {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(self.as_str())
68    }
69}
70
71/// Output resolution tiers.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
74pub enum Resolution {
75    /// 1K output, the cheapest tier.
76    OneK,
77    /// 2K output.
78    TwoK,
79    /// 4K output, the most detailed tier.
80    FourK,
81}
82
83impl Resolution {
84    /// Returns the short label used in most APIs, such as `"2K"`.
85    pub fn as_str(&self) -> &'static str {
86        match self {
87            Self::OneK => "1K",
88            Self::TwoK => "2K",
89            Self::FourK => "4K",
90        }
91    }
92
93    /// Returns the long edge in pixels for this tier.
94    pub fn long_edge_pixels(&self) -> u32 {
95        match self {
96            Self::OneK => 1024,
97            Self::TwoK => 2048,
98            Self::FourK => 4096,
99        }
100    }
101}
102
103impl fmt::Display for Resolution {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        f.write_str(self.as_str())
106    }
107}
108
109/// How a reference image should steer the generation.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
112pub enum ReferenceRole {
113    /// Keep a character or person consistent.
114    Character,
115    /// Keep a product or object consistent.
116    Product,
117    /// Carry over an art style.
118    Style,
119    /// Carry over a layout or composition.
120    Composition,
121}
122
123/// A single reference image supplied to an image-to-image edit.
124#[derive(Debug, Clone, PartialEq, Eq)]
125#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
126pub struct ReferenceImage {
127    /// Source URL or storage identifier.
128    pub source: String,
129    /// What the reference is meant to steer.
130    pub role: ReferenceRole,
131    /// Optional human-readable label.
132    pub label: Option<String>,
133}
134
135impl ReferenceImage {
136    /// Creates a reference image with the given source and role.
137    pub fn new(source: impl Into<String>, role: ReferenceRole) -> Self {
138        Self {
139            source: source.into(),
140            role,
141            label: None,
142        }
143    }
144
145    /// Attaches a human-readable label.
146    pub fn label(mut self, label: impl Into<String>) -> Self {
147        self.label = Some(label.into());
148        self
149    }
150}
151
152/// Errors produced when a request is not valid.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum RequestError {
155    /// The prompt was empty or only whitespace.
156    EmptyPrompt,
157    /// The prompt exceeded [`MAX_PROMPT_CHARS`].
158    PromptTooLong {
159        /// Actual prompt length in characters.
160        chars: usize,
161    },
162    /// More than [`MAX_REFERENCE_IMAGES`] references were supplied.
163    TooManyReferences {
164        /// Actual number of references supplied.
165        count: usize,
166    },
167    /// A reference image had an empty source.
168    EmptyReferenceSource,
169}
170
171impl fmt::Display for RequestError {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        match self {
174            Self::EmptyPrompt => write!(f, "prompt must not be empty"),
175            Self::PromptTooLong { chars } => {
176                write!(f, "prompt is {chars} characters, limit is {MAX_PROMPT_CHARS}")
177            }
178            Self::TooManyReferences { count } => {
179                write!(
180                    f,
181                    "{count} reference images supplied, limit is {MAX_REFERENCE_IMAGES}"
182                )
183            }
184            Self::EmptyReferenceSource => write!(f, "reference image source must not be empty"),
185        }
186    }
187}
188
189impl Error for RequestError {}
190
191/// A structured request for an AI image generation workflow.
192#[derive(Debug, Clone, PartialEq, Eq)]
193#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
194pub struct ImageRequest {
195    /// Main text prompt.
196    pub prompt: String,
197    /// Desired aspect ratio.
198    pub aspect_ratio: AspectRatio,
199    /// Desired output resolution.
200    pub resolution: Resolution,
201    /// Optional negative prompt.
202    pub negative_prompt: Option<String>,
203    /// Optional model name or provider identifier.
204    pub model: Option<String>,
205    /// Optional seed for reproducible output.
206    pub seed: Option<u64>,
207    /// Reference images for image-to-image editing.
208    pub references: Vec<ReferenceImage>,
209}
210
211impl ImageRequest {
212    /// Creates a new image request with sensible defaults.
213    pub fn new(prompt: impl Into<String>) -> Self {
214        Self {
215            prompt: prompt.into(),
216            aspect_ratio: AspectRatio::Square,
217            resolution: Resolution::OneK,
218            negative_prompt: None,
219            model: None,
220            seed: None,
221            references: Vec::new(),
222        }
223    }
224
225    /// Sets the aspect ratio.
226    pub fn aspect_ratio(mut self, aspect_ratio: AspectRatio) -> Self {
227        self.aspect_ratio = aspect_ratio;
228        self
229    }
230
231    /// Sets the output resolution.
232    pub fn resolution(mut self, resolution: Resolution) -> Self {
233        self.resolution = resolution;
234        self
235    }
236
237    /// Sets a negative prompt.
238    pub fn negative_prompt(mut self, prompt: impl Into<String>) -> Self {
239        self.negative_prompt = Some(prompt.into());
240        self
241    }
242
243    /// Sets a model identifier.
244    pub fn model(mut self, model: impl Into<String>) -> Self {
245        self.model = Some(model.into());
246        self
247    }
248
249    /// Sets a seed for reproducible output.
250    pub fn seed(mut self, seed: u64) -> Self {
251        self.seed = Some(seed);
252        self
253    }
254
255    /// Adds a reference image, ignoring the limit until [`ImageRequest::validate`] runs.
256    pub fn reference(mut self, reference: ReferenceImage) -> Self {
257        self.references.push(reference);
258        self
259    }
260
261    /// Adds a reference image, failing if the request already holds the maximum.
262    pub fn try_reference(&mut self, reference: ReferenceImage) -> Result<(), RequestError> {
263        if self.references.len() >= MAX_REFERENCE_IMAGES {
264            return Err(RequestError::TooManyReferences {
265                count: self.references.len() + 1,
266            });
267        }
268        self.references.push(reference);
269        Ok(())
270    }
271
272    /// Reports whether this request runs as an image-to-image edit.
273    pub fn is_image_to_image(&self) -> bool {
274        !self.references.is_empty()
275    }
276
277    /// Checks the prompt and reference images against the documented limits.
278    pub fn validate(&self) -> Result<(), RequestError> {
279        if self.prompt.trim().is_empty() {
280            return Err(RequestError::EmptyPrompt);
281        }
282
283        let chars = self.prompt.chars().count();
284        if chars > MAX_PROMPT_CHARS {
285            return Err(RequestError::PromptTooLong { chars });
286        }
287
288        if self.references.len() > MAX_REFERENCE_IMAGES {
289            return Err(RequestError::TooManyReferences {
290                count: self.references.len(),
291            });
292        }
293
294        if self.references.iter().any(|r| r.source.trim().is_empty()) {
295            return Err(RequestError::EmptyReferenceSource);
296        }
297
298        Ok(())
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    #[test]
307    fn creates_default_image_request() {
308        let request = ImageRequest::new("A neon lit street at night");
309
310        assert_eq!(request.aspect_ratio, AspectRatio::Square);
311        assert_eq!(request.resolution, Resolution::OneK);
312        assert!(!request.is_image_to_image());
313        assert!(request.validate().is_ok());
314    }
315
316    #[test]
317    fn updates_image_request_fields() {
318        let request = ImageRequest::new("A packaging shot with readable labels")
319            .aspect_ratio(AspectRatio::Widescreen)
320            .resolution(Resolution::FourK)
321            .negative_prompt("blurry text")
322            .model("gpt-image-2.5")
323            .seed(42);
324
325        assert_eq!(request.aspect_ratio.as_str(), "16:9");
326        assert_eq!(request.resolution.long_edge_pixels(), 4096);
327        assert_eq!(request.negative_prompt.as_deref(), Some("blurry text"));
328        assert_eq!(request.model.as_deref(), Some("gpt-image-2.5"));
329        assert_eq!(request.seed, Some(42));
330    }
331
332    #[test]
333    fn tracks_reference_images() {
334        let request = ImageRequest::new("Keep this character consistent")
335            .reference(ReferenceImage::new("s3://refs/face.png", ReferenceRole::Character).label("hero"))
336            .reference(ReferenceImage::new("s3://refs/jacket.png", ReferenceRole::Product));
337
338        assert!(request.is_image_to_image());
339        assert_eq!(request.references.len(), 2);
340        assert_eq!(request.references[0].label.as_deref(), Some("hero"));
341        assert!(request.validate().is_ok());
342    }
343
344    #[test]
345    fn rejects_empty_prompt() {
346        let request = ImageRequest::new("   ");
347
348        assert_eq!(request.validate(), Err(RequestError::EmptyPrompt));
349    }
350
351    #[test]
352    fn rejects_overlong_prompt() {
353        let request = ImageRequest::new("a".repeat(MAX_PROMPT_CHARS + 1));
354
355        assert_eq!(
356            request.validate(),
357            Err(RequestError::PromptTooLong {
358                chars: MAX_PROMPT_CHARS + 1
359            })
360        );
361    }
362
363    #[test]
364    fn rejects_too_many_references() {
365        let mut request = ImageRequest::new("A coordinated campaign set");
366        for index in 0..MAX_REFERENCE_IMAGES {
367            request
368                .try_reference(ReferenceImage::new(
369                    format!("s3://refs/{index}.png"),
370                    ReferenceRole::Style,
371                ))
372                .expect("within limit");
373        }
374
375        let overflow = request.try_reference(ReferenceImage::new(
376            "s3://refs/extra.png",
377            ReferenceRole::Style,
378        ));
379
380        assert_eq!(
381            overflow,
382            Err(RequestError::TooManyReferences {
383                count: MAX_REFERENCE_IMAGES + 1
384            })
385        );
386        assert_eq!(request.references.len(), MAX_REFERENCE_IMAGES);
387    }
388
389    #[test]
390    fn rejects_empty_reference_source() {
391        let request = ImageRequest::new("A hero image")
392            .reference(ReferenceImage::new("  ", ReferenceRole::Composition));
393
394        assert_eq!(request.validate(), Err(RequestError::EmptyReferenceSource));
395    }
396
397    #[test]
398    fn formats_aspect_ratio_and_resolution() {
399        assert_eq!(AspectRatio::Auto.to_string(), "auto");
400        assert_eq!(AspectRatio::Custom("21:9".into()).to_string(), "21:9");
401        assert_eq!(Resolution::TwoK.to_string(), "2K");
402    }
403}