Hooks
A hook is code that runs around every model call and tool call an agent makes, in every conversation. Use one to log, time, audit, count tokens, or end a run that has gone on long enough. A hook watches the loop and can stop it. It cannot change a request, a response or a tool result.
The trait
Hook has four methods, and each one has a default that returns Flow::Continue, so a hook implements only the points it cares about.
| Method | Runs | Arguments |
|---|---|---|
before_model | Before each request to the model | &GenerateRequest, &Context |
after_model | After each response | &GenerateResponse, the Duration the call took, &Context |
before_tool | Before each tool call the guard allowed | &ToolCall, &Context |
after_tool | After each tool call | &ToolCall, the output text the model will read, the Duration, &Context |
ToolCall carries the call's id, name and raw JSON arguments, the same value the guard sees. Context is the per-run context you passed with .context(&cx), so a hook can read a user id or a tenant the same way a tool does.
after_tool also fires for a call the guard refused. Its output is denied: <reason> and its duration is zero, so an audit sees every call the model asked for, not just the ones that ran.
Attach a hook with Agent::hook:
let agent = Agent::new(client).tool(add).hook(Timing);
Methods are synchronous
Hooks run inline in the loop, so a method cannot await and must not block. A hook that has to do I/O, such as writing to a database or posting to a metrics service, sends the work to a channel or spawns a task and returns at once. A hook that panics ends the run the way a panicking tool does.
Ending a run with Flow
Every method returns a Flow. Flow::Continue carries on. Flow::Stop(reason) ends the run with Ok, and run.stop is StopReason::Stopped(reason).
What a stop leaves behind depends on where it came from:
| Stopped from | What happens |
|---|---|
before_model | No request is made. The user's turn is stored with no reply. |
after_model | The response is kept. Tool calls it asked for are left unanswered, and the next send repairs that. |
before_tool or after_tool | The turn's other calls still finish, so every call has a result. |
The calls a stop leaves unanswered are the same ones Conversation::pending lists, and resume settles them. See Human approval.
Several hooks
Hooks run in the order they were added, and every hook is called at each point. A hook that only records still sees the point where another hook stopped the run. When more than one returns Flow::Stop, the first one in order supplies the reason.
A timing hook
This one prints each tool call's name and elapsed time:
use freyja::{Context, Flow, Hook, ToolCall};
use std::time::Duration;
struct Timing;
impl Hook for Timing {
fn after_tool(&self, call: &ToolCall, _output: &str, elapsed: Duration, _cx: &Context) -> Flow {
println!("{} took {elapsed:?}", call.name);
Flow::Continue
}
}
A hook that stops after n model calls
A hook is shared by every run of the agent, so state that must change goes behind an atomic or a lock. This one counts model calls across all runs and stops the run that crosses the limit:
use freyja::{Context, Flow, GenerateRequest, Hook};
use std::sync::atomic::{AtomicUsize, Ordering};
struct CallLimit {
limit: usize,
seen: AtomicUsize,
}
impl Hook for CallLimit {
fn before_model(&self, _request: &GenerateRequest, _cx: &Context) -> Flow {
if self.seen.fetch_add(1, Ordering::Relaxed) >= self.limit {
return Flow::Stop("too many model calls".to_string());
}
Flow::Continue
}
}
let agent = Agent::new(client)
.tool(add)
.hook(Timing)
.hook(CallLimit { limit: 20, seen: AtomicUsize::new(0) });
after_model sees the response, so a hook can read response.usage there and stop the run once the tokens it has summed pass a limit. The count covers every run, because the hook is shared.
Stopping from before_model means the request that would have been the twenty-first is never sent. To bound the tokens a run spends rather than the calls it makes, Agent::token_budget does it without a hook. See Observability.
Hooks and the guard
The two look alike and do different jobs.
| Guard | Hook | |
|---|---|---|
| Sees | Each requested tool call, including unknown names | Model calls and tool calls |
| Can | Allow, deny with a reason the model reads, or ask a person | Continue or stop the run |
| Count | One per agent | Any number |
| Output reaches the model | Yes, a denial is the tool result | No |
Use the guard to decide whether a call may run. Use a hook to observe the loop or to end it. A guard denial shows up in after_tool as denied: <reason>, so a hook can audit what the guard refused. See Refusing a call.
A hook sees all conversation content and never an API key, because keys stay inside Client. The model controls the text it writes, so escape model text and tool arguments before a hook writes them to a log.
See also
- Observability for
Tracing, the ready-made hook - Human approval for the guard's
Askand for resuming a stopped run - Extending Freyja: Hook for the rules every
Hookimplementation follows - Agents for the builder and the loop the hooks run in
- Multi-agent for what a hook sees in each setup
- Testing for checking a hook against a scripted model