reflow_api_services 0.2.0

Generated API-service actor catalog for Reflow — thousands of actors across ~90 third-party services.
Documentation
#![allow(clippy::all, unused_imports, dead_code)]

//! Auto-generated API actors for Stability AI
//!
//! Service: Stability AI (stability_ai)
//! Generative AI models for images and text
//!
//! Required env var: STABILITY_AI_API_KEY (Bearer token)
//!
//! Generated by api-schema-gen codegen — do not edit manually.

use crate::{Actor, ActorBehavior, Message, Port};
use anyhow::{Error, Result};
use reflow_actor::{message::EncodableValue, ActorContext};
use reflow_actor_macro::actor;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::time::Duration;

const BASE_URL: &str = "https://api.stability.ai/v1";
const ENV_KEY: &str = "STABILITY_AI_API_KEY";

/// Apply authentication to the request builder.
fn apply_auth(
    config: &reflow_actor::ActorConfig,
    mut builder: reqwest::RequestBuilder,
) -> Result<reqwest::RequestBuilder> {
    let credential = config
        .get_config_or_env(ENV_KEY)
        .ok_or_else(|| anyhow::anyhow!("Missing env var: {}", ENV_KEY))?;
    builder = builder.header("Authorization", format!("Bearer {}", credential));
    Ok(builder)
}

/// generate image via Stability AI API
///
/// Method: POST /generation/{engine_id}/text-to-image
#[actor(
    StabilityAiGenerateImageActor,
    inports::<100>(engine_id, text_prompts),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn stability_ai_generate_image(
    context: ActorContext,
) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let mut endpoint = "/generation/{engine_id}/text-to-image".to_string();
    if let Some(val) = inputs.get("engine_id") {
        endpoint = endpoint.replace("{{engine_id}}", &super::message_to_str(val));
    }

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.post(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut body = serde_json::Map::new();
    if let Some(val) = inputs.get("text_prompts") {
        body.insert("text_prompts".to_string(), val.clone().into());
    }
    if !body.is_empty() {
        builder = builder.json(&serde_json::Value::Object(body));
    }

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(
                    format!("POST /generation/{{engine_id}}/text-to-image failed: {}", e).into(),
                ),
            );
        }
    }

    Ok(output)
}

/// list
///
/// Method: GET /engines/list
#[actor(
    StabilityAiListEnginesActor,
    inports::<100>(trigger),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn stability_ai_list_engines(
    context: ActorContext,
) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let endpoint = "/engines/list".to_string();

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.get(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(format!("GET /engines/list failed: {}", e).into()),
            );
        }
    }

    Ok(output)
}

/// image-to-image
///
/// Method: POST /generation/{engine_id}/image-to-image
#[actor(
    StabilityAiCreateV1alphaGenerationActor,
    inports::<100>(init_image, options),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn stability_ai_create_v1alpha_generation(
    context: ActorContext,
) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let endpoint = "/generation/{engine_id}/image-to-image".to_string();

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.post(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut body = serde_json::Map::new();
    if let Some(val) = inputs.get("init_image") {
        body.insert("init_image".to_string(), val.clone().into());
    }
    if let Some(val) = inputs.get("options") {
        body.insert("options".to_string(), val.clone().into());
    }
    if !body.is_empty() {
        builder = builder.json(&serde_json::Value::Object(body));
    }

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(
                    format!(
                        "POST /generation/{{engine_id}}/image-to-image failed: {}",
                        e
                    )
                    .into(),
                ),
            );
        }
    }

    Ok(output)
}

/// account
///
/// Method: GET /user/account
#[actor(
    StabilityAiListV1alphaUserActor,
    inports::<100>(trigger),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn stability_ai_list_v1alpha_user(
    context: ActorContext,
) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let endpoint = "/user/account".to_string();

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.get(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(format!("GET /user/account failed: {}", e).into()),
            );
        }
    }

    Ok(output)
}