Skip to main content

Tool

A Tool is one function the model can call. It tells the model its name and what arguments it takes, and runs when the model asks for it. #[tool] writes the implementation for a plain Rust function, so write one by hand when the tool needs something a function cannot hold: a connection pool, a client with its own rate limit, a name or schema only known at run time, or another tool to wrap.

This page is the contract for an implementation. Tool calling covers #[tool], ToolDefinition and how tool calls travel on the wire.

The trait​

pub type ToolFuture<'a> = Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>>;
pub type MeteredFuture<'a> =
Pin<Box<dyn Future<Output = (Result<String, ToolError>, Option<Usage>)> + Send + 'a>>;

pub trait Tool: Send + Sync {
fn name(&self) -> &str;
fn definition(&self) -> ToolDefinition;
fn call<'a>(&'a self, arguments: &'a str, cx: &'a Context) -> ToolFuture<'a>;

fn call_metered<'a>(&'a self, arguments: &'a str, cx: &'a Context) -> MeteredFuture<'a> {
Box::pin(async move { (self.call(arguments, cx).await, None) })
}
}

The futures are boxed because Agent keeps its tools as Arc<dyn Tool>, and an async fn in a trait cannot be called through dyn. They are Send because an agent runs the calls of one turn at once.

name​

The name the model calls the tool by. It must match the name in definition, because the agent looks a requested call up by this method and the model only ever sees the definition.

Names are unique within an agent. Registering a second tool under the same name replaces the first, so a tool registered later overrides a built-in one of the same name.

definition​

The ToolDefinition sent to the model: the name, a description the model reads to decide when to call the tool, and a JSON Schema for the arguments.

The agent calls it once, when the tool is registered with Agent::tool or Agent::tools, and never again. The schema is therefore fixed for the life of the agent and cannot depend on who is asking. Per-run data reaches call through the Context instead.

ToolDefinition::new(name, description) starts with the schema of a tool that takes no arguments, the empty object, and .parameters(json) replaces it. .strict(true) asks the provider to hold the model to the schema exactly. With strict on, OpenAI requires every property listed in required and additionalProperties: false.

call​

Runs the tool. arguments is the model's raw JSON text, exactly as it wrote it, and cx is the run's Context. The returned string is what the model reads as the result.

Treat arguments as untrusted input. The model can write anything, including JSON that does not match the schema you sent, even with strict on some providers. Parse it and return ToolError::Arguments when it does not fit.

A failure is returned, not raised. Whatever call returns, Ok or Err, goes back to the model as the tool result, and the run carries on. An Err reaches it as error: followed by the error's Display text, so the model can correct its arguments or tell the user. Write error messages for the model to read.

VariantUse it when
ToolError::Arguments(serde_json::Error)The arguments did not parse into what the tool expects
ToolError::Execution(String)The tool ran and failed, or refused
ToolError::Result(serde_json::Error)The tool's output could not be serialized

A panic in call is not a tool failure. It ends the run.

Work that only needs &self can run before Box::pin, and the future then owns what it needs. Anything slow belongs inside the future, so it runs concurrently with the turn's other calls rather than before them. A tool that blocks a thread without awaiting stalls every other call of its turn, so send blocking work to tokio::task::spawn_blocking or your runtime's equivalent.

call_metered​

This is the method the agent actually calls. It returns the result together with the tokens the tool spent on model calls of its own. The default runs call and reports None, which is right for any tool that calls no model.

Override it in a tool that calls a model. The agent adds what it reports to Run::usage and counts it against Agent::token_budget and any Budget in the context. Agent::into_tool is the built-in tool that does this.

A tool that wraps another must forward call_metered as well as call. A wrapper that forwards only call makes the inner tool's tokens disappear from the run's usage.

Where state goes​

State known when the tool is built, such as a database pool or an HTTP client, goes in the struct's fields. One tool value serves every run of the agent, and runs can call it at the same time, so mutable state goes behind an atomic or a lock.

