Hook
A Hook runs your code around every model call and tool call an agent makes, in every conversation. It sees each request, response and tool call, and can end the run. Use one to log, trace, meter, audit, or stop a run that has spent enough. Tracing, behind the tracing feature, is the built-in hook.
This page is the contract for an implementation. Hooks covers attaching hooks and compares them with the guard.
The trait
#[non_exhaustive]
pub enum Flow {
Continue,
Stop(String),
}
pub trait Hook: Send + Sync {
fn before_model(&self, request: &GenerateRequest, cx: &Context) -> Flow { Flow::Continue }
fn after_model(&self, response: &GenerateResponse, elapsed: Duration, cx: &Context) -> Flow { Flow::Continue }
fn before_tool(&self, call: &ToolCall, cx: &Context) -> Flow { Flow::Continue }
fn after_tool(&self, call: &ToolCall, output: &str, elapsed: Duration, cx: &Context) -> Flow { Flow::Continue }
}
Every method has a default that continues, so a hook implements only the points it cares about. Attach one with Agent::hook. An agent takes any number, and calls them in the order they were added.
Methods are synchronous
The loop calls a hook inline and waits for it, so a method must return quickly and must not block. A hook that writes to a database, a file or a metrics service sends the work to a channel or a task and returns at once. A hook that panics ends the run, as a panicking tool does.
A hook is shared
One hook value belongs to the agent and is called from every run of every conversation, possibly at the same time from different tasks. Mutable state goes behind an atomic or a lock, and state that differs per run or per user is keyed by something in the Context.
The Context is the one the caller passed with .context(&cx) to an ask, a send or a resume, or an empty one. It is how a hook learns who a run is for.
The four points
| Method | Called | Sees |
|---|---|---|
before_model | Before each request to the model | The full request, with system instruction, transcript and tool definitions |
after_model | After each response | The response, with its usage, and how long the call took |
before_tool | Before each tool call the guard allowed | The ToolCall, with id, name and raw JSON arguments |
after_tool | After each tool call, and for each call the guard denied | The call, the text the model will read, and how long it took |
A denied call reaches after_tool with the output denied: <reason> and a zero duration, and never reaches before_tool. An audit that implements only after_tool therefore sees every call the model asked for.
A failed tool call reaches after_tool with the text the model reads, error: and the error message.
Stopping a run
Returning Flow::Stop(reason) ends the run with Ok, and run.stop is StopReason::Stopped(reason). Every hook is still called at that point, so a hook that only records sees where another stopped the run. When several stop, the reason comes from the first in order.
Where the stop comes from decides what is left behind:
| 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, and run.answer is its text. Any 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. |
A hook cannot change what it sees. To refuse one tool call and let the model carry on, use the guard instead, which can deny a call with a reason the model reads.
What a hook can see
A hook sees all conversation content: every message, every tool argument and every result. It never sees an API key, because keys stay inside Client. A hook crate from somewhere else is trusted like any other dependency, since it reads everything the user says.
Text in a request, a response or a tool call comes from the user or the model, and the model controls what it writes. Escape it before a hook writes it into a log format, a terminal or HTML.
Example: a token quota per user
Quota adds up the tokens each user's runs spend, across all their runs, and stops the run that takes a user over the limit. The user comes from the Context, and the totals live behind a lock because every run shares the hook.
use freyja::{Context, Flow, GenerateResponse, Hook};
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Duration;
struct UserId(String);
struct Quota {
limit: u64,
spent: Mutex<HashMap<String, u64>>,
}
impl Hook for Quota {
fn after_model(&self, response: &GenerateResponse, _elapsed: Duration, cx: &Context) -> Flow {
let Some(user) = cx.get::<UserId>() else {
return Flow::Continue;
};
let tokens = response.usage.map_or(0, |usage| usage.total_tokens);
let mut spent = self.spent.lock().expect("quota lock poisoned");
let total = spent.entry(user.0.clone()).or_insert(0);
*total += tokens;
if *total >= self.limit {
return Flow::Stop(format!("{} has used their {} tokens", user.0, self.limit));
}
Flow::Continue
}
}
let agent = Agent::new(client).hook(Quota { limit: 50_000, spent: Mutex::new(HashMap::new()) });
let mut cx = Context::new();
cx.insert(UserId("ada".to_string()));
let run = agent.ask("Summarize this report.").context(&cx).await?;
if let StopReason::Stopped(reason) = &run.stop {
println!("stopped: {reason}");
}
The totals are kept in memory, so they reset when the process restarts. A quota that must persist sends each charge to a task that writes it, and loads the totals at start. To bound one run rather than a user, Agent::token_budget or a Budget in the context does it without a hook.
Example: an audit trail
Audit sends one entry per tool call to a channel, and a task at the other end writes them wherever they go. The hook only builds the entry and sends it, so it never waits on the store.
use freyja::{Context, Flow, Hook, ToolCall};
use std::sync::Mutex;
use std::sync::mpsc::Sender;
use std::time::Duration;
struct AuditEntry {
tool: String,
arguments: String,
output: String,
elapsed: Duration,
}
struct Audit {
entries: Mutex<Sender<AuditEntry>>,
}
impl Hook for Audit {
fn after_tool(&self, call: &ToolCall, output: &str, elapsed: Duration, _cx: &Context) -> Flow {
let entry = AuditEntry {
tool: call.name.clone(),
arguments: call.arguments.clone(),
output: output.to_string(),
elapsed,
};
let _ = self.entries.lock().expect("audit lock poisoned").send(entry);
Flow::Continue
}
}
std::sync::mpsc::Sender is Send but not Sync, so it sits behind a Mutex. A tokio::sync::mpsc::UnboundedSender is Sync and needs no lock. Use an unbounded channel, or try_send on a bounded one, because a hook must not wait for room. A send error means the receiver is gone, and the audit drops the entry rather than failing the run.
Testing it
Each method is a plain function call, so a test calls it with a response or a ToolCall it builds and compares the Flow:
#[test]
fn a_hook_method_is_a_plain_call() {
let quota = Quota { limit: 10, spent: Mutex::new(HashMap::new()) };
let mut cx = Context::new();
cx.insert(UserId("ada".into()));
assert_eq!(quota.after_model(&costing("x", 5), Duration::ZERO, &cx), Flow::Continue);
assert_eq!(
quota.after_model(&costing("x", 5), Duration::ZERO, &cx),
Flow::Stop("ada has used their 10 tokens".into())
);
}
costing builds a response with a chosen usage:
fn costing(text: &str, tokens: u64) -> GenerateResponse {
let mut response =
GenerateResponse::new(ResponseStatus::Completed, vec![OutputContent::Text(text.into())]);
response.usage = Some(Usage::new(tokens, 0));
response
}
Through an agent, a ScriptedModel drives the run, and ToolCall::new builds calls for the direct form. This checks that the audit sees both an allowed call and one the guard denied:
let (sender, receiver) = std::sync::mpsc::channel();
let model = ScriptedModel::new()
.tool_call("add", json!({"a": 1, "b": 2}))
.tool_call("add", json!({"a": 99, "b": 1}))
.text("done");
Agent::new(model)
.tool(add)
.guard(|call, _| if call.arguments.contains("99") { Decision::Deny("no 99".into()) } else { Decision::Allow })
.hook(Audit { entries: Mutex::new(sender) })
.ask("go")
.await?;
let entries: Vec<AuditEntry> = receiver.try_iter().collect();
assert_eq!(entries[0].output, "3");
assert_eq!(entries[1].output, "denied: no 99");
assert_eq!(entries[1].elapsed, Duration::ZERO);
Stability
Hook stays usable as dyn Hook, which is how an agent holds it. A method added to it later comes with a default that continues, so an implementation written today keeps compiling. ToolCall is #[non_exhaustive]: read its fields, and build one with ToolCall::new in tests.
See also
- Hooks for attaching hooks and more examples
- Observability for
Tracing, token budgets and cost - Human approval for the guard, and for resuming a stopped run
- Tool for wrapping one tool rather than watching all of them
- Testing for
ScriptedModel