Skip to main content

openai_rust/
image.rs

1use reqwest::Client;
2use serde_json::json;
3use crate::client::get_api_key;
4
5#[derive(Debug)]
6pub enum ImageGenError {
7    MissingApiKey,
8    InvalidCount,
9    RequestError(reqwest::Error),
10    InvalidResponse,
11}
12
13impl From<reqwest::Error> for ImageGenError {
14    fn from(err: reqwest::Error) -> Self {
15        ImageGenError::RequestError(err)
16    }
17}
18
19/// Generates image(s) from a prompt using DALLĀ·E.
20pub async fn openai_generate_image(prompt: &str, n: u32, size: &str) -> Result<Vec<String>, ImageGenError> {
21    if n == 0 || n > 10 {
22        return Err(ImageGenError::InvalidCount);
23    }
24
25    let api_key = get_api_key().ok_or(ImageGenError::MissingApiKey)?;
26
27    let client = Client::new();
28    let response = client
29        .post("https://api.openai.com/v1/images/generations")
30        .bearer_auth(api_key)
31        .json(&json!({
32            "prompt": prompt,
33            "n": n,
34            "size": size
35        }))
36        .send()
37        .await?;
38
39    let json: serde_json::Value = response.json().await?;
40    if let Some(array) = json["data"].as_array() {
41        let urls: Vec<String> = array
42            .iter()
43            .filter_map(|item| item["url"].as_str().map(|s| s.to_string()))
44            .collect();
45        Ok(urls)
46    } else {
47        Err(ImageGenError::InvalidResponse)
48    }
49}