Skip to main content

tool

Attribute Macro tool 

Source
#[tool]
Expand description

Converts an async function into an AI tool that can be called by language models.

This procedural macro generates the necessary boilerplate code to make your function callable through the aither::llm::Tool trait.

Tool description is extracted from rustdoc on the Args struct via schemars::JsonSchema.

§Arguments

  • rename (optional): A custom name for the tool. If not provided, uses the function name.

§Examples

§Basic Usage

use aither::Result;
use aither_derive::tool;
use schemars::JsonSchema;
use serde::Deserialize;

/// Get the current system time.
#[derive(JsonSchema, Deserialize)]
pub struct CurrentTimeArgs;

#[tool]
pub async fn current_time(_args: CurrentTimeArgs) -> Result<String> {
    Ok(chrono::Utc::now().to_rfc3339())
}

§With Parameters

use schemars::JsonSchema;
use serde::Deserialize;

/// Send an email to a recipient.
#[derive(JsonSchema, Deserialize)]
pub struct EmailRequest {
    /// Recipient email address
    pub to: String,
    /// Email subject line
    pub subject: String,
    /// Email body content
    pub body: String,
}

#[tool]
pub async fn send_email(request: EmailRequest) -> Result<String> {
    Ok(format!("Email sent to {}", request.to))
}

§With Custom Name

/// Perform complex mathematical calculations.
#[derive(JsonSchema, Deserialize)]
pub struct CalcArgs {
    pub expression: String,
}

#[tool(rename = "calculator")]
pub async fn complex_math_function(args: CalcArgs) -> Result<f64> {
    Ok(42.0)
}

§Generated Code

For a function named search, the macro generates:

  1. A SearchArgs struct (if the function has multiple parameters)
  2. A Search struct that implements aither::llm::Tool
  3. All necessary trait implementations for JSON schema generation and deserialization

§Requirements

  • Function must be async
  • Return type must be Result<T> where T implements serde::Serialize
  • Parameters must implement serde::Deserialize and schemars::JsonSchema
  • No self parameters (only free functions are supported)
  • No lifetime parameters or generics

§Errors

The macro will produce compile-time errors if:

  • The function is not async
  • The function has self parameters
  • The function has more than the supported number of parameters
  • Required attributes are missing