Skip to main content

openai_tools/images/
response.rs

1//! OpenAI Images API Response Types
2//!
3//! This module defines the response structures for the OpenAI Images API.
4
5use serde::{Deserialize, Serialize};
6
7/// Response structure from image generation/edit/variation endpoints.
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct ImageResponse {
10    /// Unix timestamp when the image was created
11    pub created: i64,
12    /// Array of generated images
13    pub data: Vec<ImageData>,
14}
15
16/// Individual image data from generation response.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct ImageData {
19    /// URL of the generated image (if response_format = url)
20    /// Note: URLs are only valid for 60 minutes after generation
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub url: Option<String>,
23
24    /// Base64-encoded image data (if response_format = b64_json)
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub b64_json: Option<String>,
27
28    /// The revised prompt used by the model (DALL-E 3 only)
29    /// DALL-E 3 may revise the original prompt for safety or quality
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub revised_prompt: Option<String>,
32}
33
34impl ImageData {
35    /// Decodes base64 image data to bytes.
36    ///
37    /// Returns `None` if no b64_json data is present.
38    /// Returns `Some(Err(...))` if base64 decoding fails.
39    ///
40    /// # Example
41    ///
42    /// ```rust,no_run
43    /// use openai_tools::images::response::ImageData;
44    /// use std::fs;
45    ///
46    /// # fn example(image_data: &ImageData) -> Result<(), Box<dyn std::error::Error>> {
47    /// if let Some(bytes_result) = image_data.as_bytes() {
48    ///     let bytes = bytes_result?;
49    ///     fs::write("output.png", bytes)?;
50    /// }
51    /// # Ok(())
52    /// # }
53    /// ```
54    pub fn as_bytes(&self) -> Option<std::result::Result<Vec<u8>, base64::DecodeError>> {
55        use base64::{engine::general_purpose::STANDARD, Engine};
56        self.b64_json.as_ref().map(|b64| STANDARD.decode(b64))
57    }
58
59    /// Returns true if this image data contains a URL.
60    pub fn has_url(&self) -> bool {
61        self.url.is_some()
62    }
63
64    /// Returns true if this image data contains base64 data.
65    pub fn has_b64(&self) -> bool {
66        self.b64_json.is_some()
67    }
68}