Skip to main content

Agents

An agent is the part of Freyja that runs the tool-calling loop for you. You describe it once with a model, tools, a system instruction and limits, and it sends requests, runs the tools the model asks for, feeds the results back and stops when the model answers. This guide covers building one, what a run reports, and how to share one across requests.

What an agent is​

Agent holds configuration only. It does not hold a transcript, a connection or any per-user state. The transcript belongs to a Conversation, which you start from the agent with a Storage backend, so one agent can serve any number of conversations at once.

Agent::new(model) takes anything that implements Model. A Client is one, and so is anything else that can answer a GenerateRequest, such as a scripted model in a test. A new agent has no tools, no system instruction and a bound of ten turns.

use freyja::{Agent, Client, EndpointPreset};

// Connects to OpenAI with the key in OPENAI_API_KEY.
let client = Client::from_env(EndpointPreset::OpenAi)?;

let agent = Agent::new(client)
.model("gpt-5-mini")
.system("You answer in one sentence.")
.max_turns(5);

let run = agent.ask("What is 20 + 22?").await?;
println!("{}", run.answer);

This example calls a real provider, so it needs a key and network access. Client::from_env picks the provider and reads its API key from the environment, and the examples further down this page reuse the same client. Providers lists the others. ask answers one message with no history and keeps nothing, so a second call knows nothing of the first. For a chat, start a conversation.

The builder​

Every method takes self and returns the agent, so they chain. The ones that configure the request, model, max_tokens, temperature, top_p, reasoning_effort, tool_choice and extra_for, set the same fields a GenerateRequest has and apply them to every turn of every run.

MethodWhat it does
tool(tool)Adds one tool. A second tool with the same name replaces the first.
tools(iter)Adds tools whose types are already erased, as an IntoIterator<Item = Arc<dyn Tool>>, for tools built at run time.
system(text)Sets a system instruction sent ahead of the transcript on every turn. It is never written to storage.
model(name)Sets the model every turn asks for. Unset, the endpoint's default is used.
max_tokens(n)Caps the tokens generated on each turn.
temperature(x)Sets the sampling temperature.
top_p(x)Sets nucleus sampling.
reasoning_effort(effort)Sets how much internal reasoning the model spends, a ReasoningEffort from None up to Max.
tool_choice(choice)Constrains which tools the model may call. ToolChoice::Required is sent on the first turn only and downgraded to Auto afterwards, so the model can still answer.
extra_for(dialect, fields)Merges vendor-only JSON fields into the wire body of one dialect. Panics when fields is not a JSON object.
max_turns(n)Sets how many requests one run may make.
token_budget(n)Ends a run once the tokens it has spent reach n.
memory(memory)Decides what the model sees of a long conversation. See Memory.
guard(closure)Consulted before every tool call, and answers Decision::Allow, Deny or Ask.
hook(hook)Adds code that runs around every model call and tool call. Hooks run in the order they were added.
into_tool(name, description)Turns the agent into a tool another agent can call.

ask and conversation are not builders. They run or start something, and are covered below.

The reference pages cover the pieces a method hands off to. Tool calling covers tool, tools, tool_choice and guard, and Requests covers the sampling fields and extra_for. memory and the conversation methods have guides of their own, and a short tutorial that builds one end to end is Building an agent.

A tool-using agent looks like this:

use freyja::{Agent, tool};

#[tool(description = "adds two numbers together", strict = true)]
fn add(a: i64, b: i64) -> i64 {
a + b
}

let agent = Agent::new(client)
.model("gpt-5-mini")
.system("Use the add tool for arithmetic.")
.tool(add)
.max_tokens(500)
.temperature(0.2)
.max_turns(5);

Model and sampling settings live on the builder alongside the tools. The transcript does not. It is held by whatever Storage you pass to conversation, which is why there is no way to put messages into an agent's configuration.

Parallel tool calls​

The loop dispatches the tool calls of one turn concurrently, up to eight at once. How many a turn requests is the model's choice, and a tool holding a socket or a file handle turns that choice into pressure on your process, so the loop staggers them. Nothing is refused: calls past the limit wait for a slot and answer in the order they were requested.

The guard​

.guard(|call, _cx| ...) is consulted before every call, with a ToolCall that carries the call's id, name and raw JSON arguments. Decision::Deny(reason) sends the model denied: {reason} instead of running the tool, which keeps a tool registered for the cases it is meant for while refusing the rest. Decision::Ask pauses the run for a person, see Human approval.

use freyja::{Context, Decision, ToolCall};

let agent = Agent::new(client)
.tool(add)
.guard(|call: &ToolCall, _cx: &Context| match call.name.as_str() {
"add" => Decision::Deny("arithmetic is off limits".to_string()),
_ => Decision::Allow,
})
.max_turns(5);

See Refusing a call.

Agents as tools​

into_tool(name, description) wraps an agent so another agent can call it. The calling model sees the name and description and passes one string, task. Each call runs the inner agent on that task with no history, and only its final answer goes back. The inner run's tokens count against the outer run's usage and budget.

