aidaemon-sdk 0.24.0

Build agents in Rust on the aidaemon kernel: one crate, a feature per subsystem (providers, tools, policies, memory, channels)
Documentation
//! Runtime support for code generated by `#[tool]`. Not a public API: the
//! macro's output is the only intended caller.

pub use aidaemon_core;
pub use async_trait;
pub use schemars;
pub use serde;
pub use serde_json;

use aidaemon_core::{ToolError, ToolOutput, ToolResult};
use serde::de::DeserializeOwned;
use serde_json::Value;

/// The closed parameters schema for `T`.
pub fn parameters<T: schemars::JsonSchema>() -> Value {
    crate::schema::tool_parameters::<T>()
}

/// Read a call's arguments as `T`. Refuses anything but an object, keys the
/// schema does not declare (so a type without `deny_unknown_fields` is as
/// closed as its schema says), and whatever `T` does not deserialize from.
pub fn parse_arguments<T: DeserializeOwned + schemars::JsonSchema>(
    arguments: &Value,
) -> Result<T, String> {
    let Some(object) = arguments.as_object() else {
        return Err("arguments must be a JSON object".to_string());
    };
    let schema = parameters::<T>();
    if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
        let unknown: Vec<&str> = object
            .keys()
            .filter(|key| !properties.contains_key(key.as_str()))
            .map(String::as_str)
            .collect();
        if !unknown.is_empty() {
            return Err(format!("unknown argument(s): {}", unknown.join(", ")));
        }
    }
    serde_json::from_value(arguments.clone()).map_err(|err| format!("invalid arguments: {err}"))
}

/// What a `#[tool]` function may return.
pub trait IntoToolResult {
    fn into_tool_result(self) -> ToolResult;
}

impl IntoToolResult for ToolOutput {
    fn into_tool_result(self) -> ToolResult {
        Ok(self)
    }
}

impl IntoToolResult for String {
    fn into_tool_result(self) -> ToolResult {
        Ok(ToolOutput::text(self))
    }
}

impl IntoToolResult for &str {
    fn into_tool_result(self) -> ToolResult {
        Ok(ToolOutput::text(self))
    }
}

impl IntoToolResult for Value {
    fn into_tool_result(self) -> ToolResult {
        Ok(ToolOutput::text(self.to_string()).with_details(self))
    }
}

impl<T: IntoToolResult, E: std::fmt::Display> IntoToolResult for Result<T, E> {
    fn into_tool_result(self) -> ToolResult {
        match self {
            Ok(value) => value.into_tool_result(),
            Err(err) => Err(ToolError(err.to_string())),
        }
    }
}