Tool call guardrails in plain Python and TypeScript
Tool call guardrails for an agent loop you wrote yourself. Wrap each tool function with the Amiril SDK and every call is checked before it runs, in Python or TypeScript.
Tool call guardrails for an agent loop you wrote yourself. Wrap each tool function with the Amiril SDK and every call is checked before it runs, in Python or TypeScript.
OpenAI's function calling guide suggests "Issue refunds for a lost order" as a tool you might hand a model, and then leaves the refund to you. The model sends back a name and some arguments, and your application runs the code. If you skipped the frameworks, that happens on one line of your own loop, the one that looks the function up by name and calls it. Every call the model asks for passes through that line, so it's the one place tool call guardrails can't be skipped. With the Amiril SDK you wrap each tool function once, and from then on every call is checked against your rules before the function body runs. It works the same in Python and TypeScript, and the rules live in Amiril, so changing one doesn't mean changing your code.
Without a framework, AI agent tool calling is a short loop. Send the conversation and the tool schemas, get back zero or more tool calls, run each one, append the results and ask again. Anthropic's tool use API splits the work the same way: Claude returns the call and your code runs it.
The example here is a support agent with two tools. lookup_order returns an order with its total, and issue_refund takes an order id and an amount. A customer writes in about a $48 order and the model asks to refund 480. Maybe it slipped a zero, maybe the customer told it a story about postage. Your loop passes order A1001 and 480 to issue_refund all the same, and the payments service sends the money.
The oldest tool call guardrails are an if at the top of the function, and for a check that never changes, like a refund that can't be negative, you should keep one. A cap against the order total fits in the function too, in two lines. One refund per order on a ticket is harder, since the function would need its own store of past refunds, keyed by ticket. A new if also blocks for real from the deploy that ships it, and every change to its limit is another deploy.
The SDK has a core package for loops like this one, with no runtime dependencies:
pip install amiril
To block a tool call Python is about to run, you decorate the function with the agent's tool. The agent's name is the one your rules will target. A run is one piece of work, here one reply to a customer's message, and the session id ties a ticket's runs together. Call run.turn() each time the model replies:
import amiril
from amiril import plain
amiril.init()
agent = plain.Agent("support")
@agent.tool
def lookup_order(order_id: str) -> dict:
"""Look up an order by id."""
return orders.get(order_id)
@agent.tool
def issue_refund(order_id: str, amount: float) -> dict:
"""Refund part or all of an order."""
return payments.refund(order_id, amount)
tools = {"lookup_order": lookup_order, "issue_refund": issue_refund}
with agent.run(session_id=ticket_id) as run:
while tool_calls := ask_model(messages): # your own model call
run.turn()
for call in tool_calls:
result = tools[call["name"]](**call["args"])
messages.append(tool_result(call["id"], result))orders, payments, ask_model and tool_result are your own code. The dispatch line didn't change. A call that passes runs the function as before, and a blocked one returns Amiril's answer where the function's result would have been, which your loop hands to the model like any other tool result.
You block a tool call TypeScript code is about to run the same way, by installing @amiril/sdk and wrapping each function with agent.tool. A wrapped tool takes its arguments as one object, since rules read arguments by name:
import { init } from "@amiril/sdk/node";
import { Agent } from "@amiril/sdk/plain";
init();
const agent = new Agent("support");
const lookupOrder = agent.tool(
{ name: "lookup_order", description: "Look up an order by id." },
async ({ order_id }: { order_id: string }) => orders.get(order_id),
);
const issueRefund = agent.tool(
{ name: "issue_refund", description: "Refund part or all of an order." },
async ({ order_id, amount }: { order_id: string; amount: number }) => payments.refund(order_id, amount),
);
const tools: Record<string, (args: any) => Promise<unknown>> = {
lookup_order: lookupOrder,
issue_refund: issueRefund,
};
await agent.run({ sessionId: ticketId }, async (run) => {
let toolCalls = await askModel(messages); // your own model call
while (toolCalls.length > 0) {
run.turn();
for (const call of toolCalls) {
const result = await tools[call.name](call.args);
messages.push(toolResult(call.id, result));
}
toolCalls = await askModel(messages);
}
});Some loops never call a tool function in their own process, for instance one that forwards tool calls to a worker. For those, run.before takes the tool's name, its arguments and the model's call id and returns a check, and when check.proceeds is false you skip the tool and give the model check.result instead. The no-framework SDK guide shows run.before and run.after in both languages.
Rules are a few lines of text, written in Amiril's web app or by an AI assistant through Amiril's MCP server. This one reads the order total from the earlier lookup_order call:
@id("refund-within-order-total")
@sentence("A refund of {amount} is more than order {order_id} cost")
block (
agent == "support",
tool == "issue_refund"
)
unless {
order_id = call.args.order_id;
total = latest(lookup_order{ args.order_id == order_id }).result.total;
call.args.amount <= total
};lookup_order{ ... } matches earlier calls in the run that looked up the same order, latest takes the most recent, and .result.total reads what it returned. An unless rule fires when its condition is false. No lookup means no total, and the refund is blocked.
The rule reads the lookups made in earlier replies. With parallel calls off (parallel_tool_calls: false in OpenAI's API, disable_parallel_tool_use: true in the tool_choice of Anthropic's), the lookup always comes a reply before the refund, and the run.turn() in the loop marks where each reply starts.
When the model asks for 480, the function never runs and the model gets this back:
The call to issue_refund was not performed. Rule refund-within-order-total blocked it: A refund of 480 is more than order A1001 cost (total 48). Do not retry this call with different arguments or achieve the same outcome another way; tell the user it was not performed.
total isn't in the @sentence, so it's added at the end in parentheses. A refund of 48 runs. The second rule stops that 48 going out twice:
@id("one-refund-per-order")
@sentence("This order was already refunded in this conversation")
@per("order_id")
block (
agent == "support",
tool == "issue_refund"
)
when {
issue_refund{}
};@per("order_id") narrows the pattern to earlier refunds of the same order, and it looks across every run in the session. That's what the session_id in the loop is for. If the customer writes again on the same ticket and talks the model into a second refund, the earlier one still counts, because both runs carry the ticket id. A refund counts only if it ran without an error, so the blocked 480 doesn't use up the order's one refund.
We swapped ask_model for a script that asks for a lookup and then refunds of 480, 48 and 48, each in its own reply, and ran the code above with both rules in Python and TypeScript. In both, the first and last refunds were blocked and the middle one ran.
For refunds, the order total was the cap. A discount, or the number of emails sent per conversation, has no lookup to read a limit from, and the right number depends on what this agent normally does.
Amiril reads your agent's traces, sent over OpenTelemetry from any loop. The Anthropic SDK traces its tool runner by itself once OpenTelemetry is set up. It ranks each run by how rare it was for that agent and groups runs that share a problem into an issue. An AI model then reads a sample of the issue's runs and drafts a rule that would have stopped them. Amiril tests the draft on past runs and keeps it only if it catches some of the issue's runs and fires on at most one in a hundred of the agent's other runs. A kept draft shows up as a rule suggestion, and Create rule opens it in the editor.
New tool call guardrails shouldn't block anything on their first day, so a published rule starts in Shadow. It checks every call, records what it would have done and lets the call run. The rule's page counts the calls it would have fired on in the last 24 hours, and Test on past calls replays any version of it, drafts included, over the last day, week or month of the agent's real tool calls. When the list holds only calls you meant to stop, switch the rule to Enforce on its page. In shadow mode for AI agents, a LiveKit salon agent's discount rule makes that switch while phone calls are in progress.
The SDK keeps a copy of your published rules inside the agent's process, so a check makes no network request. A new version reaches running agents within about a minute, with no redeploy. If Amiril can't be reached, the SDK keeps enforcing the last rules it received, and it saves them to disk so a restart doesn't lose them, as how rules reach your agent explains.
You can also try all of this before you have an API key. init takes a rules file, and the SDK runs the rules in it on your laptop with no network requests. If you'd rather not write the loop, the SDK also hooks into agents built on LangGraph, Google ADK and LiveKit.
The setup guide for agents without a framework walks through the rules file, the run and connecting to your workspace, where init reads the key from AMIRIL_API_KEY.