Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Tool agent

Models are unreliable at exact arithmetic, so this example gives the agent a tool for it. The tool_agent example gives an agent one tool, add, and asks it a sum. We write the tool first, as a plain fn with #[tool]:

#![allow(unused)]
fn main() {
use troupekit::prelude::*;

/// Adds two numbers.
#[tool]
pub async fn add(a: i64, b: i64) -> i64 {
    a + b
}
}

Then we name it in the agent's tools key and ask a question:

mod tools;
use tools::add;
use troupekit::prelude::*;

/// Adds numbers with the add tool.
#[agent(model = "openai/gpt-6-luna", tools = [add])]
fn calc() {}

#[tokio::main]
async fn main() -> Result<(), KitError> {
    println!("{}", calc().run("What is 2 + 40?").await?);
    Ok(())
}

Run it

export OPENAI_API_KEY="sk-..."
cargo run -p troupekit --example tool_agent

What happens

  1. The model sees the add tool with the schema {a: integer, b: integer}, built from the fn arguments.
  2. The model asks for add with a = 2 and b = 40. The registry checks the arguments against the schema and calls the fn.
  3. The result goes back to the model, which answers with the sum.

That is two model calls for one question: one that asks for the tool and one that answers. The kit tests check both facts against a scripted model. tool_agent_runs_lab2_flow expects The sum is 42, and run_with_returns_usage_calls_and_messages counts the two calls.

Tools covers the tool(..) form and the web and HTTP tools.