# Add Amiril to a Google ADK agent

Check every tool call of a Google ADK agent against your rules, in Python or TypeScript. Amiril runs as the first plugin and blocks calls that break a rule.

On Google ADK, Amiril is a plugin. It sits first in your app's plugin list, so it sees every tool call before other plugins do. You add it to your `App`, and your agent and its tools stay as they are.

## Install [#install]

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

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

Python needs 3.11 or later and google-adk 2.11 or later. TypeScript needs Node 24 or later and `@google/adk` 2.2.1 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 app [#add-amiril-to-your-app]

Call `init` once, then hand your `App` to `instrument`.

```py tab="Python" title="agent.py"
import amiril
from google.adk.agents import LlmAgent
from google.adk.apps import App

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 = LlmAgent(name="payments", model=model, tools=[issue_payment])
app = App(name="payments", root_agent=agent)
amiril.instrument(app)  # puts Amiril's plugin first in app.plugins
```

```ts tab="TypeScript" title="agent.ts"
import { App, FunctionTool, LlmAgent } from "@google/adk";
import { z } from "zod";
import { init } from "@amiril/sdk/node";
import { instrument } from "@amiril/sdk-adk";

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

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

const agent = new LlmAgent({ name: "payments", model, tools: [issuePayment] });
const app = new App({ name: "payments", rootAgent: agent });
instrument(app); // puts Amiril's plugin first in app.plugins
```

Call `instrument` before you build the `Runner`, because a `Runner` copies the app's plugin list when it is built. `model` is the model your agent already uses. Rules see the agent under its ADK `name`, `payments` here.

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

Run the agent the way you already do. In this snippet a scripted model stands in for Gemini and asks for payments of 500 and 20000 in one turn.

```py tab="Python"
import asyncio
import json

from google.adk.runners import InMemoryRunner
from google.genai import types

async def main() -> None:
    runner = InMemoryRunner(app=app)
    session = await runner.session_service.create_session(app_name=app.name, user_id="user")
    message = types.Content(role="user", parts=[types.Part.from_text(text="Pay Acme Ltd 500 and 20000.")])
    async for event in runner.run_async(user_id="user", session_id=session.id, new_message=message):
        for part in event.content.parts if event.content else []:
            if part.function_response:
                print(part.function_response.id, json.dumps(part.function_response.response))
    await runner.close()

asyncio.run(main())
```

```ts tab="TypeScript"
import { InMemoryRunner } from "@google/adk";

const runner = new InMemoryRunner({ app });
const session = await runner.sessionService.createSession({ appName: app.name, userId: "user" });
const newMessage = { role: "user", parts: [{ text: "Pay Acme Ltd 500 and 20000." }] };
for await (const event of runner.runAsync({ userId: "user", sessionId: session.id, newMessage })) {
  for (const part of event.content?.parts ?? []) {
    if (part.functionResponse) console.log(part.functionResponse.id, JSON.stringify(part.functionResponse.response));
  }
}
```

The payment of 500 runs, and the payment of 20000 is blocked before it reaches the tool. ADK hands the model Amiril's answer as the tool's result. That answer tells the model why the rule blocked the call.

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

## 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. Set it for each service you run. Without it the SDK takes the name in your `pyproject.toml` or `package.json`, and two services in one project become one installation. [SDK configuration](/reference/sdk-config) has 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 Google ADK](https://docs.amiril.ai/traces/google-adk.md): Turn on Google ADK's own OpenTelemetry tracing in Python or TypeScript and send every agent invocation to Amiril, with each tool call's arguments and result.

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