# Add Amiril to a LangGraph agent

Check every tool call of a LangGraph agent built with create_agent against your rules, in Python or TypeScript, and block the calls that break one.

On LangGraph, Amiril is middleware for `create_agent`, the function in the `langchain` package that builds a LangGraph agent. It goes first in the agent's middleware list and checks each tool call before the tool runs. A call that breaks a rule gets an error message in place of the tool's result. For a Python `StateGraph` you build by hand, use [Amiril's ToolNode](#use-amirils-toolnode-in-a-stategraph) instead.

## Install [#install]

```bash tab="Python"
pip install "amiril[langgraph]"
```

```bash tab="TypeScript"
npm install @amiril/sdk @amiril/sdk-langgraph
```

Python needs 3.11 or later, langgraph 1.2 or later and langchain 1.3 or later. TypeScript needs Node 24 or later and `langchain` 1.4.5 or later.

## Save a rules file [#save-a-rules-file]

Save this file as `rules.json` beside your agent. Its one rule blocks an `issue_payment` call for more than 10000. With the rule in a local file, you can try the SDK before you have an API key. The file is JSON because that is the form the SDK runs. Once you connect, you write rules as [rule text](/rules/language) in Amiril and the SDK fetches them in this form.

```json title="rules.json"
{
  "schema": "amiril.rules/1",
  "ruleset_version": "example-1",
  "rules": [
    {
      "id": "payment-cap",
      "version": "1",
      "mode": "enforce",
      "description": "A payment amount must be above 0 and at most 10000",
      "target": { "tools": ["issue_payment"] },
      "assert": { "and": [{ ">": [{ "arg": "amount" }, 0] }, { "<=": [{ "arg": "amount" }, 10000] }] },
      "action": "block"
    }
  ]
}
```

## Add Amiril to your agent [#add-amiril-to-your-agent]

Call `init` once, then put Amiril's middleware first in the agent's list. The first middleware is the outermost, so nothing else sees a call before Amiril does. Then pass the agent to `instrument`, which checks that the middleware is there and first.

```py tab="Python" title="agent.py"
import amiril
import amiril.langgraph
from langchain.agents import create_agent
from langchain_core.tools import tool

@tool
def issue_payment(payee: str, amount: float) -> dict:
    """Send a payment to a payee."""
    return {"payee": payee, "amount": amount, "status": "sent"}

amiril.init(rules_file="rules.json")

agent = create_agent(model, [issue_payment], middleware=[amiril.langgraph.middleware()], name="payments")
amiril.instrument(agent)  # checks Amiril's middleware is in place and first
```

```ts tab="TypeScript" title="agent.ts"
import { createAgent, tool } from "langchain";
import { z } from "zod";
import { init } from "@amiril/sdk/node";
import { amirilMiddleware, instrument } from "@amiril/sdk-langgraph";

const issuePayment = tool(async ({ payee, amount }) => ({ payee, amount, status: "sent" }), {
  name: "issue_payment",
  description: "Send a payment to a payee.",
  schema: z.object({ payee: z.string(), amount: z.number() }),
});

init({ rulesFile: "rules.json" });

const agent = createAgent({ model, tools: [issuePayment], middleware: [amirilMiddleware()], name: "payments" });
instrument(agent); // checks Amiril's middleware is in place and first
```

LangGraph cannot add a hook to an agent once it is built, so the middleware goes in when you build it. `model` is the chat model your agent already uses. Rules see the agent under the `name` you give it, `payments` here.

## Run the agent [#run-the-agent]

Run the agent the way you already do. LangChain's fake chat model stands in for yours here, and it asks for payments of 500 and 20000 in one turn.

```py tab="Python"
from langchain_core.messages import ToolMessage

result = agent.invoke({"messages": [("user", "Pay Acme Ltd 500 and 20000.")]})
for message in result["messages"]:
    if isinstance(message, ToolMessage):
        print(message.tool_call_id, message.status, message.content)
```

```ts tab="TypeScript"
import { ToolMessage } from "@langchain/core/messages";

const result = await agent.invoke({ messages: [{ role: "user", content: "Pay Acme Ltd 500 and 20000." }] });
for (const message of result.messages) {
  if (ToolMessage.isInstance(message)) console.log(message.tool_call_id, message.status, message.content);
}
```

The payment of 500 runs, and the payment of 20000 is blocked before it reaches the tool. The model gets an error `ToolMessage` in its place, and that message tells the model why the rule blocked the call.

```text tab="Python"
c1 success {"payee": "Acme Ltd", "amount": 500.0, "status": "sent"}
c2 error The call to issue_payment was not performed. Rule payment-cap blocked it: A payment amount must be above 0 and at most 10000 (amount 20000). Do not retry this call with different arguments or achieve the same outcome another way; tell the user it was not performed.
```

```text tab="TypeScript"
c1 success {"payee":"Acme Ltd","amount":500,"status":"sent"}
c2 error The call to issue_payment was not performed. Rule payment-cap blocked it: A payment amount must be above 0 and at most 10000 (amount 20000). Do not retry this call with different arguments or achieve the same outcome another way; tell the user it was not performed.
```

## Use Amiril's ToolNode in a StateGraph [#use-amirils-toolnode-in-a-stategraph]

In Python, a `StateGraph` you build by hand takes Amiril's `ToolNode` in place of LangGraph's. It takes the same arguments, and `instrument` checks every `ToolNode` in the graph and its subgraphs. The TypeScript adapter supports `createAgent` only.

```py tab="Python" title="graph.py"
builder = StateGraph(State)
builder.add_node("model", call_model)
builder.add_node("tools", amiril.langgraph.ToolNode([issue_payment], agent="payments"))
builder.add_edge(START, "model")
builder.add_conditional_edges("model", tools_condition)
builder.add_edge("tools", "model")
graph = builder.compile()
amiril.instrument(graph)  # checks every ToolNode carries Amiril's hook
```

## Connect to your workspace [#connect-to-your-workspace]

So far the SDK runs the rules in your file. Connect it to your workspace and it runs the rules you publish in Amiril instead.

1. Open the **Data** page and select **Set up a new installation**.
2. Under **API key**, choose **Create a new key**. Name it and select **Create key**.
3. Select **Copy key**. Amiril shows the key only once.
4. Select **Copy SDK endpoint**.

Where your agent runs, set the key, the endpoint and a name for this service:

```bash
export AMIRIL_API_KEY="<your API key>"
export AMIRIL_ENDPOINT="<the SDK endpoint>"
export AMIRIL_SERVICE="<a name for this service>"
```

Remove `rules_file` from `init`, or `rulesFile` in TypeScript, and restart the agent. The SDK now enforces the rules published to the key's [environment](/traces/environments-and-keys). A rule blocks calls only once it is published and in Enforce, as [Write your first rule](/rules/first-rule) shows.

When the agent starts, your service appears on the **Installations** page under the name in `AMIRIL_SERVICE`. Its **Coverage** card lists the agent and the tools Amiril checks. Otherwise the SDK reads the name from `pyproject.toml` or `package.json`, and every service in that project is listed as one installation. See [SDK configuration](/reference/sdk-config) for the order it reads names in.

## Next steps

- [Write your first rule](https://docs.amiril.ai/rules/first-rule.md): Start from a rule Amiril drafted for an issue, or from a blank rule. Save it, publish it in Shadow, then switch it to Enforce in one environment.
- [How rules reach your agent](https://docs.amiril.ai/sdk/rule-sync.md): The SDK keeps your published rules in the agent's process and checks each tool call there. It keeps checking when Amiril is unreachable or the agent restarts.
- [SDK configuration](https://docs.amiril.ai/reference/sdk-config.md): Every option of the Amiril SDK's init and every environment variable it reads, in Python and TypeScript, with its type, its default and what it does.
- [Send traces from LangGraph](https://docs.amiril.ai/traces/langgraph.md): Send each run of a LangGraph agent to Amiril over OpenTelemetry with OpenInference's LangChain instrumentation, in Python or TypeScript.

## More detail

- [SDK behaviour in detail](https://docs.amiril.ai/assistant/sdk.md): The Amiril SDK past the setup guides: per-framework gaps, run ids and sessions, hook order and its errors, restarts, shutdown, offline behaviour, model messages, tested versions.
- [Troubleshooting](https://docs.amiril.ai/assistant/troubleshooting.md): Symptom, cause, how to confirm and fix for common Amiril problems: missing runs, plan limits, wrong agent or environment, rules that never fire or never block, SDK, key, import and MCP failures.
- [Limits and defaults](https://docs.amiril.ai/assistant/limits.md): Every limit and default a customer can hit in Amiril, with its number: plan amounts, ingest sizes and rates, imports, rules, backtests, API and MCP rates, page sizes, retention, name lengths.
