Building an agent
An agent is a model that can act. You give it functions, it decides when to call them, you run them, it uses the results. This page builds one end to end.
Everything here runs.
The shape of it
The model never runs anything. It asks, the agent executes your tool in your process, and the agent reports back. That boundary is the whole security model: nothing happens that your code did not register.
Step 1: declare the tool
#[tool] turns a typed function into a value implementing Tool. The function name becomes the model-visible name, its parameters become a JSON Schema, and its return value is sent back as text when it is a string and as JSON otherwise.
use freyja::{Agent, tool};
#[tool(
description = "adds two numbers together. Use this instead of doing arithmetic yourself",
strict = true
)]
fn add(a: i64, b: i64) -> i64 {
a + b
}
let agent = Agent::new(client).tool(add).max_turns(5);
The description is a prompt, not a comment. It is the only thing the model reads when deciding whether this tool applies. Write it for the model. Say when to call it, not just what it does: "adds two numbers together" is weaker than "adds two numbers together. Use this instead of doing arithmetic yourself".
strict defaults to false. With strict = true, Freyja also rewrites the generated schema into the strict subset accepted by providers that enforce it.
The macro accepts free functions with explicit parameter types and simple identifier parameters, sync or async fn. Methods, generics, and destructuring patterns are rejected at compile time. Parameter types must support Deserialize and JsonSchema. The return type must support Serialize.
Step 2: build the agent and ask
Agent runs the loop for you. It sends the request, runs every tool the model asks for, sends the results back, and repeats until the model answers or max_turns stops it. Agent::new takes any Model, and a Client is one. This example needs a key and network access.
let agent = Agent::new(client)
.model("gpt-4o")
.temperature(0.2)
.tool(add)
.max_turns(5);
let run = agent.ask("What is 20 + 22?").await?;
println!("{}", run.answer);
ask keeps no history. max_turns defaults to ten model calls. Check run.stop before trusting run.answer, because a run can end MaxTurns, Refused or Incomplete and still be an Ok. Agents lists every builder method, every stop reason and how to share one agent. To write the loop by hand, see Calling the model directly.
Step 3: hold a conversation
A conversation is an agent plus a transcript kept in a Storage backend, so each message continues the last.
let mut chat = agent.conversation(InMemoryStorage::new());
let run = chat.send("What is 20 + 22?").await?;
let run = chat.send("Now double it").await?;
println!("{}", run.answer);
InMemoryStorage::new() lives as long as the process and JsonlStorage::open(path)? lives in a file a later process reopens. Conversations covers streaming, what is stored and when, and clearing.
Going further
| To | Read |
|---|---|
| Refuse or log tool calls, or end a run early | Agents and Hooks |
| Hold a person's approval before a tool runs | Human approval |
| Bound what the model sees of a long chat | Memory |
| Hand a chat to another agent, or call one as a tool | Multi-agent |
| See events, spans and token cost | Observability |
| Test with no key | Testing |
Things that bite
ToolChoice::Required inside a loop
Sent on every round it forces a tool call each time, so the model can never produce a final answer. Agent sends it on the first turn only and downgrades it to Auto afterwards. A loop you write by hand must do the same. See Tool calling.
Growing transcripts
Every tool result becomes part of the prompt on the next round, and is billed as input tokens on every round after that. Return what the model needs and nothing more. A conversation grows until the provider rejects it, and a window set with Agent::memory bounds what is sent while the backend keeps every turn. See Memory.
A timeout only bounds a tool that awaits
Freyja has no per-tool budget, deliberately: a timer belongs to a runtime, and Freyja depends on none. Wrap the tool in another tool that applies your runtime's timeout, as the Tool documentation spells out. The wrapper cannot interrupt work that never yields. A tool that blocks the thread runs past its budget and starves its siblings, because concurrent dispatch drives them all on one task. See Tool calling.
Errors and persistence
ask and send return the freyja::Error of the call that failed, and not every failure is worth retrying. Http and an Api with 429 or 5xx are transient, while UnsupportedCapability and InvalidRequest never succeed on retry. See Errors. Message is Serialize and Deserialize, so a Vec<Message> goes to disk or a database and comes back without a conversion layer, and the reasoning parts must be kept because they are part of the transcript. JsonlStorage::open(path) does this for you. See Storage.
Next
| Every builder method on the request | Requests |
| Roles, content parts, transcripts | Messages |
| Tool types in full | Tools |
| Reading responses, statuses, usage | Responses |
| Which errors are worth retrying | Errors |
| Writing the loop by hand | Calling the model directly |