# Add Amiril to a LiveKit voice agent

Send each LiveKit call to Amiril as a run and check every tool call against your rules in Python. A blocked call never reaches your tool.

This guide connects a LiveKit Agents voice agent to Amiril. Each call reaches Amiril as one run, and the Amiril SDK checks every tool call against your rules before the tool runs. The example is a payments line whose `issue_payment` tool sends money, so one bad call sends real money.

You need LiveKit Agents 1.6 to 1.9 on Python 3.11 or later.

## Install [#install]

```bash
pip install livekit-agents amiril opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
```

With uv, `uv add amiril` works the same way.

## Turn on trace export [#turn-on-trace-export]

Save this file as `tracing.py` beside your agent. It gives LiveKit a tracer provider and sends a call's spans as soon as the call ends. [Send traces from LiveKit Agents](/traces/livekit) explains each line.

```py title="tracing.py"
from livekit.agents.telemetry import set_tracer_provider
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

class FlushWhenJobEnds(SpanProcessor):
    """Sends a job's spans when its root span ends, the last span the job records."""

    def __init__(self, provider: TracerProvider) -> None:
        self.provider = provider

    def on_end(self, span: ReadableSpan) -> None:
        if span.name == "job_entrypoint":
            self.provider.force_flush()

def start_tracing() -> TracerProvider:
    provider = TracerProvider()
    provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    provider.add_span_processor(FlushWhenJobEnds(provider))
    set_tracer_provider(provider)
    return provider
```

## Wrap your function tools [#wrap-your-function-tools]

Put `@sdk_agent.tool` under LiveKit's `@function_tool`. The SDK then checks each call before your function runs, and LiveKit still reads the tool's arguments and docstring.

```py title="agent.py"
import asyncio

import amiril
from amiril import plain
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, JobProcess, cli, function_tool

from tracing import start_tracing

def payment_tools(sdk_agent: plain.Agent) -> list:
    @function_tool
    @sdk_agent.tool
    async def issue_payment(recipient: str, amount: float, invoice_id: str | None = None) -> dict:
        """Send a payment to a recipient, optionally against an invoice."""
        return {"status": "sent", "amount": amount, "recipient": recipient}

    return [issue_payment]

class PaymentsAgent(Agent):
    def __init__(self, sdk_agent: plain.Agent) -> None:
        super().__init__(instructions="You take payments over the phone.", tools=payment_tools(sdk_agent))
```

`payment_tools` takes the SDK agent as an argument because each job process starts its own, in the next step.

## Start Amiril once per process [#start-amiril-once-per-process]

LiveKit runs `setup_fnc` once in each job process, before that process takes a call. Start tracing and the SDK there.

```py title="agent.py"
def setup(proc: JobProcess) -> None:
    start_tracing()
    amiril.init(handle_sigterm=False)
    proc.userdata["sdk_agent"] = plain.Agent("payments_agent")

server = AgentServer(setup_fnc=setup)
```

`handle_sigterm=False` leaves shutdown to LiveKit's worker. The name you give `plain.Agent` is the name your rules use. It must match the name LiveKit gives the agent in traces, which is your `Agent` class in snake case. `PaymentsAgent` traces as `payments_agent`. If you pass `Agent(id="...")`, use that id instead.

The dispatch name in `rtc_session(agent_name=...)` only routes calls to your worker. Amiril never uses it as the agent's name.

## Make each call one run [#make-each-call-one-run]

A run is one piece of work by your agent. For a voice agent, that is one call. Start the session inside the SDK's run and wait there until the session closes.

```py title="agent.py"
@server.rtc_session(agent_name="payments-line")
async def entrypoint(ctx: JobContext) -> None:
    await ctx.connect()
    sdk_agent = ctx.proc.userdata["sdk_agent"]
    session = AgentSession(stt="deepgram/nova-3", llm="openai/gpt-4.1-mini", tts="cartesia/sonic-3")
    closed = asyncio.Event()
    session.on("close", lambda _event: closed.set())

    async with sdk_agent.run(session_id=ctx.room.name) as run:
        session.on("function_tools_executed", lambda _event: run.turn())
        await session.start(agent=PaymentsAgent(sdk_agent), room=ctx.room)
        await closed.wait()
```

The run ends when the `async with` block exits. If the entrypoint returned straight after `session.start()`, the run would end before the caller said a word.

`run.turn()` marks the end of each model reply, once LiveKit has run that reply's tool calls. A rule that needs an earlier call, such as a lookup before a payment, sees the calls of earlier replies only. Without the marks, the whole call counts as one reply.

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

One API key sends both the traces and the SDK's reports, to one [environment](/traces/environments-and-keys). Start in **Development** so test calls stay out of production. On the Free plan, your workspace has only **Production**.

1. Switch to **Development** with the environment menu at the top of the page.
2. Open **Data** and select **Set up a new installation**.
3. Under **API key**, choose **Create a new key**. Name it and select **Create key**.
4. Select **Copy key**. Amiril shows the key only once.
5. Copy the **OpenTelemetry traces endpoint** and select **Copy SDK endpoint**.

Set these where the agent runs:

```bash
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="<OpenTelemetry traces endpoint>"
export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL="http/protobuf"
export OTEL_EXPORTER_OTLP_TRACES_HEADERS="Authorization=Bearer <your API key>"
export AMIRIL_API_KEY="<your API key>"
export AMIRIL_ENDPOINT="<the SDK endpoint>"
export AMIRIL_SERVICE="payments-line"
```

