fauna-api 1.0.814

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use futures_util::stream::BoxStream;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use super::generative::{
    Content, Image, StreamEvent, Text, TextResponse, ToolsOrTool, Video, Voice, VoiceEvent,
};
use super::socket;
use crate::ant::persona::PartialDemographic;
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::groups::Group;
use crate::http::{client, ok};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Memory {
    pub id: u64,
    pub memory: String,
    pub scope: String,
    #[serde(default)]
    pub embedding: Vec<f64>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Memories {
    pub nodes: Vec<Memory>,
    pub edges: Vec<(u64, u64)>,
    pub scopes: Vec<String>,
}

/// Observe: store a new memory. Pass `group` to act on that group's shared
/// memory graph instead of the caller's personal one (caller must be a member).
pub async fn observe(
    authorization: &CredentialsOrApiKey,
    content: &str,
    group: Option<&Group>,
) -> Result<Memory> {
    let mut request = client()
        .post(format!("{}/agent/memories", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.json(&json!({ "content": content })).send().await?;
    Ok(ok(response).await?.json().await?)
}

/// Recall: query associative memory. Pass `group` for that group's shared graph.
pub async fn recall(
    authorization: &CredentialsOrApiKey,
    query: &str,
    scope: Option<&str>,
    group: Option<&Group>,
) -> Result<Vec<Memory>> {
    let mut request = client()
        .post(format!("{}/agent/recall", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let mut body = Map::new();
    body.insert("query".to_string(), Value::from(query));
    if let Some(scope) = scope {
        body.insert("scope".to_string(), Value::from(scope));
    }
    let response = request.json(&body).send().await?;
    Ok(ok(response).await?.json().await?)
}

/// Export: get the full memory graph. Pass `group` for that group's shared graph.
pub async fn export_memory(
    authorization: &CredentialsOrApiKey,
    group: Option<&Group>,
) -> Result<Memories> {
    let mut request = client()
        .get(format!("{}/agent/memories", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.send().await?;
    Ok(ok(response).await?.json().await?)
}

/// Remove: delete a specific memory node. Pass `group` for that group's graph.
pub async fn remove_memory(
    authorization: &CredentialsOrApiKey,
    id: u64,
    group: Option<&Group>,
) -> Result<()> {
    let mut request = client()
        .delete(format!("{}/agent/memories/{id}", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    ok(request.send().await?).await?;
    Ok(())
}

/// Clear: wipe the entire memory graph. Pass `group` for that group's graph.
pub async fn clear_memory(
    authorization: &CredentialsOrApiKey,
    group: Option<&Group>,
) -> Result<()> {
    let mut request = client()
        .delete(format!("{}/agent/memories", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    ok(request.send().await?).await?;
    Ok(())
}

/// The `options` argument of the agent's `generate_text` and `generate_text_sync`:
/// the generative options plus `memories`, how many to recall on the latest
/// request, and `group`, whose memory graph. Dropping the returned stream
/// closes the socket.
#[derive(Debug, Clone, Default)]
pub struct TextOptions {
    pub content: Option<Vec<Content>>,
    pub tools: Option<ToolsOrTool>,
    pub max_tools: Option<u32>,
    pub memories: Option<u32>,
    pub reasoning: Option<String>,
    pub group: Option<Group>,
}

/// Streaming text generation. A singular Tool forces it; an array lets the model
/// choose. Where the model can call tools it can also save memories with
/// observe_memory.
pub async fn generate_text(
    authorization: &CredentialsOrApiKey,
    model: Text,
    options: TextOptions,
) -> Result<BoxStream<'static, StreamEvent>> {
    socket::stream_text(
        authorization,
        "/agent/text",
        model.as_str(),
        socket::TextOptions {
            content: options.content,
            tools: options.tools,
            max_tools: options.max_tools,
            memories: options.memories,
            reasoning: options.reasoning,
            group: options.group,
        },
    )
    .await
}

pub async fn generate_text_sync(
    authorization: &CredentialsOrApiKey,
    model: Text,
    options: TextOptions,
) -> Result<TextResponse> {
    socket::collect_text(generate_text(authorization, model, options).await?).await
}

/// The `options` argument of the agent's `generate_voice` and `generate_voice_sync`.
#[derive(Default)]
pub struct VoiceOptions {
    pub content: Option<Vec<Content>>,
    pub audio: Option<BoxStream<'static, Vec<u8>>>,
    pub notes: Option<BoxStream<'static, String>>,
    pub tools: Option<ToolsOrTool>,
    pub max_tools: Option<u32>,
    pub voice: Option<PartialDemographic>,
    pub memories: Option<u32>,
    pub group: Option<Group>,
}

/// Realtime voice: PCM16 16 kHz in from `audio`, PCM16 24 kHz out as audio events. Each of
/// `notes` tells the model something to act on now.
pub async fn generate_voice(
    authorization: &CredentialsOrApiKey,
    model: Voice,
    options: VoiceOptions,
) -> Result<BoxStream<'static, VoiceEvent>> {
    socket::stream_voice(
        authorization,
        "/agent/voice",
        model.as_str(),
        socket::VoiceOptions {
            content: options.content,
            audio: options.audio,
            notes: options.notes,
            tools: options.tools,
            max_tools: options.max_tools,
            voice: options.voice,
            memories: options.memories,
            group: options.group,
        },
    )
    .await
}

pub async fn generate_voice_sync(
    authorization: &CredentialsOrApiKey,
    model: Voice,
    options: VoiceOptions,
) -> Result<TextResponse> {
    socket::collect_voice(
        authorization,
        generate_voice(authorization, model, options).await?,
    )
    .await
}

/// The `options` argument of the agent's `generate_image`.
#[derive(Debug, Clone, Default)]
pub struct ImageOptions {
    pub content: Option<Vec<Content>>,
    pub size: Option<[u32; 2]>,
    pub memories: Option<u32>,
    pub group: Option<Group>,
}

pub async fn generate_image(
    authorization: &CredentialsOrApiKey,
    model: Image,
    options: ImageOptions,
) -> Result<TextResponse> {
    let mut extra = Map::new();
    if let Some(size) = options.size {
        extra.insert("size".to_string(), json!(size));
    }
    if let Some(memories) = options.memories {
        extra.insert("memories".to_string(), Value::from(memories));
    }
    socket::generate_media(
        authorization,
        "/agent/image",
        model.as_str(),
        options.content,
        options.group,
        extra,
        "image/png",
    )
    .await
}

/// The `options` argument of the agent's `generate_video`.
#[derive(Debug, Clone, Default)]
pub struct VideoOptions {
    pub content: Option<Vec<Content>>,
    pub duration: Option<f64>,
    pub size: Option<[u32; 2]>,
    pub memories: Option<u32>,
    pub group: Option<Group>,
}

pub async fn generate_video(
    authorization: &CredentialsOrApiKey,
    model: Video,
    options: VideoOptions,
) -> Result<TextResponse> {
    let mut extra = Map::new();
    if let Some(duration) = options.duration {
        extra.insert("duration".to_string(), Value::from(duration));
    }
    if let Some(size) = options.size {
        extra.insert("size".to_string(), json!(size));
    }
    if let Some(memories) = options.memories {
        extra.insert("memories".to_string(), Value::from(memories));
    }
    socket::generate_media(
        authorization,
        "/agent/video",
        model.as_str(),
        options.content,
        options.group,
        extra,
        "video/mp4",
    )
    .await
}