# Write an Amiril adapter for your framework

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.

Amiril ships adapters for Google ADK and LangGraph. For another framework you write the adapter yourself. The adapter passes the framework's hooks on to Amiril, which then checks each tool call before it runs.

## Check what your framework offers [#check-what-your-framework-offers]

An adapter needs three things from the framework:

- a hook before each tool call that can answer the call itself, in place of the tool
- a hook after each tool call, with the result or the error
- a way to tell one run from another

The first is what lets Amiril block a call. If the framework's hook before a call can only watch, wrap the tools instead, as [Add Amiril to an agent without a framework](/sdk/no-framework) shows.

## Map the hooks [#map-the-hooks]

Each hook the framework calls maps to one call into Amiril.

| When the framework | The adapter calls |
|---|---|
| builds an agent | `Agent(name)`, then `declare` for each tool |
| starts a run | `agent.run(run_id=...)` in Python, `agent.start({ runId })` in TypeScript |
| gets a reply from the model | `run.turn(turn_id)` |
| is about to run a tool | `run.before(tool, args, call_id=...)` |
| has run a tool, or the tool failed | `run.after(check, result)` or `run.after(check, error=error)` |
| ends the run | `run.end()` |

`declare` adds a tool to the agent's list, with its description, so Amiril knows the tool before its first call. `run.before` returns a check. `check.proceeds` says whether the tool may run, and you pass the same check to `run.after` once the tool has run. Except for starting a run, the table shows Python. TypeScript passes `{ callId }`, `{ result }` and `{ error }` as objects.

## Install [#install]

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

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

An adapter needs only this core package. Python needs 3.11 or later and TypeScript needs Node 24 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"
    }
  ]
}
```

## Write the adapter [#write-the-adapter]

In this example, `TinyFramework` stands in for your framework. It runs a model's tool calls and calls a hook at each step, such as `before_tool` before each tool runs. `AmirilHooks` is the whole adapter, and its methods map to the rows of the table above.

```py tab="Python" title="adapter.py"
class AmirilHooks:
    """Amiril for TinyFramework: each hook hands its step to `amiril.plain`."""

    def __init__(self, agent_name: str, tools: dict[str, Callable[..., Any]]) -> None:
        self.agent = plain.Agent(agent_name)
        for name, fn in tools.items():
            self.agent.declare(name, description=fn.__doc__)
        self.runs: dict[str, plain.Run] = {}
        self.checks: dict[str, plain.Check] = {}

    def on_run_start(self, run_id: str) -> None:
        self.runs[run_id] = self.agent.run(run_id=run_id)

    def on_model_turn(self, run_id: str, turn_id: str) -> None:
        self.runs[run_id].turn(turn_id)

    def before_tool(self, run_id: str, call: ToolCall) -> Any:
        check = self.runs[run_id].before(call.name, call.args, call_id=call.id)
        if not check.proceeds:
            return check.result  # the framework hands this to the model, and the tool does not run
        self.checks[call.id] = check
        return None

    def after_tool(self, run_id: str, call: ToolCall, result: Any) -> None:
        self.runs[run_id].after(self.checks.pop(call.id), result)

    def on_tool_error(self, run_id: str, call: ToolCall, error: Exception) -> None:
        self.runs[run_id].after(self.checks.pop(call.id), error=error)

    def on_run_end(self, run_id: str) -> None:
        self.runs.pop(run_id).end()
```

```ts tab="TypeScript" title="adapter.ts"
/** Amiril for TinyFramework: each hook hands its step to `@amiril/sdk/plain`. */
class AmirilHooks implements Hooks {
  private readonly agent: Agent;
  private readonly runs = new Map<string, Run>();
  private readonly checks = new Map<string, Check>();

  constructor(agentName: string, tools: Record<string, Tool>) {
    this.agent = new Agent(agentName);
    for (const [name, tool] of Object.entries(tools)) this.agent.declare({ name, description: tool.description });
  }

  onRunStart(runId: string): void {
    this.runs.set(runId, this.agent.start({ runId }));
  }

  onModelTurn(runId: string, turnId: string): void {
    this.runs.get(runId)?.turn(turnId);
  }

  async beforeTool(runId: string, call: ToolCall): Promise<{ answer: unknown } | null> {
    const run = this.runs.get(runId);
    if (run === undefined) return null;
    const check = await run.before(call.name, call.args, { callId: call.id });
    if (!check.proceeds) return { answer: check.result }; // the framework hands this to the model, and the tool does not run
    this.checks.set(call.id, check);
    return null;
  }

  afterTool(runId: string, call: ToolCall, result: unknown): void {
    this.settle(runId, call, { result });
  }

