Skip to main content

adk_model/muse/
images.rs

1//! Image generation and editing via the Meta Model API (`muse-image-1.0`).
2//!
3//! OpenAI Images-compatible endpoints:
4//! - `POST /v1/images/generations` (text-to-image)
5//! - `POST /v1/images/edits` (image edit/compose, multipart)
6//!
7//! Every call is metered against the current run ([`adk_core::meter_usage`]): the spend
8//! hold covers the requested image count at the catalog's per-image price, and the images
9//! returned are committed. A call refused by the run's budget or spend ledger is not sent.
10
11use super::config::MuseConfig;
12use crate::pricing::PricingCatalog;
13use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
14use adk_core::{AdkError, ErrorComponent, MeteredUsage, UsageCall, UsageUnit, UsageVector};
15use reqwest::Client;
16use serde::Deserialize;
17
18/// Model served by the Images endpoints.
19pub const MUSE_IMAGE_MODEL: &str = "muse-image-1.0";
20
21/// One generated or edited image.
22#[derive(Debug, Clone, Deserialize)]
23pub struct ImageData {
24    /// Base64 PNG/JPEG bytes, when `response_format` is `b64_json` (the default).
25    #[serde(default)]
26    pub b64_json: Option<String>,
27    /// Hosted URL, when `response_format` is `url`.
28    #[serde(default)]
29    pub url: Option<String>,
30    /// The prompt the model used after any rewrite.
31    #[serde(default)]
32    pub revised_prompt: Option<String>,
33}
34
35impl ImageData {
36    /// Decoded image bytes, for `b64_json` results.
37    ///
38    /// # Errors
39    ///
40    /// Returns `model.muse.image_decode` when the result carries no base64 body or
41    /// the body is not valid base64.
42    pub fn bytes(&self) -> Result<Vec<u8>, AdkError> {
43        use base64::Engine as _;
44        let b64 = self.b64_json.as_deref().ok_or_else(|| {
45            AdkError::model(
46                "muse image result has no b64_json body; request b64_json or use the url",
47            )
48        })?;
49        base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| {
50            AdkError::new(
51                ErrorComponent::Model,
52                adk_core::ErrorCategory::InvalidInput,
53                "model.muse.image_decode",
54                format!("muse image result is not valid base64: {e}"),
55            )
56            .with_provider("muse")
57        })
58    }
59}
60
61/// Images response envelope.
62#[derive(Debug, Clone, Deserialize)]
63pub struct ImagesResponse {
64    /// Unix creation timestamp.
65    pub created: u64,
66    /// Generated images.
67    #[serde(default)]
68    pub data: Vec<ImageData>,
69}
70
71/// Options for one image call.
72#[derive(Debug, Clone, Default)]
73pub struct ImageOptions {
74    /// Number of images (billed per image; failures are free).
75    pub n: Option<u32>,
76    /// `WxH` size (aspect over 16:1 is rejected).
77    pub size: Option<String>,
78    /// `b64_json` (default) or `url`.
79    pub response_format: Option<String>,
80}
81
82/// Client for `muse-image-1.0` generation and edits.
83///
84/// # Example
85///
86/// ```rust,ignore
87/// use adk_model::muse::{MuseConfig, MuseImagesClient};
88///
89/// let images = MuseImagesClient::new(MuseConfig::new(api_key, "muse-image-1.0"))?;
90/// let response = images.generate("a red barn at dawn", Default::default()).await?;
91/// ```
92pub struct MuseImagesClient {
93    client: Client,
94    config: MuseConfig,
95    retry_config: RetryConfig,
96}
97
98impl MuseImagesClient {
99    /// Create an Images client. The config model is forced to `muse-image-1.0`
100    /// unless a custom base URL already implies another deployment.
101    pub fn new(mut config: MuseConfig) -> Result<Self, AdkError> {
102        if config.model.is_empty() || config.model.starts_with("muse-spark") {
103            config.model = MUSE_IMAGE_MODEL.to_string();
104        }
105        let client = crate::HttpTimeouts::default()
106            .apply(Client::builder())
107            .build()
108            .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
109        Ok(Self { client, config, retry_config: RetryConfig::default() })
110    }
111
112    /// Generate images from a text prompt.
113    ///
114    /// # Errors
115    ///
116    /// Returns the API error (HTTP status, code `model.muse.api_error`) on rejection, or
117    /// the current run's refusal (spend limit, budget) before anything is sent.
118    pub async fn generate(
119        &self,
120        prompt: impl Into<String>,
121        options: ImageOptions,
122    ) -> Result<ImagesResponse, AdkError> {
123        let url = format!("{}/images/generations", self.base());
124        let call = self.usage_call(options.n);
125        let body = serde_json::json!({
126            "model": self.config.model,
127            "prompt": prompt.into(),
128            "n": options.n,
129            "size": options.size,
130            "response_format": options.response_format,
131        });
132        adk_core::meter_usage(call, async {
133            let response = self.post_json(&url, body).await?;
134            let usage = self.usage(&response);
135            Ok((response, usage))
136        })
137        .await
138    }
139
140    /// Edit or compose from an existing image (multipart upload).
141    ///
142    /// # Errors
143    ///
144    /// Returns the API error (HTTP status, code `model.muse.api_error`) on rejection, or
145    /// the current run's refusal (spend limit, budget) before anything is sent.
146    pub async fn edit(
147        &self,
148        image: Vec<u8>,
149        filename: impl Into<String>,
150        content_type: &str,
151        prompt: impl Into<String>,
152        options: ImageOptions,
153    ) -> Result<ImagesResponse, AdkError> {
154        let url = format!("{}/images/edits", self.base());
155        let call = self.usage_call(options.n);
156        let filename = filename.into();
157        let prompt = prompt.into();
158        let (opt_n, opt_size, opt_format) =
159            (options.n, options.size.clone(), options.response_format.clone());
160        let client = self.client.clone();
161        let api_key = self.config.api_key.clone();
162        let model = self.config.model.clone();
163        let retry_config = self.retry_config.clone();
164        let edited = execute_with_retry(&retry_config, is_retryable_model_error, || {
165            let client = client.clone();
166            let url = url.clone();
167            let api_key = api_key.clone();
168            let image = image.clone();
169            let filename = filename.clone();
170            let prompt = prompt.clone();
171            let model = model.clone();
172            let (opt_n, opt_size, opt_format) = (opt_n, opt_size.clone(), opt_format.clone());
173            async move {
174                let part = reqwest::multipart::Part::bytes(image)
175                    .file_name(filename)
176                    .mime_str(content_type)
177                    .map_err(|e| AdkError::model(format!("invalid image content type: {e}")))?;
178                let mut form = reqwest::multipart::Form::new()
179                    .text("model", model)
180                    .text("prompt", prompt)
181                    .part("image", part);
182                if let Some(n) = opt_n {
183                    form = form.text("n", n.to_string());
184                }
185                if let Some(size) = &opt_size {
186                    form = form.text("size", size.clone());
187                }
188                if let Some(format) = &opt_format {
189                    form = form.text("response_format", format.clone());
190                }
191                let response = client
192                    .post(&url)
193                    .header("Authorization", format!("Bearer {api_key}"))
194                    .multipart(form)
195                    .send()
196                    .await
197                    .map_err(|e| {
198                        AdkError::new(
199                            ErrorComponent::Model,
200                            crate::http_timeouts::transport_category(&e),
201                            "model.muse.request",
202                            format!("Muse images request failed: {e}"),
203                        )
204                        .with_provider("muse")
205                    })?;
206                Self::read_response(response).await
207            }
208        });
209        adk_core::meter_usage(call, async {
210            let response = edited.await?;
211            let usage = self.usage(&response);
212            Ok((response, usage))
213        })
214        .await
215    }
216
217    /// The metered call for `n` images (one when unset), bounded at the catalog price.
218    fn usage_call(&self, n: Option<u32>) -> UsageCall {
219        let requested = UsageVector::new().with(UsageUnit::Images, u64::from(n.unwrap_or(1)));
220        let call = UsageCall::new("muse", self.config.model.clone());
221        match PricingCatalog::standard().unit_cost_micro_usd(
222            Some("muse"),
223            &self.config.model,
224            &requested,
225        ) {
226            Some(bound) => call.with_max_cost_micro_usd(bound),
227            None => call,
228        }
229    }
230
231    /// The images a response returned, which are the ones billed.
232    fn usage(&self, response: &ImagesResponse) -> MeteredUsage {
233        let returned = UsageVector::new().with(UsageUnit::Images, response.data.len() as u64);
234        let cost = PricingCatalog::standard().unit_cost_micro_usd(
235            Some("muse"),
236            &self.config.model,
237            &returned,
238        );
239        let usage = MeteredUsage::new(returned);
240        match cost {
241            Some(cost) => usage.with_cost_micro_usd(cost),
242            None => usage,
243        }
244    }
245
246    fn base(&self) -> String {
247        self.config.effective_base_url().trim_end_matches('/').to_string()
248    }
249
250    async fn post_json(
251        &self,
252        url: &str,
253        body: serde_json::Value,
254    ) -> Result<ImagesResponse, AdkError> {
255        let client = self.client.clone();
256        let api_key = self.config.api_key.clone();
257        let retry_config = self.retry_config.clone();
258        let url = url.to_string();
259        execute_with_retry(&retry_config, is_retryable_model_error, || {
260            let client = client.clone();
261            let url = url.clone();
262            let api_key = api_key.clone();
263            let body = body.clone();
264            async move {
265                let response = client
266                    .post(&url)
267                    .header("Authorization", format!("Bearer {api_key}"))
268                    .header("Content-Type", "application/json")
269                    .json(&body)
270                    .send()
271                    .await
272                    .map_err(|e| {
273                        AdkError::new(
274                            ErrorComponent::Model,
275                            crate::http_timeouts::transport_category(&e),
276                            "model.muse.request",
277                            format!("Muse images request failed: {e}"),
278                        )
279                        .with_provider("muse")
280                    })?;
281                Self::read_response(response).await
282            }
283        })
284        .await
285    }
286
287    async fn read_response(response: reqwest::Response) -> Result<ImagesResponse, AdkError> {
288        if !response.status().is_success() {
289            let status = response.status();
290            let status_code = status.as_u16();
291            let retry_after = response
292                .headers()
293                .get(reqwest::header::RETRY_AFTER)
294                .and_then(|value| value.to_str().ok())
295                .and_then(crate::retry::parse_retry_after);
296            let error_text = response.text().await.unwrap_or_default();
297            let error = AdkError::new(
298                ErrorComponent::Model,
299                crate::retry::category_for_status_code(status_code),
300                "model.muse.api_error",
301                format!(
302                    "Muse images API error (HTTP {status}): {}",
303                    adk_core::upstream_excerpt(&error_text)
304                ),
305            )
306            .with_upstream_status(status_code)
307            .with_provider("muse");
308            return Err(crate::retry::with_retry_after(error, retry_after));
309        }
310        let text = response
311            .text()
312            .await
313            .map_err(|e| AdkError::model(format!("Failed to read images response: {e}")))?;
314        serde_json::from_str(&text).map_err(|e| {
315            AdkError::model(format!(
316                "Failed to parse images response: {}",
317                adk_core::json_error_summary(&e)
318            ))
319        })
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn image_bytes_decode_base64() {
329        let data =
330            ImageData { b64_json: Some("aGVsbG8=".to_string()), url: None, revised_prompt: None };
331        assert_eq!(data.bytes().unwrap(), b"hello");
332    }
333
334    #[test]
335    fn image_bytes_require_a_body() {
336        let data = ImageData {
337            b64_json: None,
338            url: Some("https://example.com/x.png".to_string()),
339            revised_prompt: None,
340        };
341        assert!(data.bytes().is_err());
342    }
343}