DEVSAIO

Call AI models from Rust with reqwest and serde

An async Rust example for chat completions against DEVSAIO, with proper error handling.

DEVSAIO team · 1 min read
Share on X
toml
# Cargo.toml
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Msg { role: String, content: String }

#[derive(Serialize)]
struct Req<'a> { model: &'a str, messages: Vec<Msg>, max_tokens: u32 }

#[derive(Deserialize)]
struct Choice { message: Msg }

#[derive(Deserialize)]
struct Resp { choices: Option<Vec<Choice>>, error: Option<serde_json::Value> }

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("DEVSAIO_API_KEY")?;
    let client = reqwest::Client::new();
    let body = Req {
        model: "claude-sonnet-4-6",
        messages: vec![Msg { role: "user".into(), content: "Explain Rust ownership in 3 sentences.".into() }],
        max_tokens: 500,
    };
    let res = client.post("https://devsaio.lol/v1/chat/completions").bearer_auth(key).json(&body).send().await?;
    let status = res.status();
    let out: Resp = res.json().await?;
    match out.choices {
        Some(c) if status.is_success() && !c.is_empty() => println!("{}", c[0].message.content),
        _ => eprintln!("AI error {}: {:?}", status, out.error),
    }
    Ok(())
}

For streaming, enable reqwest's stream feature and parse data: lines from bytes_stream().

Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading