> ## Documentation Index
> Fetch the complete documentation index at: https://docs.unpod.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Run Your Own Brain

> Put your own process at the text boundary of a live call - an AgentRunner serving inbound and outbound phone calls.

The [Quickstart](https://docs.unpod.ai/home/quickstart.md) placed a call with a `Prompt`
brain and deployed nothing. This page is the `Runner` path: your own
long-lived Python process at the text boundary - for DB reads mid-call, your
own framework, or logic a prompt cannot carry.

The deal is unchanged: your
[`AgentRunner`](https://docs.unpod.ai/get-started/core-concepts#agentrunner) receives a
transcribed turn as a string and returns a string. No frames, no codecs, no
SIP - the speech pipeline and the carrier stay on Unpod's side.

## Prerequisites

* Python 3.12+ and `pip install unpod`
* `UNPOD_PLATFORM_TOKEN`, `UNPOD_ORG_HANDLE`, `UNPOD_BASE_URL` and
  `UNPOD_SERVICE_BASE_URL` in a `.env` file - the same four values as the
  [Quickstart](https://docs.unpod.ai/home/quickstart.md#prerequisites). The runner registers
  with the platform token.
* **A number in your account.** Provision one from the dashboard under
  **Dev Platform → Numbers**. No carrier account, no SIP trunk - see
  [Numbers](https://docs.unpod.ai/speech-stack/numbers.md).

> [!NOTE]
>
> Already own a number elsewhere? You can bring it over a
> [trunk](https://docs.unpod.ai/speech-stack/numbers.md#trunks) instead. That is the only path that needs
> carrier credentials.

## Step 1 - Provision the number

Provisioning uses the **Management API** - the REST half of the [SDK](https://github.com/unpod-ai/unpod-python-sdk), reached
through `AsyncClient`. It authenticates with the org-scoped
`UNPOD_PLATFORM_TOKEN` (with `UNPOD_ORG_HANDLE`) - the same token the
runner uses - and sends REST calls to `UNPOD_SERVICE_BASE_URL`
(`https://unpod.ai`, bare host).

Provisioning is the same `agents.voice.create()` call as the
[Quickstart](https://docs.unpod.ai/home/quickstart.md) - the only difference is
`brain=Runner()`: your process answers the turns instead of a platform-run
prompt.

If you need one-off overrides in code, pass `base_url=` to `AsyncClient` or
`AgentRunner`; those arguments win over `.env` for that process only.

Run this once to pick a voice profile, create the agent, and attach a free
number from your account:

```python theme={null}
# setup.py - run once to provision your phone number
import asyncio
from unpod import AsyncClient, Runner

async def setup() -> None:
    async with AsyncClient() as client:
        # 1. Pick a voice profile from the read-only catalog.
        profiles = await client.voice_profiles.list(language="en")
        if not profiles:
            print("No voice profiles found.")
            return
        vp = profiles[0]
        print(f"Using voice profile: {vp.name} ({vp.profile_id})")

        # 2. Create the agent. agent_id MUST match your AgentRunner.
        voice = await client.agents.voice.create(
            "my-runner-agent",            # agent_id - must match AgentRunner's
            brain=Runner(),               # your own worker answers turns
            name="my-runner",
            voice_profile=vp.name,        # name (case-insensitive) or profile_id
            recording=True,
            max_call_duration_s=600,
        )
        print(f"Created agent: {voice.agent_id}")

        # 3. Find a number in your org that is not attached yet.
        numbers = await client.telephony.numbers.list()
        free = [n.number for n in numbers if n.status == "not_assigned"]
        if not free:
            print("No free numbers - provision one under Dev Platform -> Numbers.")
            return

        # 4. Attach it to the agent.
        result = await client.agents.numbers.attach("my-runner-agent", free[0])
        print(f"Attached {result.get('number')} -> agent my-runner-agent "
              f"(status={result.get('status')})")

asyncio.run(setup())
```

What it does:

1. **`voice_profiles.list()`** - pick a voice from the read-only catalog.
2. **`agents.voice.create()`** - create the agent, its brain, and its first voice.
3. **`telephony.numbers.list()`** - find a number with `status="not_assigned"`.
4. **`agents.numbers.attach()`** - route that number to the `agent_id`.

If step 3 finds nothing, provision a number from the dashboard first.

> [accordion] Bringing your own number instead
>
> BYON numbers arrive over a trunk you register once, then sync into your account:
>
> ```python theme={null}
> summary = await client.numbers.sync()   # {"synced": int, "new": int}
> ```
>
> Full setup: [Trunks](https://docs.unpod.ai/speech-stack/numbers.md#trunks).

> [!NOTE]
>
> The agent's `agent_id` (`"my-runner-agent"`) is the same string your
> `AgentRunner` registers under in Step 2. They must match exactly, or
> inbound calls never reach your runner. See
> [IDs You'll Meet](https://docs.unpod.ai/get-started/core-concepts.md#ids-youll-meet).

## Step 2 - Answer an inbound call

One `entrypoint`, one `AgentRunner`. The brain here is SuperDialog's
`LLMAgent`; any adapter works - Anthropic, OpenAI, LangChain, an HTTP
endpoint, or a playbook (see
[Bring your agent](https://docs.unpod.ai/agent-sdk/bring-your-agent.md)) - and nothing about the
call path changes:

```python theme={null}
# agent.py - your process at the text boundary
import os
from unpod import AgentRunner, CallContext
from superdialog import LLMAgent

async def entrypoint(ctx: CallContext) -> None:
    ctx.session.dialog_machine = LLMAgent(
        llm="anthropic/claude-haiku-4-5-20251001",
        system_prompt="You are a helpful voice assistant. Keep answers under 3 sentences.",
    )
    await ctx.session.run()

def build_runner() -> AgentRunner:
    return AgentRunner(
        entrypoint=entrypoint,
        agent_id=os.getenv("AGENT_ID", "my-runner-agent"),
        # base_url, platform_token and org_handle come from UNPOD_BASE_URL /
        # UNPOD_PLATFORM_TOKEN / UNPOD_ORG_HANDLE unless you pass them here.
    )

if __name__ == "__main__":
    build_runner().start()   # blocking
```

Start the runner:

```bash theme={null}
python agent.py
```

The runner connects to the orchestrator and waits. Now call the number you
attached. Unpod recognises the number, resolves the `agent_id` it is attached
to, and dispatches the call to your waiting runner. Your agent answers
and speaks - your own process at the text boundary, live on a phone call.

> [!NOTE]
>
> The runner does not need to restart when you provision the number. Run `setup.py`
> once, then leave the runner up; it serves every inbound call until you stop it.

## If the runner will not connect

Three close codes cover almost every failure:

* **4001** on the control socket - the orchestrator refused the credential.
  Do not retry: a reconnect loop on a bad key is indistinguishable from a
  network outage.
* **4003** on the bridge - the pairing failed: an unknown `call_id`, an
  expired pairing (it expires \~20s after dispatch), or a bad call token.
* **4009** - that call already has a live bridge socket.

## Step 3 - Make an outbound call (optional)

Inbound is one direction. To have your agent place a call, use `calls.create`
with the `agent_id` and the destination number:

```python theme={null}
# call_out.py - dispatch an outbound call
import asyncio
from unpod import AsyncClient

AGENT_ID = "my-runner-agent"   # from setup.py
TO_NUMBER = "+19995550001"

async def make_call() -> None:
    async with AsyncClient() as client:
        call = await client.calls.create(
            agent_id=AGENT_ID,
            to_number=TO_NUMBER,
        )
        print(f"Outbound call {call.call_id} -> {TO_NUMBER} (status: {call.status})")

asyncio.run(make_call())
```

`calls.create` enqueues the call and returns immediately with `status="pending"`.
Unpod dials out, then dispatches the answered call to the same running
`AgentRunner` - your `entrypoint` handles outbound exactly as it handles inbound.

> [!NOTE]
>
> `calls.create` also still accepts `pipe_id=` for older code. `agent_id` wins if
> you pass both, and `to_number` is always required. Outbound dispatch may also
> need `from_number=` depending on your numbers - see
> [Outbound calls](https://docs.unpod.ai/agent-sdk/outbound-calls.md).

## Next steps

> [card] [Production setup](https://docs.unpod.ai/agent-sdk/setup-checklist.md)
>
> The full path: trunks, numbers, recording, and deployment.

> [card] [Outbound calls](https://docs.unpod.ai/agent-sdk/outbound-calls.md)
>
> Campaigns, dynamic instructions, and per-call data.

> [card] [Use your own agent](https://docs.unpod.ai/agent-sdk/bring-your-agent.md)
>
> Plug in LangChain, an HTTP endpoint, or any brain you already have.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.