kavel 0.2.0

Generate and edit images from Rust with no API key and no account, via the free tier of kavel.ai
Documentation
//! Generate and edit images from Rust with no API key and no account.
//!
//! This crate calls the anonymous tier of [Kavel](https://www.kavel.ai), which
//! meters its free allowance against a client id the crate invents rather than
//! an account you register, so a program using it runs on a machine with
//! nothing configured.
//!
//! ```no_run
//! let img = kavel::generate("a paper boat at sunrise", &kavel::Options::default())?;
//! println!("{}", img.url);
//! # Ok::<(), kavel::Error>(())
//! ```
//!
//! Measured against the running service: a signed-out caller is granted 15
//! credits, one generated image costs 5 and one edit costs 15, so the crate
//! mints a fresh client id per call. A ceiling of 30 credits per IP per day sits
//! above that. Free output is 1K and watermarked.

use serde::Deserialize;
use serde_json::{json, Value};
use std::fmt;
use std::thread::sleep;
use std::time::{Duration, Instant};

/// The service this crate talks to.
pub const BASE_URL: &str = "https://www.kavel.ai";
/// Credit balance a signed-out caller starts with.
pub const ANON_GRANT: u32 = 15;
/// What one generated image costs, so the grant pays for three.
pub const COST_TEXT_TO_IMAGE: u32 = 5;
/// What one edit costs: the whole grant, so one edit per client id.
pub const COST_EDIT: u32 = 15;
/// Credits one machine may spend per day regardless of client ids.
pub const IP_DAILY_CEILING: u32 = 30;
/// The free text-to-image engine.
pub const MODEL_GENERATE: &str = "kavel-image-v1";
/// The free image-to-image engine.
pub const MODEL_EDIT: &str = "nano-banana-2-lite";

/// One finished picture.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    /// A permanent, cacheable CDN link.
    pub url: String,
    /// Whether a mark was actually drawn on it. Signing in removes it.
    pub watermarked: bool,
}

/// Tunes a single call. `Options::default()` is a square image with a six minute deadline.
#[derive(Debug, Clone)]
pub struct Options {
    /// One of "1:1", "16:9", "9:16", "4:3", "3:4". Ignored by [`edit`].
    pub aspect_ratio: String,
    /// How often the job is polled.
    pub poll_every: Duration,
    /// Bounds the whole call.
    pub timeout: Duration,
    /// Override for tests or a proxy.
    pub base_url: String,
    /// An API key from <https://www.kavel.ai/settings/apikeys>. With a key the
    /// call runs on your account: your credits, your plan's models, and no
    /// watermark on a paid plan. `None` reads `KAVEL_API_KEY`, and without that
    /// the call runs on the free anonymous tier.
    pub api_key: Option<String>,
    /// Engine override. Only honoured with an API key.
    pub model: Option<String>,
}

impl Options {
    fn key(&self) -> Option<String> {
        self.api_key
            .clone()
            .or_else(|| std::env::var("KAVEL_API_KEY").ok())
            .filter(|k| !k.is_empty())
    }
    fn model_or(&self, free: &str) -> String {
        match (self.key(), &self.model) {
            (Some(_), Some(m)) => m.clone(),
            _ => free.to_string(),
        }
    }
}

impl Default for Options {
    fn default() -> Self {
        Options {
            aspect_ratio: "1:1".into(),
            poll_every: Duration::from_secs(5),
            timeout: Duration::from_secs(360),
            base_url: BASE_URL.into(),
            api_key: None,
            model: None,
        }
    }
}

/// Everything that can go wrong, split by what the caller should do next.
#[derive(Debug)]
pub enum Error {
    /// A bad argument; fix the call.
    Invalid(&'static str),
    /// The free allowance is spent for this client id or this machine today. Wait, or sign in.
    Quota(String),
    /// The content filter or the model refused the prompt. Reword it.
    Rejected,
    /// The request needs a signed-in account or a plan that includes this model.
    SignIn(String),
    /// The API key is invalid or has been deleted.
    Auth(String),
    /// The deadline passed while the job was still queued or running.
    Timeout,
    /// The service answered with an error message.
    Service(String),
    /// The network or the response body failed.
    Transport(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Invalid(m) => write!(f, "kavel: {m}"),
            Error::Quota(m) => write!(
                f,
                "kavel: allowance spent: {m} (create an API key at https://www.kavel.ai/settings/apikeys to keep going)"
            ),
            Error::Rejected => write!(f, "kavel: prompt refused"),
            Error::SignIn(m) => write!(f, "kavel: this needs a signed-in account: {m}"),
            Error::Auth(m) => write!(f, "kavel: {m}"),
            Error::Timeout => write!(f, "kavel: deadline passed"),
            Error::Service(m) => write!(f, "kavel: {m}"),
            Error::Transport(m) => write!(f, "kavel: transport: {m}"),
        }
    }
}

