#[cfg(feature = "tools-buildin")]
pub mod buildin;
#[cfg(feature = "mcp-client")]
pub mod mcp;
#[cfg(feature = "tools-web")]
pub mod web;
use serde_json::Value;
use thiserror::Error;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Tool {
pub name: String,
pub description: Option<String>,
pub schema: Option<serde_json::Value>,
pub strict: Option<bool>,
}
impl Tool {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
description: None,
schema: None,
strict: None,
}
}
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
self.schema = Some(schema);
self
}
pub fn with_strict(mut self, strict: bool) -> Self {
self.strict = Some(strict);
self
}
}
impl Tool {
pub(crate) fn into_genai(self) -> genai::chat::Tool {
let tool = self;
let mut out = genai::chat::Tool::new(tool.name);
out.description = tool.description;
out.schema = Some(
tool.schema
.unwrap_or_else(|| serde_json::json!({"type": "object", "properties": {}})),
);
out.strict = tool.strict;
out
}
}
pub type ToolResult = Result<String, ToolError>;
#[cfg(feature = "macros")]
pub use agentai_macros::toolbox;
#[async_trait::async_trait]
pub trait ToolBox: Send + Sync + 'static {
fn tools_definitions(&self) -> Result<Vec<Tool>, ToolError>;
async fn call_tool(&self, tool_name: String, arguments: Value) -> ToolResult;
}
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ToolError {
#[error("tool '{0}' not found")]
NotFound(String),
#[error("invalid arguments: {0}")]
InvalidArguments(String),
#[error("{0}")]
Failed(String),
#[error("tool is not configured correctly: {0}")]
Configuration(String),
#[error(transparent)]
Fatal(Box<dyn std::error::Error + Send + Sync>),
}
impl ToolError {
pub fn fatal(err: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
Self::Fatal(err.into())
}
pub fn is_recoverable(&self) -> bool {
matches!(
self,
Self::NotFound(_) | Self::InvalidArguments(_) | Self::Failed(_)
)
}
}
#[derive(Default)]
pub struct ToolBoxSet {
toolboxes: Vec<Box<dyn ToolBox + Send + Sync>>,
}
impl ToolBoxSet {
pub fn new() -> Self {
Self::default()
}
pub fn add_tool(&mut self, toolbox: impl ToolBox) {
self.toolboxes.push(Box::new(toolbox));
}
}
#[async_trait::async_trait]
impl ToolBox for ToolBoxSet {
fn tools_definitions(&self) -> Result<Vec<Tool>, ToolError> {
let mut all_definitions = Vec::new();
for toolbox in &self.toolboxes {
all_definitions.extend(toolbox.tools_definitions()?);
}
Ok(all_definitions)
}
async fn call_tool(&self, tool_name: String, arguments: Value) -> ToolResult {
for toolbox in &self.toolboxes {
match toolbox
.call_tool(tool_name.clone(), arguments.clone())
.await
{
Err(ToolError::NotFound(_)) => {
continue;
}
result => {
return result;
}
};
}
Err(ToolError::NotFound(tool_name))
}
}