`AMIRIL_SERVICE` names the installation, the service that runs the SDK. Then start the worker with `python agent.py dev` and make a test call.

## Check the first call in Amiril [#check-the-first-call-in-amiril]

Three pages show that the setup worked:

- **Traces** lists the call as a run under `payments_agent`. Each turn shows what the caller said, the reply and the tool calls with their arguments and results. A new run shows a **Scoring** badge until Amiril has ranked it.
- **Installations** lists `payments-line`. Its **Coverage** card shows the agent and the tools the SDK checks.
- **Agents** lists `payments_agent` as an unregistered agent. Select **Register** to give it a display name.

## Block a bad call with a rule [#block-a-bad-call-with-a-rule]

This rule blocks a phone payment over 2000. Write it in the web app, or ask an [AI assistant](/assistants/connect) to write it through Amiril's MCP server.

```amiril
@id("phone-payment-cap")
@sentence("A payment of {amount} is over the 2000 limit for phone payments")
block (
    agent == "payments_agent",
    tool == "issue_payment"
)
when {
    call.args.amount > 2000
};
```

1. Open **Rules**, select **New rule** and give it a **Name**.
2. Select **Edit as text** and paste the rule.
3. Leave the mode on **Shadow** and select **Save draft**. In Shadow the rule records what it would do and every call still runs.
4. [Test the rule on past calls](/rules/test) to see which calls it would have blocked.
5. Select **Publish version 1**, and confirm.
6. Open the mode menu, **Mode in Development**, and choose **Enforce**. Enforce needs the Team plan.

The SDK picks up the change within about a minute. Call again and ask for a payment of 2500. The SDK blocks the call before `issue_payment` runs. The model gets Amiril's answer in place of the tool's result. It says the call was not performed and gives the rule's sentence, so the agent tells the caller it could not make the payment. The rule's page counts the block under **Decided in installations, last 24 hours**.

## Troubleshooting [#troubleshooting]

**Calls show up about ten minutes late.** Call `start_tracing()` from `setup_fnc`, not from the entrypoint. LiveKit opens each call's root span before the entrypoint runs. Without that span, Amiril waits ten minutes of silence before it builds the run.

**One agent shows as two.** The name in `plain.Agent(...)` must match your `Agent`'s id, such as `payments_agent`. If **Agents** also lists your dispatch name, you passed that name to `plain.Agent`. Pass the `Agent`'s id in `setup` instead, then [assign](/agents) the extra agent to `payments_agent`.

**A rule blocks calls that leave out an optional argument.** LiveKit passes every parameter to your function. A parameter the model left out arrives with its default, so `invoice_id: str | None = None` reaches your rules as `null`. A condition that reads a `null` is never true, so a `when` rule lets the call run but an `unless` rule blocks it. To let it through an `unless` rule, test for the value with `present()`:

```amiril
@id("phone-invoice-id")
@sentence("Invoice {invoice_id} is not in the INV-123456 format")
block (
    agent == "payments_agent",
    tool == "issue_payment"
)
unless {
    !present(call.args.invoice_id)
        || matches(call.args.invoice_id, "^INV-[0-9]{6}$")
};
```

**A rule with `matches` never fires.** The pattern must match the whole value. `"^2026-12-03"` does not match `"2026-12-03T10:00"`, but `"^2026-12-03.*"` does.

**Two services show as one installation.** Without `AMIRIL_SERVICE` the SDK takes the name in your `pyproject.toml`, so two workers in one project share it. Set `AMIRIL_SERVICE` for each worker and restart them.

**The rule editor says no agent is seen under the name.** Amiril knows an agent once a run of it has arrived. Make one test call first, then save the rule.

**A rule that counts calls in a run never adds them up.** The entrypoint left the SDK's run too early, so each tool call became a run of its own. Keep `session.start()` inside `async with sdk_agent.run(...)` and wait there for the session's `close` event.

**A rule that needs an earlier call blocks it anyway.** The entrypoint does not mark turns, so the earlier call counts as part of the same reply. Keep the `function_tools_executed` handler that calls `run.turn()`.

## Next steps

- [Take a LiveKit voice agent to production](https://docs.amiril.ai/sdk/livekit-production.md): Answer a LiveKit phone number with your Amiril-checked agent, move it to the Production environment and reach its tools through the Amiril gateway.
- [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.
- [Send traces from LiveKit Agents](https://docs.amiril.ai/traces/livekit.md): Give LiveKit Agents a tracer provider and send each voice session to Amiril over OpenTelemetry as one run, with every turn and the tool calls made in it.
- [Set up environments and API keys](https://docs.amiril.ai/traces/environments-and-keys.md): Create an environment such as Staging and an API key that sends to it, so test runs stay out of production. Then put the key where each service runs.

## More detail

- [Setting up Amiril on a LiveKit Agents voice agent](https://docs.amiril.ai/assistant/livekit.md): LiveKit Agents (Python) with Amiril end to end: trace export, rules on function tools through amiril.plain, naming, turns, phone dispatch, environments, gateway tools, pitfalls.
- [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.
- [Rule settings, modes and publishing](https://docs.amiril.ai/assistant/rules/modes.md): Everything about a rule besides its text: mode, fail mode, if_missing, on_error, ids, versions, publishing, shadow records, backtests, permissions, and the MCP tools and routes for each.
- [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.