impl std::error::Error for Error {}

#[derive(Deserialize)]
struct Envelope {
    code: i64,
    #[serde(default)]
    message: String,
    #[serde(default)]
    data: Value,
}

/// A fresh client id. The grant pays for three images or one edit, so a reused
/// id walls partway through a loop for reasons the caller cannot see.
pub fn anon_id() -> String {
    let mut b = [0u8; 8];
    if getrandom::getrandom(&mut b).is_err() {
        let n = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        return format!("rs-{n}");
    }
    let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
    format!("rs-{hex}")
}

/// Turn a prompt into a new image.
///
/// Naming the light, the material and the composition moves the result far
/// more than adding adjectives.
pub fn generate(prompt: &str, opts: &Options) -> Result<Image, Error> {
    if prompt.trim().is_empty() {
        return Err(Error::Invalid("prompt is required"));
    }
    let ratio = if opts.aspect_ratio.is_empty() { "1:1" } else { &opts.aspect_ratio };
    run(
        opts,
        json!({
            "provider": "kie", "mediaType": "image", "model": opts.model_or(MODEL_GENERATE),
            "scene": "text-to-image", "prompt": prompt,
            "options": { "aspect_ratio": ratio }
        }),
    )
}

/// Rewrite an existing image. `source_url` must be a public http(s) url and
/// `instruction` says what to change.
pub fn edit(source_url: &str, instruction: &str, opts: &Options) -> Result<Image, Error> {
    if !(source_url.starts_with("http://") || source_url.starts_with("https://")) {
        return Err(Error::Invalid("source_url must be a public http(s) url"));
    }
    if instruction.trim().is_empty() {
        return Err(Error::Invalid("instruction is required"));
    }
    run(
        opts,
        json!({
            "provider": "kie", "mediaType": "image", "model": opts.model_or(MODEL_EDIT),
            "scene": "image-to-image", "prompt": instruction,
            "options": { "image_input": [source_url] }
        }),
    )
}

fn agent(timeout: Duration) -> ureq::Agent {
    ureq::AgentBuilder::new()
        .timeout(timeout.min(Duration::from_secs(60)))
        .user_agent(concat!("kavel-rs/", env!("CARGO_PKG_VERSION")))
        .build()
}

fn read(resp: Result<ureq::Response, ureq::Error>) -> Result<Envelope, Error> {
    let resp = match resp {
        Ok(r) => r,
        Err(ureq::Error::Status(_, r)) => r,
        Err(e) => return Err(Error::Transport(e.to_string())),
    };
    resp.into_json::<Envelope>().map_err(|e| Error::Transport(e.to_string()))
}

/// Interpret the submit response. The quota wall answers HTTP 200 with code 0,
/// so it can only be recognised by a field.
pub fn parse_submit(env_code: i64, message: &str, data: &Value) -> Result<String, Error> {
    if env_code != 0 {
        let lower = message.to_lowercase();
        if lower.contains("invalid api key") {
            return Err(Error::Auth(message.to_string()));
        }
        if lower.contains("insufficient credits") {
            return Err(Error::Quota(message.to_string()));
        }
        if lower.contains("sign in") || lower.contains("subscription") {
            return Err(Error::SignIn(message.to_string()));
        }
        return Err(Error::Service(message.to_string()));
    }
    if data.get("wall").and_then(Value::as_bool).unwrap_or(false) {
        let reason = data.get("reason").and_then(Value::as_str).unwrap_or("");
        return match reason {
            "anon_ip_daily" => Err(Error::Quota(format!(
                "this machine has used its {IP_DAILY_CEILING} credits for today"
            ))),
            "anon_unmetered_video" => Err(Error::SignIn("video".into())),
            _ => Err(Error::Quota(reason.to_string())),
        };
    }
    match data.get("id").and_then(Value::as_str) {
        Some(id) if !id.is_empty() => Ok(id.to_string()),
        _ => Err(Error::Service("the service returned no task id".into())),
    }
}

