cencori 1.4.0

Official Rust SDK for Cencori - AI Infrastructure for Production
Documentation
/// Module for managing Cencori Agents.
///
/// Agents are AI agents with configurable model, system prompt, and tools.
/// Each agent can have its own API keys for secure access.
use std::sync::Arc;

use crate::client::{parse_response, InnerClient};
use crate::error::CencoriError;
use crate::types::{
    Agent, AgentKey, AgentListItem, CreateAgentKeyParams, CreateAgentParams, UpdateAgentParams,
};
use serde_json::Value;

/// Module for managing Cencori Agents.
#[derive(Debug, Clone)]
pub struct AgentsModule {
    inner: Arc<InnerClient>,
}

impl AgentsModule {
    pub(crate) fn new(inner: Arc<InnerClient>) -> Self {
        Self { inner }
    }

    /// List all agents.
    ///
    /// Returns a list of agent list items.
    pub fn list(&self) -> Result<Vec<AgentListItem>, CencoriError> {
        let url = self.inner.url("/v1/agents");
        let response = self
            .inner
            .blocking_client
            .get(&url)
            .send()
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        let agents = data["data"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(|a| AgentListItem {
                        id: a["id"].as_str().unwrap_or_default().to_string(),
                        name: a["name"].as_str().unwrap_or_default().to_string(),
                        description: a["description"].as_str().map(String::from),
                        is_active: a["is_active"].as_bool().unwrap_or(false),
                        shadow_mode: a["shadow_mode"].as_bool().unwrap_or(false),
                        created_at: a["created_at"].as_str().unwrap_or_default().to_string(),
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(agents)
    }

    /// Create a new agent.
    pub fn create(&self, params: &CreateAgentParams) -> Result<Agent, CencoriError> {
        let url = self.inner.url("/v1/agents");
        let response = self
            .inner
            .blocking_client
            .post(&url)
            .json(params)
            .send()
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        Self::parse_agent(&data)
    }

    /// Get an agent by ID.
    pub fn get(&self, agent_id: &str) -> Result<Agent, CencoriError> {
        let path = format!("/v1/agents/{agent_id}");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .blocking_client
            .get(&url)
            .send()
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        Self::parse_agent(&data)
    }

    /// Update an agent's configuration.
    pub fn update_config(
        &self,
        agent_id: &str,
        params: &UpdateAgentParams,
    ) -> Result<Agent, CencoriError> {
        let path = format!("/v1/agents/{agent_id}");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .blocking_client
            .patch(&url)
            .json(params)
            .send()
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        Self::parse_agent(&data)
    }

    /// Delete an agent.
    pub fn delete(&self, agent_id: &str) -> Result<(), CencoriError> {
        let path = format!("/v1/agents/{agent_id}");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .blocking_client
            .delete(&url)
            .send()
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().map_err(CencoriError::Http)?;
        parse_response(status, &body)?;
        Ok(())
    }

    /// Create an API key for an agent.
    pub fn create_key(
        &self,
        agent_id: &str,
        params: &CreateAgentKeyParams,
    ) -> Result<AgentKey, CencoriError> {
        let path = format!("/v1/agents/{agent_id}/keys");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .blocking_client
            .post(&url)
            .json(params)
            .send()
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        serde_json::from_value(data).map_err(CencoriError::Json)
    }

    fn parse_agent(data: &Value) -> Result<Agent, CencoriError> {
        serde_json::from_value(data.clone()).map_err(CencoriError::Json)
    }

    // =========================================================================
    // Asynchronous Methods
    // =========================================================================

    /// List all agents asynchronously.
    pub async fn async_list(&self) -> Result<Vec<AgentListItem>, CencoriError> {
        let url = self.inner.url("/v1/agents");
        let response = self
            .inner
            .http_client
            .get(&url)
            .send()
            .await
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().await.map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        let agents = data["data"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(|a| AgentListItem {
                        id: a["id"].as_str().unwrap_or_default().to_string(),
                        name: a["name"].as_str().unwrap_or_default().to_string(),
                        description: a["description"].as_str().map(String::from),
                        is_active: a["is_active"].as_bool().unwrap_or(false),
                        shadow_mode: a["shadow_mode"].as_bool().unwrap_or(false),
                        created_at: a["created_at"].as_str().unwrap_or_default().to_string(),
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(agents)
    }

    /// Create a new agent asynchronously.
    pub async fn async_create(&self, params: &CreateAgentParams) -> Result<Agent, CencoriError> {
        let url = self.inner.url("/v1/agents");
        let response = self
            .inner
            .http_client
            .post(&url)
            .json(params)
            .send()
            .await
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().await.map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        Self::parse_agent(&data)
    }

    /// Get an agent by ID asynchronously.
    pub async fn async_get(&self, agent_id: &str) -> Result<Agent, CencoriError> {
        let path = format!("/v1/agents/{agent_id}");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .http_client
            .get(&url)
            .send()
            .await
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().await.map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        Self::parse_agent(&data)
    }

    /// Update an agent's configuration asynchronously.
    pub async fn async_update_config(
        &self,
        agent_id: &str,
        params: &UpdateAgentParams,
    ) -> Result<Agent, CencoriError> {
        let path = format!("/v1/agents/{agent_id}");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .http_client
            .patch(&url)
            .json(params)
            .send()
            .await
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().await.map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        Self::parse_agent(&data)
    }

    /// Delete an agent asynchronously.
    pub async fn async_delete(&self, agent_id: &str) -> Result<(), CencoriError> {
        let path = format!("/v1/agents/{agent_id}");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .http_client
            .delete(&url)
            .send()
            .await
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().await.map_err(CencoriError::Http)?;
        parse_response(status, &body)?;
        Ok(())
    }

    /// Create an API key for an agent asynchronously.
    pub async fn async_create_key(
        &self,
        agent_id: &str,
        params: &CreateAgentKeyParams,
    ) -> Result<AgentKey, CencoriError> {
        let path = format!("/v1/agents/{agent_id}/keys");
        let url = self.inner.url(&path);
        let response = self
            .inner
            .http_client
            .post(&url)
            .json(params)
            .send()
            .await
            .map_err(CencoriError::Http)?;

        let status = response.status();
        let body = response.text().await.map_err(CencoriError::Http)?;
        let data = parse_response(status, &body)?;

        serde_json::from_value(data).map_err(CencoriError::Json)
    }
}