  onToolError(runId: string, call: ToolCall, error: unknown): void {
    this.settle(runId, call, { error });
  }

  onRunEnd(runId: string): void {
    this.runs.get(runId)?.end();
    this.runs.delete(runId);
  }

  private settle(runId: string, call: ToolCall, ended: { result?: unknown; error?: unknown }): void {
    const check = this.checks.get(call.id);
    this.checks.delete(call.id);
    if (check !== undefined) this.runs.get(runId)?.after(check, ended);
  }
}
```

<Accordions>
<Accordion title="The stand-in framework">
```py tab="Python" title="adapter.py"
class TinyFramework:
    """Runs a scripted model's tool calls and tells its hooks about each step.
    `before_tool` may answer a call itself, and then the tool does not run."""

    def __init__(self, tools: dict[str, Callable[..., Any]], hooks: Any) -> None:
        self.tools, self.hooks = tools, hooks

    def run(self, run_id: str, turns: list[list[ToolCall]]) -> list[tuple[str, Any]]:
        results: list[tuple[str, Any]] = []
        self.hooks.on_run_start(run_id)
        for index, calls in enumerate(turns):
            self.hooks.on_model_turn(run_id, f"{run_id}-turn-{index}")
            for call in calls:
                answer = self.hooks.before_tool(run_id, call)
                if answer is None:
                    try:
                        answer = self.tools[call.name](**call.args)
                    except Exception as error:
                        self.hooks.on_tool_error(run_id, call, error)
                        raise
                    self.hooks.after_tool(run_id, call, answer)
                results.append((call.id, answer))
        self.hooks.on_run_end(run_id)
        return results
```

```ts tab="TypeScript" title="adapter.ts"
interface Hooks {
  onRunStart(runId: string): void;
  onModelTurn(runId: string, turnId: string): void;
  /** May answer a call itself, and then the tool does not run. */
  beforeTool(runId: string, call: ToolCall): Promise<{ answer: unknown } | null>;
  afterTool(runId: string, call: ToolCall, result: unknown): void;
  onToolError(runId: string, call: ToolCall, error: unknown): void;
  onRunEnd(runId: string): void;
}

/** Runs a scripted model's tool calls and tells its hooks about each step. */
class TinyFramework {
  private readonly tools: Record<string, Tool>;
  private readonly hooks: Hooks;

  constructor(tools: Record<string, Tool>, hooks: Hooks) {
    this.tools = tools;
    this.hooks = hooks;
  }

  async run(runId: string, turns: ToolCall[][]): Promise<Array<[string, unknown]>> {
    const results: Array<[string, unknown]> = [];
    this.hooks.onRunStart(runId);
    for (const [index, calls] of turns.entries()) {
      this.hooks.onModelTurn(runId, `${runId}-turn-${index}`);
      for (const call of calls) {
        const answered = await this.hooks.beforeTool(runId, call);
        if (answered !== null) {
          results.push([call.id, answered.answer]);
          continue;
        }
        let result: unknown;
        try {
          result = await this.tools[call.name].run(call.args);
        } catch (error) {
          this.hooks.onToolError(runId, call, error);
          throw error;
        }
        this.hooks.afterTool(runId, call, result);
        results.push([call.id, result]);
      }
    }
    this.hooks.onRunEnd(runId);
    return results;
  }
}
```
</Accordion>
</Accordions>

When a call does not proceed, hand the model `check.result` unchanged. When it does, call `after` exactly once, with the result or the error.

Pass the framework's own ids. The run id goes to `agent.run` or `agent.start`, and the model's tool call id goes to `run.before` as the call id. That way, a call the framework runs again after a resume gets the same decision as the first time.

## Add the adapter to your framework [#add-the-adapter-to-your-framework]

Call `init`, then add the adapter the way your framework adds any hook. Add it ahead of every other hook. A hook that runs first could answer a call, or change its arguments, before Amiril sees it.

```py tab="Python"
amiril.init(rules_file="rules.json")

tools = {"issue_payment": issue_payment}
framework = TinyFramework(tools, hooks=AmirilHooks("payments", tools))
```

```ts tab="TypeScript"
init({ rulesFile: "rules.json" });

const framework = new TinyFramework(tools, new AmirilHooks("payments", tools));
```

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

The framework's scripted model asks 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. For the second, the framework hands the model Amiril's answer.

```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."}
```

```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."}
```

To take your rules from Amiril instead of the file, follow [connect to your workspace](/sdk/no-framework#connect-to-your-workspace). The adapter needs no change.

## Next steps

- [Add Amiril to an agent without a framework](https://docs.amiril.ai/sdk/no-framework.md): 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.
- [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.