fn run(opts: &Options, payload: Value) -> Result<Image, Error> {
    let started = Instant::now();
    let agent = agent(opts.timeout);
    // With a key the account is the identity; without one, a fresh anonymous id.
    let key = opts.key();
    let id = anon_id();
    let auth = |req: ureq::Request| match &key {
        Some(k) => req.set("Authorization", &format!("Bearer {k}")),
        None => req.set("x-anon-id", &id),
    };

    let env = read(auth(agent.post(&format!("{}/api/ai/generate", opts.base_url))).send_json(payload))?;
    let task = parse_submit(env.code, &env.message, &env.data)?;

    // Queued runs only reach the model on the poll that crosses the end of the
    // wait, so polling is what starts the work.
    loop {
        if started.elapsed() >= opts.timeout {
            return Err(Error::Timeout);
        }
        sleep(opts.poll_every);
        let polled = if key.is_some() {
            auth(agent.post(&format!("{}/api/ai/query", opts.base_url))).send_json(json!({ "taskId": task }))
        } else {
            auth(agent.get(&format!(
                "{}/api/ai/anon-query?taskId={}&provider=kie&mediaType=image",
                opts.base_url, task
            )))
            .call()
        };
        // A dropped connection mid-queue is not a failed generation; keep polling.
        let env = match read(polled) {
            Ok(e) if e.code == 0 => e,
            _ => continue,
        };
        if let Some(url) = env.data.get("cleanImages").and_then(|v| v.get(0)).and_then(Value::as_str) {
            return Ok(Image { url: url.to_string(), watermarked: false });
        }
        if let Some(url) = env.data.get("images").and_then(|v| v.get(0)).and_then(Value::as_str) {
            let watermarked = env
                .data
                .get("watermarked")
                .and_then(|v| v.get(0))
                .and_then(Value::as_bool)
                .unwrap_or(false);
            return Ok(Image { url: url.to_string(), watermarked });
        }
        match env.data.get("status").and_then(Value::as_str) {
            Some("failed") | Some("error") => return Err(Error::Rejected),
            _ => {}
        }
    }
}

/// What a client id has left. Costs nothing to call. `None` asks about a fresh id.
pub fn credits(client_id: Option<&str>) -> Result<(u32, u32), Error> {
    let id = client_id.map(str::to_string).unwrap_or_else(anon_id);
    let env = read(
        agent(Duration::from_secs(30))
            .get(&format!("{BASE_URL}/api/ai/anon-credits"))
            .set("x-anon-id", &id)
            .call(),
    )?;
    if env.code != 0 {
        return Err(Error::Service(env.message));
    }
    let n = |k: &str| env.data.get(k).and_then(Value::as_u64).unwrap_or(0) as u32;
    Ok((n("remaining"), n("grant")))
}

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

    #[test]
    fn ids_are_unique() {
        assert_ne!(anon_id(), anon_id());
        assert!(anon_id().starts_with("rs-"));
    }

    #[test]
    fn validates_arguments() {
        let o = Options::default();
        assert!(matches!(generate("  ", &o), Err(Error::Invalid(_))));
        assert!(matches!(edit("file:///x.png", "hi", &o), Err(Error::Invalid(_))));
        assert!(matches!(edit("https://x/y.png", "", &o), Err(Error::Invalid(_))));
    }

    #[test]
    fn wall_is_a_200_recognised_by_field() {
        let d = json!({"wall": true, "reason": "anon_ip_daily"});
        assert!(matches!(parse_submit(0, "ok", &d), Err(Error::Quota(_))));
        let d = json!({"wall": true, "reason": "anon_credits"});
        assert!(matches!(parse_submit(0, "ok", &d), Err(Error::Quota(_))));
    }

    #[test]
    fn sign_in_refusal() {
        let r = parse_submit(-1, "Please sign in to use this model", &Value::Null);
        assert!(matches!(r, Err(Error::SignIn(_))));
    }

    #[test]
    fn key_errors_map_to_their_variants() {
        assert!(matches!(parse_submit(-1, "invalid API key — create one", &Value::Null), Err(Error::Auth(_))));
        assert!(matches!(parse_submit(-1, "insufficient credits", &Value::Null), Err(Error::Quota(_))));
    }

    #[test]
    fn model_override_only_with_a_key() {
        let mut o = Options { model: Some("gpt-image-2".into()), ..Default::default() };
        std::env::remove_var("KAVEL_API_KEY");
        assert_eq!(o.model_or(MODEL_GENERATE), MODEL_GENERATE);
        o.api_key = Some("sk-abc".into());
        assert_eq!(o.model_or(MODEL_GENERATE), "gpt-image-2");
    }

    #[test]
    fn task_id_extracted() {
        assert_eq!(parse_submit(0, "ok", &json!({"id": "t1"})).unwrap(), "t1");
        assert!(matches!(parse_submit(0, "ok", &json!({})), Err(Error::Service(_))));
    }
}