Skip to main content

Hooks

Hooks are attributed functions on handler objects, the way #[test] and #[main] work. They see and change every model call and every tool call, which is how a pricing or policy layer (Ex. Limitr) caps tokens, routes models, holds and settles budgets, and allows or refuses tools, without the code making calls knowing about it.

HookRunsCan
#[ai-before] fn (ctx: obj) -> unknownbefore each model callchange ctx.request (model, max_tokens, tools, ...); return anything but null to refuse
#[ai-after] fn (ctx: obj)after a call finishedread ctx.response.usage; change the response
#[ai-error] fn (ctx: obj)when a call fails, is refused, or is closedrelease what a before hook held
#[ai-event] fn (ctx: obj, event: map)for each streamed eventforward events to a UI; set ctx.run.cancel
#[ai-approve] fn (ctx: obj, call: obj) -> unknownbefore each tool callchange call.args; return anything but null to refuse
#[ai-result] fn (ctx: obj, call: obj)after each tool callread or change call.content

Pass handler objects (one, or a list) to chat, stream, agent, or count. Hooks run in the order of the objects, then in the order they're written, and any of them can be async.

The promises​

  • Before, then after or error. Every call that started its before hooks ends with the after hooks (it finished) or the error hooks (it failed, was refused, was closed early, or a hook threw). A hold made before a call can always be settled or released.
  • Each try is a call. A retry or a fallback model runs the before hooks again, so it's checked and priced like any call.
  • The caller's request isn't changed. Hooks change the call's copy (ctx.request).
  • No tools behind a hook's back. The model can call only what ctx.request.tools offered after the before hooks.

A meter​

One handler object can serve every call. Each call's account rides in the request's meta, which is never sent to the provider. This one refuses a call with nothing left, caps max_tokens at what's left, holds that much, settles what was used, and releases the hold when a call fails:

meter: {
#[ai-before]
fn reserve(ctx: obj) -> unknown {
const account = ctx.request.meta.get('account');
const left = account.get('left') - account.get('held');
if (left <= 0) return 'out of tokens until the 1st';
if (ctx.request.max_tokens == null || ctx.request.max_tokens > left) ctx.request.max_tokens = left;
account.insert('held', account.get('held') + ctx.request.max_tokens);
ctx.data.insert('hold', ctx.request.max_tokens);
null
}

#[ai-after]
fn settle(ctx: obj) {
const account = ctx.request.meta.get('account');
const usage = ctx.response.usage;
const used = usage.get('input') + usage.get('cache_read') + usage.get('cache_write') + usage.get('output');
account.insert('held', account.get('held') - ctx.data.get('hold'));
account.insert('left', account.get('left') - used);
}

#[ai-error]
fn release(ctx: obj) {
const hold = ctx.data.get('hold');
if (hold != null) {
const account = ctx.request.meta.get('account');
account.insert('held', account.get('held') - hold);
}
}
}
const account = {'left': 50000, 'held': 0};
using request = new {
model: 'anthropic/claude-sonnet-5-5',
messages: [new { role: 'user', content: question }],
meta: {'account': account},
};
const run = await self.ai.agent(request, [self.meter, self.desk]);

A refused call fails with the kind 'denied' (an agent stops with 'denied', and run.error.reason is the refusal). usage keeps cached input apart from the rest (input is only what wasn't cached), so each kind can have its own price. await self.ai.count(request) gives a request's input tokens before a call: the provider's count when it has one (Anthropic), or an estimate.

Routing​

A before hook that changes ctx.request.model sends the call elsewhere, Ex. a cheaper model for a customer on a free plan:

#[ai-before]
fn route(ctx: obj) -> unknown {
if (ctx.request.meta.get('plan') == 'free') ctx.request.model = 'groq/llama-4';
null
}

Allowing tools​

A before hook can take tools off a call's offer, and an approve hook decides each call. A refusal is the model's error result, so it can explain or try something else:

policy: {
#[ai-before]
fn offer(ctx: obj) -> unknown {
ctx.request.tools = ctx.request.tools.filter((tool: map): bool => tool.get('name') != 'admin_tool');
null
}

#[ai-approve]
fn approve(ctx: obj, call: obj) -> unknown {
if (call.name == 'refund' && call.args.get('amount') > 100) return 'refunds over $100 need a person';
null
}
}

Events to a UI​

With an #[ai-event] hook, calls stream, and the hook sees each event as it arrives. Send them on to the app through a library function the host added (see Hosts):

ui: {
#[ai-event]
fn forward(ctx: obj, event: map) {
App::emit(event);
if (ctx.run != null && App::stopped()) ctx.run.cancel = true; // an agent stops after this event
}
}

Events are maps with a type: start, text, thinking, tool_call, usage, stop, and more, plus tool_start, tool_end, turn, and finish in an agent (the README's Streaming section lists them all).

Many calls, one collection​

Hooks and tools are collected from the handler objects once per call (once per run for an agent). Code making many calls can collect them once, and pass the map instead:

const hooks = <Ai>.hooks([self.meter, self.policy, self.ui]);
for (const question in questions) await self.ai.chat(self.request_for(question), hooks);