State that only exists once a run starts, such as the user, the tenant or a request id, goes in the Context. The caller inserts it and passes the context to an ask or a send with .context(&cx), and every tool call of that run sees it. Context is keyed by type, so give each value its own newtype. cx.require::<T>() returns a ToolError::Execution naming the missing type, ready to return with ?.

Example: a directory lookup​

This tool finds a colleague's email address. The directory is fixed when the tool is built, so it is a field. The tenant differs per user, so it comes from the Context, and the model never sees it in the schema and cannot supply its own.

use freyja::{Context, Tool, ToolDefinition, ToolError, ToolFuture};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;

struct Tenant(String);

#[derive(Deserialize)]
struct LookupArguments {
name: String,
}

struct Directory {
people: HashMap<(String, String), String>,
}

impl Tool for Directory {
fn name(&self) -> &str {
"lookup_person"
}

fn definition(&self) -> ToolDefinition {
ToolDefinition::new("lookup_person", "Finds a colleague's email address by their full name")
.parameters(json!({
"type": "object",
"properties": {
"name": {"type": "string", "description": "The person's full name"}
},
"required": ["name"],
"additionalProperties": false
}))
.strict(true)
}

fn call<'a>(&'a self, arguments: &'a str, cx: &'a Context) -> ToolFuture<'a> {
Box::pin(async move {
let arguments: LookupArguments =
serde_json::from_str(arguments).map_err(ToolError::Arguments)?;
let tenant = cx.require::<Tenant>()?;
let key = (tenant.0.clone(), arguments.name.to_lowercase());
match self.people.get(&key) {
Some(email) => Ok(email.clone()),
None => Err(ToolError::Execution(format!(
"no one named {} in this directory",
arguments.name
))),
}
})
}
}

Register it and pass the tenant with the run:

let agent = Agent::new(client).tool(Directory { people });

let mut cx = Context::new();
cx.insert(Tenant("acme".to_string()));
let run = agent.ask("What is Ada Lovelace's email?").context(&cx).await?;

A name that is not in the directory does not end the run. The model reads error: no one named Grace Hopper in this directory and answers the user with that.

Example: a timeout around any tool​

A wrapper is a tool that holds another tool. This one gives any tool, including one you did not write, a time limit. It holds Arc<T> with T: ?Sized, so it wraps a concrete tool and an Arc<dyn Tool> alike, and it forwards call_metered so a wrapped tool's tokens are still counted.

use freyja::{Context, MeteredFuture, Tool, ToolDefinition, ToolError, ToolFuture};
use std::sync::Arc;
use std::time::Duration;

struct Timeout<T: ?Sized> {
inner: Arc<T>,
budget: Duration,
}

impl<T: Tool + ?Sized> Tool for Timeout<T> {
fn name(&self) -> &str {
self.inner.name()
}

fn definition(&self) -> ToolDefinition {
self.inner.definition()
}

fn call<'a>(&'a self, arguments: &'a str, cx: &'a Context) -> ToolFuture<'a> {
Box::pin(async move {
tokio::time::timeout(self.budget, self.inner.call(arguments, cx))
.await
.unwrap_or_else(|_| {
Err(ToolError::Execution(format!("timed out after {:?}", self.budget)))
})
})
}

fn call_metered<'a>(&'a self, arguments: &'a str, cx: &'a Context) -> MeteredFuture<'a> {
Box::pin(async move {
tokio::time::timeout(self.budget, self.inner.call_metered(arguments, cx))
.await
.unwrap_or_else(|_| {
let error = format!("timed out after {:?}", self.budget);
(Err(ToolError::Execution(error)), None)
})
})
}
}

A timed-out call reaches the model as error: timed out after 5s. Dropping the inner future cancels only work that is awaiting, so a tool that blocks its thread is not stopped by this, and no timer fires while it blocks.

Example: search a vector database​

A vector database usually plugs in as a VectorStore, and Index::into_tool supplies the tool. Write the tool yourself when the search needs what a store does not answer, such as filters on metadata, a keyword search mixed in, or output that is not plain text.

VectorSearch embeds the model's query with any Embedder, asks the database for the nearest texts, and turns them into Hits, the type an Index search returns. VectorDb stands in for the database's own client.

