# Add Amiril to an agent without a framework

Check each tool call of an agent loop you wrote yourself against your rules, in Python or TypeScript, with the core SDK package and nothing else.

If your agent is a loop you wrote yourself, you add the core SDK to it directly. You name the agent, wrap its tools and mark where each run starts and ends. From then on, Amiril checks every call before the tool runs.

## Install [#install]

```bash tab="Python"
pip install amiril
```

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

Python needs 3.11 or later and TypeScript needs Node 24 or later. Neither package has a runtime dependency.

## 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"
    }
  ]
}
```

## Name the agent and wrap its tools [#name-the-agent-and-wrap-its-tools]

`Agent` gives the agent the name your rules target. Wrapping a tool function means every call of it is checked first.

```py tab="Python" title="agent.py"
import amiril
from amiril import plain

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

agent = plain.Agent("payments")

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

```ts tab="TypeScript" title="agent.ts"
import { init } from "@amiril/sdk/node";
import { Agent } from "@amiril/sdk/plain";

interface Payment {
  payee: string;
  amount: number;
}

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

const agent = new Agent("payments");

const issuePayment = agent.tool(
  { name: "issue_payment", description: "Send a payment to a payee." },
  async ({ payee, amount }: Payment) => ({ payee, amount, status: "sent" }),
);
```

In TypeScript, a wrapped tool takes its arguments as one object, because rules read arguments by name.

## Mark the run [#mark-the-run]

Wrap each piece of work in a run, such as the handling of one message. Rules that count calls, or that need one call before another, look within a run. You can pass a session id when you start the run, `session_id` in Python and `sessionId` in TypeScript. It ties together the runs of one conversation.

Inside the run, call `run.turn()` each time the model replies. A rule sees the calls of earlier replies, but not the other calls in the reply it is checking. So if one reply asks for `verify_payee` and `issue_payment`, a rule that needs `verify_payee` first blocks the payment. Without `run.turn()`, the whole run counts as one reply, and that rule blocks every payment.

```py tab="Python"
with agent.run(session_id="conversation-1") as run:
    for tool_calls in model_turns():  # your own model call goes here
        run.turn()
        for call in tool_calls:
            result = issue_payment(**call["args"])
            print(call["id"], json.dumps(result))
```

```ts tab="TypeScript"
await agent.run({ sessionId: "conversation-1" }, async (run) => {
  for (const toolCalls of modelTurns()) { // your own model call goes here
    run.turn();
    for (const call of toolCalls) {
      const result = await issuePayment(call.args);
      console.log(call.id, JSON.stringify(result));
    }
  }
});
```

A blocked call returns Amiril's answer in place of the tool's result. Hand it to the model as the tool result, the same as any other.

## Check a call by hand [#check-a-call-by-hand]

Some loops never call a tool function in your code, such as one that hands tool calls to another process. Check each of those calls yourself. `run.before` takes the tool's name, its arguments and the model's tool call id, and returns a check. When `check.proceeds` is true, run the tool and pass its result to `run.after`. When it is false, skip the tool and hand the model `check.result` in its place.

```py tab="Python"
with agent.run(session_id="conversation-2") as run:
    for tool_calls in model_turns():
        run.turn()
        for call in tool_calls:
            check = run.before(call["name"], call["args"], call_id=call["id"])
            if check.proceeds:
                result = tools[call["name"]](**call["args"])  # however your loop runs a tool
                run.after(check, result)
            else:
                result = check.result  # hand this to the model in the tool's place
            print(call["id"], "ran" if check.proceeds else "blocked")
```

```ts tab="TypeScript"
await agent.run({ sessionId: "conversation-2" }, async (run) => {
  for (const toolCalls of modelTurns()) {
    run.turn();
    for (const call of toolCalls) {
      const check = await run.before(call.name, call.args, { callId: call.id });
      let result: unknown;
      if (check.proceeds) {
        result = await tools[call.name](call.args); // however your loop runs a tool
        run.after(check, { result });
      } else {
        result = check.result; // hand this to the model in the tool's place
      }
      console.log(call.id, check.proceeds ? "ran" : "blocked");
    }
  }
});
```

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

In this example, `model_turns()` in Python and `modelTurns()` in TypeScript stand in for your model. They ask for payments of 500 and 20000 in one turn. The payment of 500 runs, and the payment of 20000 is blocked before it reaches the tool. The same two calls are then checked by hand.

```text tab="Python"
c1 {"payee": "Acme Ltd", "amount": 500, "status": "sent"}
c2 {"status": "blocked", "blocked_by": "amiril", "message": "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."}
c1 ran
c2 blocked
```

```text tab="TypeScript"
c1 {"payee":"Acme Ltd","amount":500,"status":"sent"}
c2 {"status":"blocked","blocked_by":"amiril","message":"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."}
c1 ran
c2 blocked
```

## 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. Without `AMIRIL_SERVICE`, the SDK uses your project's name, so services that share a project show as one installation. [SDK configuration](/reference/sdk-config) lists every place it reads the name from.

## 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.
- [Write an Amiril adapter for your framework](https://docs.amiril.ai/sdk/write-an-adapter.md): Connect Amiril to an agent framework it has no adapter for. A small class hands each run, model turn and tool call to Amiril from the framework's own hooks.
- [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.

## 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.
