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

# Direct calls or campaigns: which to use

> When to ring one number with POST /v2/calls, when to feed an always-on campaign instead, and how to move a direct-call integration onto one.

You can place an outbound call in two ways. [`POST /v2/calls`](https://docs.miraiminds.co/v2/calls#create-a-call)
rings one number now. A [campaign](https://docs.miraiminds.co/v2/campaigns.md) keeps a list of people and
dials it for you, with calling hours, pacing and retries. With
[`always_on: true`](https://docs.miraiminds.co/v2/campaigns#always-on-campaigns) the campaign stays open,
and your system adds one person at a time as events happen.

Both run the same agents, cost the same per minute and send the same `call.*`
[webhooks](https://docs.miraiminds.co/v2/webhooks.md). What changes is who schedules the calls. With direct
calls your code does it, and with a campaign we do.

## Which one to use

| Use `POST /v2/calls` for | Use an always-on campaign for |
| :- | :- |
| A handful of calls, such as tests and demos | Any steady flow: abandoned carts, deliveries, payment and appointment reminders, new leads |
| A person waiting for the call, such as a **Call me now** button | More than about 200 calls a day |
| Real-time triggers at low volume, where the call is no use a few minutes later | Bursts: a nightly job, a sale, a list your team uploads |
| [Browser calls](https://docs.miraiminds.co/v2/web-calls.md) and [Realtime sessions](https://docs.miraiminds.co/v2/realtime.md) | Calls that should wait for calling hours, or be tried again later |

Adding a person to an always-on campaign is one request, the same as placing a
direct call. If you aren't sure which to use, start with the campaign.

## How they compare

| | `POST /v2/calls` | Always-on campaign |
| :- | :- | :- |
| Queue and pacing | Rings as soon as it can. On a Mirai number, a call waits in the [call queue](https://docs.miraiminds.co/v2/calls.md#pacing-and-the-call-queue) for a free line for up to 30 minutes, then ends `queue-timeout`. On your own carrier account or SIP trunk, pacing is up to you. With 500 calls waiting, `429 rate_limited`. | Each contact waits in the campaign's list, for days if needed, and is dialled at the campaign's pace on every kind of number. |
| Retries | None. An unanswered call ends `no_answer`, and calling again is up to you. | [`retry_count`](https://docs.miraiminds.co/v2/campaigns#retries) (up to 5) tries again after `re_attempt_period_secs`, only when the call didn't reach a person. `retry_slots` keeps retries to the hours you choose. |
| Calling hours | A call to an Indian (+91) number outside 09:00 to 21:00 IST is refused with `422 outside_calling_hours`. Narrower hours are up to your scheduler. | [`slots`](https://docs.miraiminds.co/v2/campaigns#calling-window) in the campaign's timezone. Outside them the campaign sleeps and calls again when they open. Each contact can also have a `not_before` and an `expires_at`. |
| Concurrency | Every call shares your workspace's [concurrency](https://docs.miraiminds.co/v2/limits.md#concurrency). Calls above it wait in `queued`. | [`max_concurrent`](https://docs.miraiminds.co/v2/campaigns#budget-and-pacing) (1 to 50) caps the campaign's live calls, inside your workspace's concurrency. |
| Number rotation | A [phone pool](https://docs.miraiminds.co/v2/phone-numbers.md#why-a-pool) can pick the number for each call. When every number in it is at its pace, the call is refused with `409 pool_busy` and you send it again later. | The pool spreads the campaign's calls over its numbers, each at its own pace, and the campaign waits when they are all busy. |
| Bad input | A `4xx`, and nothing is stored. If your code ignores the answer, the call is lost. | Bad rows come back in [`contacts_rejected`](https://docs.miraiminds.co/v2/campaigns#contacts-are-reported-row-by-row-not-rejected-as-a-batch) by index, and the rest of the batch goes in. |
| A call that fails on our side | Ends `failed`. Calling again is up to you. | Placed again without using one of the contact's attempts, and not billed. |
| Low wallet | `402 insufficient_balance`, and nothing is kept. Send the call again after you top up. | The campaign [pauses](https://docs.miraiminds.co/v2/campaigns.md#pause-reasons) with `insufficient_balance`, and every contact keeps its place. Add credit and resume it. |
| Sending twice | `Idempotency-Key` keeps a retried request to one call for 24 hours. | Your contact `id` is unique for the life of the campaign. Sending it again counts in `contacts_duplicate` and rings nobody. |
| Results | `call.*` webhooks to the call's `webhook_url`, and `call.processed` with the transcript when you send `final_results: true`. | The same webhooks, carrying `campaign_id`, `contact_id` and your `metadata`. Each call ends with `call.processed`, transcript and results included, by default. |

A refused direct call and a rejected campaign row both appear in
[Refused requests](https://docs.miraiminds.co/v2/refusals.md). Once your company is live, its owners also get
an email when one keeps repeating.

## Space retries by hours

Across the platform, a second attempt after an unanswered call connects about
24% of the time when it comes within 15 minutes. When it comes one to three
hours later, about 33% connect.

Set `re_attempt_period_secs` to `7200` (two hours) with a `retry_count` of 1
or 2. If your customers pick up more at some
hours of the day, add `retry_slots`: up to 4 `{start, end}` ranges, each inside
`slots`, and retries ring only inside them. First calls are never held back by
`retry_slots`, and neither is a call placed again after a failure on our side.

## Move from direct calls to an always-on campaign

You create the campaign once. After that, each `POST /v2/calls` becomes a
`POST /v2/campaigns/{id}/contacts` with one contact.

| On `POST /v2/calls` | On the campaign |
| :- | :- |
| `agent_id` | The campaign's `agent_id`, set once. Use one campaign per agent. |
| `to` | The contact's `phone`. |
| `variables` | The contact's `variables`, with the same [rules and limits](https://docs.miraiminds.co/v2/calls.md#how-long-a-value-can-be). |
| `metadata` | The contact's [`metadata`](https://docs.miraiminds.co/v2/campaigns#your-own-fields-metadata). Every call to the contact carries it in `data.call.metadata`. |
| `Idempotency-Key` | The contact's `id`: your own record id, such as `cart-5531`. |
| `call_settings` | The contact's [`call_settings`](https://docs.miraiminds.co/v2/campaigns#voice-and-language-per-contact). |
| `webhook_url`, `max_duration_secs`, `phone_number_id`, `pool_id` | Set once on the campaign. |
| `final_results` | On by default for a campaign. |
| `first_message`, `system_prompt` | Not set per contact. Personalise the agent's own prompt and first message with `variables`. |
| Your retry and scheduling code | `retry_count`, `re_attempt_period_secs`, `retry_slots` and `slots` on the campaign, and `not_before`, `expires_at` and `priority` on each contact. |

### Step 1: Create the campaign once

Create it, start it, and keep its id in your configuration.

> [tab] cURL
>
> ```bash theme={"system"}
> curl -X POST https://sandbox.voice.miraiminds.co/v2/campaigns \
>   -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
>   -H "Content-Type: application/json" \
>   -H "Idempotency-Key: cart-reminders-campaign-1" \
>   -d '{
>     "name": "Cart reminders (always on)",
>     "agent_id": "agt_01K7Q9F3K7M2N5P9R4T6V8W0XZ",
>     "timezone": "Asia/Kolkata",
>     "start_date": "2026-12-01",
>     "end_date": "2027-05-31",
>     "slots": [{ "start": "10:00", "end": "20:00" }],
>     "max_concurrent": 5,
>     "retry_count": 2,
>     "re_attempt_period_secs": 7200,
>     "always_on": true,
>     "webhook_url": "https://example.com/mirai/webhook"
>   }'
>
> curl -X POST https://sandbox.voice.miraiminds.co/v2/campaigns/cmp_01K8QAC5N9P4R7S3T6V8W2X4YB/start \
>   -H "Authorization: Bearer sk_live_YOUR_API_KEY"
> ```

> [tab] Python
>
> ```python theme={"system"}
> import os, httpx
>
> API = "https://sandbox.voice.miraiminds.co"
> auth = {"Authorization": f"Bearer {os.environ['MIRAI_API_KEY']}"}
>
> campaign = httpx.post(
>     f"{API}/v2/campaigns",
>     headers={**auth, "Idempotency-Key": "cart-reminders-campaign-1"},
>     json={
>         "name": "Cart reminders (always on)",
>         "agent_id": "agt_01K7Q9F3K7M2N5P9R4T6V8W0XZ",
>         "timezone": "Asia/Kolkata",
>         "start_date": "2026-12-01",
>         "end_date": "2027-05-31",
>         "slots": [{"start": "10:00", "end": "20:00"}],
>         "max_concurrent": 5,
>         "retry_count": 2,
>         "re_attempt_period_secs": 7200,
>         "always_on": True,
>         "webhook_url": "https://example.com/mirai/webhook",
>     },
>     timeout=30,
> ).raise_for_status().json()
>
> httpx.post(f"{API}/v2/campaigns/{campaign['id']}/start",
>            headers=auth, timeout=30).raise_for_status()
> print(campaign["id"])  # keep it in your configuration as MIRAI_CAMPAIGN_ID
> ```

> [tab] Node.js
>
> ```javascript theme={"system"}
> const API = "https://sandbox.voice.miraiminds.co";
> const auth = { Authorization: `Bearer ${process.env.MIRAI_API_KEY}` };
>
> const res = await fetch(`${API}/v2/campaigns`, {
>   method: "POST",
>   headers: {
>     ...auth,
>     "Content-Type": "application/json",
>     "Idempotency-Key": "cart-reminders-campaign-1",
>   },
>   body: JSON.stringify({
>     name: "Cart reminders (always on)",
>     agent_id: "agt_01K7Q9F3K7M2N5P9R4T6V8W0XZ",
>     timezone: "Asia/Kolkata",
>     start_date: "2026-12-01",
>     end_date: "2027-05-31",
>     slots: [{ start: "10:00", end: "20:00" }],
>     max_concurrent: 5,
>     retry_count: 2,
>     re_attempt_period_secs: 7200,
>     always_on: true,
>     webhook_url: "https://example.com/mirai/webhook",
>   }),
> });
> const campaign = await res.json();
> if (!res.ok) throw new Error(`${campaign.error.code}: ${campaign.error.message}`);
>
> const started = await fetch(`${API}/v2/campaigns/${campaign.id}/start`, {
>   method: "POST",
>   headers: auth,
> });
> if (!started.ok) throw new Error(`start failed: ${started.status}`);
> console.log(campaign.id); // keep it in your configuration as MIRAI_CAMPAIGN_ID
> ```

* Set `end_date` as far ahead as the campaign should stay open. Running out of
  contacts never ends an always-on campaign.
* Calling hours in India must lie inside 09:00 to 21:00 IST.
* `budget_paise` is optional. On an open campaign it counts everything the
  campaign has ever spent, so treat it as a ceiling you raise from time to
  time, or leave it out and rely on the wallet.

### Step 2: Add each event as a contact

Where your code placed a call, add a contact instead. Give it your own `id`,
such as the cart or order id. Sending the same `id` again is safe: it counts in
`contacts_duplicate` and rings nobody, so you can retry a request that timed out
without a second call. A new cart for the same phone number gets a new `id` and
is called.

> [tab] cURL
>
> ```bash theme={"system"}
> curl -X POST https://sandbox.voice.miraiminds.co/v2/campaigns/cmp_01K8QAC5N9P4R7S3T6V8W2X4YB/contacts \
>   -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "contacts": [
>       { "id": "cart-5531", "phone": "+919876543210",
>         "variables": { "customer_name": "Rahul", "items": "2 cotton kurtas" },
>         "metadata": { "cart_id": "5531", "store": "web" },
>         "expires_at": "2026-12-02T20:00:00+05:30",
>         "priority": 10 }
>     ]
>   }'
> ```

> [tab] Python
>
> ```python theme={"system"}
> CAMPAIGN = os.environ["MIRAI_CAMPAIGN_ID"]
>
>
> def call_about_cart(cart) -> bool:
>     r = httpx.post(
>         f"{API}/v2/campaigns/{CAMPAIGN}/contacts",
>         headers=auth,
>         json={"contacts": [{
>             "id": f"cart-{cart.id}",
>             "phone": cart.phone,  # E.164, e.g. +919876543210
>             "variables": {"customer_name": cart.first_name, "items": cart.summary},
>             "metadata": {"cart_id": str(cart.id), "store": cart.store},
>             "expires_at": cart.call_deadline.isoformat(),  # aware datetime, e.g. 2026-12-02T20:00:00+05:30
>             "priority": 10 if cart.value_inr >= 5000 else 0,
>         }]},
>         timeout=30,
>     )
>     if r.status_code == 409:
>         raise RuntimeError("campaign has finished; create a new one")
>     added = r.raise_for_status().json()
>     if added["contacts_rejected"]:
>         raise ValueError(added["contacts_rejected"][0]["reason"])  # fix the row, don't resend it as is
>     return added["contacts_accepted"] == 1  # False: this cart is already in the campaign
> ```

> [tab] Node.js
>
> ```javascript theme={"system"}
> const CAMPAIGN = process.env.MIRAI_CAMPAIGN_ID;
>
> export async function callAboutCart(cart) {
>   const res = await fetch(`${API}/v2/campaigns/${CAMPAIGN}/contacts`, {
>     method: "POST",
>     headers: { ...auth, "Content-Type": "application/json" },
>     body: JSON.stringify({
>       contacts: [{
>         id: `cart-${cart.id}`,
>         phone: cart.phone, // E.164, e.g. +919876543210
>         variables: { customer_name: cart.firstName, items: cart.summary },
>         metadata: { cart_id: String(cart.id), store: cart.store },
>         expires_at: cart.callDeadline, // RFC 3339 with offset, e.g. 2026-12-02T20:00:00+05:30
>         priority: cart.valueInr >= 5000 ? 10 : 0,
>       }],
>     }),
>   });
>   if (res.status === 409) throw new Error("campaign has finished; create a new one");
>   const added = await res.json();
>   if (!res.ok) throw new Error(`${added.error.code}: ${added.error.message}`);
>   if (added.contacts_rejected.length) throw new Error(added.contacts_rejected[0].reason);
>   return added.contacts_accepted === 1; // false: this cart is already in the campaign
> }
> ```

```json title="200 OK" theme={"system"}
{
  "id": "cmp_01K8QAC5N9P4R7S3T6V8W2X4YB",
  "object": "campaign",
  "status": "play",
  "always_on": true,
  "contacts_accepted": 1,
  "contacts_duplicate": 0,
  "contacts_rejected": []
}
```

| Field | Use it for |
| :- | :- |
| `id` | Your own key for the contact. It comes back as `data.call.contact_id` on every webhook. |
| `metadata` | The ids your webhook handler needs to find your row. The agent never sees it. |
| `expires_at` | The moment the call stops being useful. A contact that is still waiting then ends `expired` and is never called, retries included. |
| `not_before` | The earliest moment to call, such as an hour after the cart was left. |
| `priority` | Among contacts due at the same moment, higher goes first. Use it for urgent or high-value events. |

The contact is called straight away when the calling window is open, and when
it next opens otherwise. If the customer finishes the purchase first,
[cancel the contact](https://docs.miraiminds.co/v2/campaigns.md#cancel-a-contact) so nobody is called about
it.

### Step 3: Match webhooks to your records

Every call of the campaign sends the usual `call.*` events to the campaign's
`webhook_url`. Each event has `data.call.campaign_id`, `data.call.contact_id`
and your `metadata` in `data.call.metadata`. With `final_results` on, which is
the campaign default, each call also ends with one
[`call.processed`](https://docs.miraiminds.co/v2/webhooks#final-results) that has the transcript and the
after-call results.

Do this work after you have [verified the signature](https://docs.miraiminds.co/v2/webhooks.md#signature-verification)
and answered `200`:

> [tab] Python
>
> ```python theme={"system"}
> def handle_event(event: dict) -> None:
>     call = event["data"].get("call")
>     if not call or call.get("campaign_id") != CAMPAIGN:
>         return
>     cart_id = call.get("metadata", {}).get("cart_id")
>
>     if event["type"] == "call.processed":
>         analysis = call.get("analysis") or {}
>         db.carts.update(
>             cart_id,
>             last_call_id=call["id"],
>             call_status=call["status"],               # completed, no_answer, ...
>             outcome=analysis.get("data", {}),         # your extracted fields
>             summary=analysis.get("summary"),
>             transcript=event["data"]["transcript"].get("turns", []),
>         )
> ```

> [tab] Node.js
>
> ```javascript theme={"system"}
> export async function handleEvent(event) {
>   const call = event.data.call;
>   if (!call || call.campaign_id !== CAMPAIGN) return;
>   const cartId = call.metadata?.cart_id;
>
>   if (event.type === "call.processed") {
>     const analysis = call.analysis ?? {};
>     await db.carts.update(cartId, {
>       lastCallId: call.id,
>       callStatus: call.status, // completed, no_answer, ...
>       outcome: analysis.data ?? {}, // your extracted fields
>       summary: analysis.summary,
>       transcript: event.data.transcript?.turns ?? [],
>     });
>   }
> }
> ```

`db` stands for your own database. A contact can have several calls, one for
each attempt, and each carries the same `metadata`. Keep the latest, or read the
contact's state from [List contacts](https://docs.miraiminds.co/v2/campaigns.md#list-contacts): `exhausted`
means it used every attempt and never connected.

### Step 4: Watch it

* Alert on `campaign.paused` with a `pause_reason`. An open campaign that
  pauses for money stops calling until you add credit and resume it.
* Read [Refused requests](https://docs.miraiminds.co/v2/refusals.md) for rejected rows, or watch
  `contacts_rejected` in your own code.
* [Pause the campaign](https://docs.miraiminds.co/v2/campaigns.md#pause-a-campaign) when you need calls to
  stop for a while. New contacts are still accepted and wait their turn.

## When to keep direct calls

Keep `POST /v2/calls` where a person is waiting for the phone to ring, for
browser and Realtime sessions, and for test calls. For those, send an
`Idempotency-Key`, check every answer, and [alert on `4xx`](https://docs.miraiminds.co/v2/refusals#alert-on-refusals-in-your-own-code).

## Related

> [card] [Campaigns](https://docs.miraiminds.co/v2/campaigns.md#always-on-campaigns)
>
> Always-on campaigns, the contact schedule and every campaign setting.

> [card] [Calls](https://docs.miraiminds.co/v2/calls.md#pacing-and-the-call-queue)
>
> Direct calls, the call queue on Mirai numbers and variable limits.

> [card] [Refused requests](https://docs.miraiminds.co/v2/refusals.md)
>
> Every refused call and rejected contact, with the fix.

> [card] [Phone numbers and pools](https://docs.miraiminds.co/v2/phone-numbers.md)
>
> Spread calls over several numbers at a pace each can keep.


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