let researcher = Agent::new(client.clone())
.system("You research one question and report what you found.")
.into_tool("research", "Researches a question and returns the findings");

let run = Agent::new(client)
.tool(researcher)
.ask("What changed in the last Rust release?")
.await?;

The outer agent's guard and hooks see only the one call. To vet the inner agent's tools, set a guard on the inner agent. When the inner run ends any way but Answered, or fails, the calling model reads an error: result and its own run carries on. See Multi-agent.

Running an agent​

ask(message) runs one message with no history. conversation(storage) starts a Conversation that keeps the transcript in the backend you pass, and every call to send on it continues the same chat. Both return a Run once the loop stops, as an Ok even when the model refused or ran out of turns, because the call itself succeeded. An Err is a freyja::Error from a request that failed.

ask is conversation(Vec::new()).send(message), so a run through ask follows the same rules as one through a conversation. ask(message).context(&cx) adds a Context, which carries a shared Budget, a Cancel or request state to the run.

The Run​

Run is #[non_exhaustive], so you read its fields and never construct one.

FieldMeaning
answer: StringThe final assistant text, empty when the loop ended without one.
stop: StopReasonWhy the loop stopped.
usage: UsageToken usage summed across every request of the run, as input_tokens, output_tokens and total_tokens.
turns: usizeHow many requests the run made.
agent: Option<String>The team member that gave the final answer, and None outside a team.

The transcript is not on the run. A conversation extends its storage in place, and you read it back through Conversation::storage.

Why a run stopped​

Check run.stop before trusting run.answer. StopReason is #[non_exhaustive], so match it with a trailing _ arm.

VariantCause
AnsweredThe model answered without requesting more tools. This is the normal end.
MaxTurnsThe run made max_turns requests and the model was still working. answer is empty.
RefusedThe model refused, and answer holds the refusal text.
IncompleteThe provider cut the generation short, for example at the token cap. answer holds what arrived.
FailedThe provider reported a failed or unrecognised status. answer is empty.
Stopped(reason)A hook returned Flow::Stop(reason), or a Cancel in the context was tripped. See Stopping a request.
OverBudgetThe run's summed total_tokens reached the token_budget, or a shared Budget or Cost limit was reached. No requested tool runs, and answer is that call's text.
PausedThe guard answered Decision::Ask, and the turn's tool calls wait for Conversation::resume.
HandedOff(name)A team member handed the conversation to name, and the handoff limit of three was passed. The next message goes to that agent.
use freyja::StopReason;

match run.stop {
StopReason::Answered => println!("{}", run.answer),
StopReason::MaxTurns => eprintln!("gave up after {} turns", run.turns),
StopReason::Refused => eprintln!("refused: {}", run.answer),
other => eprintln!("stopped: {other:?}"),
}

token_budget is checked after each model call and again after a turn's tools. Each run starts from zero, so the second message of a conversation has the whole budget again. A call that reports no usage counts as zero. To cap a whole request across helpers and team members, use a shared Budget, see A budget for a whole request.

Stopping a request​

A Cancel stops every run in a request from outside it, such as a stop button, a timeout or a Ctrl+C handler. Put a clone in the Context and send with .context(&cx). Clones share one signal, so the agent, every helper made with into_tool and every team member see it.

use freyja::{Cancel, Context, StopReason};
use std::time::Duration;

let cancel = Cancel::new();
let mut cx = Context::new();
cx.insert(cancel.clone());

let timeout = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(30)).await;
timeout.cancel("took too long");
});

let run = chat.send("Summarise the repo").context(&cx).await?;
if let StopReason::Stopped(reason) = &run.stop {
eprintln!("stopped: {reason}");
}

Once cancel is called, a model call in progress is dropped at once, streaming or not. A tool call that has not started answers stopped: <reason> without running. A tool already running finishes, because cutting it off could leave a half done side effect such as a file written halfway. The run returns Ok with StopReason::Stopped(reason) and the usage counted so far, and a conversation saves what happened before the stop.

A long tool can stop early on its own by reading the handle from its context:

if let Some(cancel) = cx.get::<Cancel>() {
if cancel.is_cancelled() {
return Ok("stopped".into());
}
}

cancelled() is a future that resolves to the reason, for racing against slow work. The first reason given is the one kept, and the signal cannot be reset, so make a new Cancel per request. Dropping the send future also stops everything, but it returns no Run and may leave the conversation's last turn unsaved.

Sharing an agent​

Agent is Clone, and cloning is cheap because the model, tools, guard, hooks and memory sit behind Arcs. Build the agent once, keep it in your application state, and call conversation or ask per request. Each Conversation owns its storage and takes &mut self on send, so two sends on one conversation cannot overlap, while two conversations from one agent run independently.

let agent = Agent::new(client).tool(add).system("Be brief.");

let mut alice = agent.conversation(InMemoryStorage::new());
let mut bob = agent.conversation(InMemoryStorage::new());

A hook or tool that holds state, such as a counter, is shared by every clone and every conversation, so keep it behind an atomic or a lock. State that belongs to one request goes in a Context passed with .context(&cx). See Tool calling.

See also​