use freyja::{Context, EmbedRequest, Embedder, Hit, Tool, ToolDefinition, ToolError, ToolFuture};
use serde::Deserialize;
use serde_json::json;
use std::sync::Arc;

// The database's own client: a Faiss index, Qdrant, pgvector.
trait VectorDb: Send + Sync {
fn nearest(&self, vector: &[f32], k: usize) -> Vec<(String, f32)>;
}

#[derive(Deserialize)]
struct SearchArguments {
query: String,
}

struct VectorSearch<D> {
db: D,
embedder: Arc<dyn Embedder>,
model: String,
k: usize,
}

impl<D: VectorDb> Tool for VectorSearch<D> {
fn name(&self) -> &str {
"search_documents"
}

fn definition(&self) -> ToolDefinition {
ToolDefinition::new("search_documents", "Searches the company documents by meaning")
.parameters(json!({
"type": "object",
"properties": {"query": {"type": "string", "description": "What to look for"}},
"required": ["query"],
"additionalProperties": false
}))
}

fn call<'a>(&'a self, arguments: &'a str, _cx: &'a Context) -> ToolFuture<'a> {
Box::pin(async move {
let arguments: SearchArguments =
serde_json::from_str(arguments).map_err(ToolError::Arguments)?;
let request = EmbedRequest::new(self.model.clone(), [arguments.query]);
let embeddings = self
.embedder
.embed(&request)
.await
.map_err(|error| ToolError::Execution(format!("could not embed the query: {error}")))?;
let hits: Vec<Hit> = self
.db
.nearest(&embeddings.vectors[0], self.k)
.into_iter()
.map(|(text, score)| Hit::new(text, score))
.collect();
if hits.is_empty() {
return Ok("no documents matched".to_string());
}
Ok(hits
.iter()
.map(|hit| format!("[{:.2}] {}", hit.score, hit.text))
.collect::<Vec<_>>()
.join("\n"))
})
}
}

The embedder is an Arc<dyn Embedder>, so the crate's user chooses it: a Client for a provider's embeddings, or a local model through Embedder. It must be the same model that embedded the stored texts, or the distances mean nothing.

An empty result is a successful answer, not an error, so the model reads that nothing matched and can rephrase. A database whose client blocks, as Faiss's bindings do, runs the search on a blocking thread.

Testing it​

A tool is a value with an async method, so a test calls it directly with a Context it builds:

#[tokio::test]
async fn the_directory_finds_a_person_in_the_callers_tenant() {
let tool = directory();
let mut cx = Context::new();
cx.insert(Tenant("acme".to_string()));

let found = tool.call(r#"{"name":"Ada Lovelace"}"#, &cx).await.unwrap();
assert_eq!(found, "ada@acme.example");

let missing = tool.call(r#"{"name":"Grace Hopper"}"#, &cx).await;
assert_eq!(missing.unwrap_err().to_string(), "no one named Grace Hopper in this directory");

assert!(matches!(tool.call("not json", &cx).await, Err(ToolError::Arguments(_))));
}

To check what the model reads, run the tool in an agent over a ScriptedModel and look at the request that followed the call:

use freyja::testing::ScriptedModel;

let model = Arc::new(
ScriptedModel::new()
.tool_call("lookup_person", json!({"name": "Grace Hopper"}))
.text("I could not find her."),
);
let run = Agent::new(model.clone())
.tool(directory())
.ask("What is Grace Hopper's email?").context(&cx)
.await?;

let shown = format!("{:?}", model.requests()[1].messages);
assert!(shown.contains("no one named Grace Hopper"));

Stability​

Tool stays usable as dyn Tool. A method added to it later comes with a default, so an implementation written today keeps compiling. ToolError is not #[non_exhaustive], so a match on it needs no wildcard arm.

See also​

  • Tool calling for #[tool], ToolDefinition, ToolChoice and tools defined at run time
  • Human approval for the guard that decides whether a call may run
  • Hook to observe every tool call without changing any tool
  • Retrieval for Index, the in-memory search this example scales past
  • Testing for ScriptedModel