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

# Runs and results

> How POST /chat starts a durable run, and how to wait for it, poll it, retry it safely, answer its questions and cancel it.

A run is one turn of an agent's work: the message you send and everything the agent does to answer it. `POST /chat` starts a run that the platform carries out in the background, so the work does not depend on your HTTP connection staying open.

## The durable-run model

`POST /chat` creates the run and gives you its `run_id`. Two form fields decide what the first response looks like:

| Mode | Fields | First response |
| - | - | - |
| Observe (default) | `streaming=false`, `wait=true` | The request stays open. If the run finishes within the observe window (10 minutes by default), you get the result with `200`. Otherwise you get a `202` run handle and the run keeps going |
| Fire and forget | `streaming=false`, `wait=false` | A `202` run handle at once |
| Stream | `streaming=true` | An NDJSON stream of the run, with an `x-agent-run-id` header. See [Streaming](https://docs.neuralfactory.ai/api-reference/streaming.md) |

For a run that is still going, there are three ways to get the result:

1. Poll `GET /runs/{run_id}` until the status is final. See [Poll a run](#poll-a-run).
2. Stream `GET /runs/{run_id}/stream` (Server-Sent Events). See [Streaming](https://docs.neuralfactory.ai/api-reference/streaming.md).
3. Pass `callback_url` on `POST /chat` and receive a POST when the run ends or pauses. See [Webhooks](https://docs.neuralfactory.ai/api-reference/webhooks.md).

> [!NOTE]
>
> A dropped connection never cancels a run. Whether you stream, poll or disconnect, the run finishes, its result is saved and it is billed once. Reattach at any time with the `run_id`.

## Start a run: POST /chat

Send the body as `multipart/form-data`.

```bash theme={null}
curl -X POST https://api.neuralfactory.ai/chat \
  -H "Authorization: Bearer $NF_TOKEN" \
  -F "agent_id=$AGENT_ID" \
  -F "message=Draft a reply to the attached customer email" \
  -F "files=@./customer-email.pdf" \
  -F "wait=false" \
  -F "idempotency_key=ticket-4711-reply"
```

### Form fields

| Field | Type | Default | Description |
| - | - | - | - |
| `message` | string | | Required. The message. It may take at most half of the context window of the agent's model, in tokens; a longer one answers `400` with `Message is too long: … tokens, the agent's model allows … tokens` |
| `agent_id` | string | | Required. The agent. It must be published: a draft answers `409` with `This agent is not published yet` |
| `chat_id` | string | generated | The conversation. Leave it out to start a new one; send it again to continue one. Another person's conversation answers `403` |
| `wait` | bool | `true` | Without streaming only. `false` returns a `202` at once instead of observing |
| `streaming` | bool | `false` | `true` streams the run as NDJSON |
| `idempotency_key` | string | | A retry with the same key reattaches to the existing run. See [Idempotency](#idempotency) |
| `callback_url` | string | | An `https` address that receives the run's webhooks. See [Webhooks](https://docs.neuralfactory.ai/api-reference/webhooks.md) |
| `on_conflict` | string | `reject` | What to do when the conversation already has an active run: `reject` answers `409`, `enqueue` holds this message behind it. See [One active run per conversation](#one-active-run-per-conversation) |
| `save_interactions` | bool | `true` | `false` keeps the message, the answer and its sources out of the stored interaction record and out of the conversation's transcript |
| `subject_id` | string | | Up to 256 characters: who the turn is about, in your own terms (a customer or case number, never a national id), so the interaction record can be found later |
| `name`, `email`, `client` | string | | Optional details about the caller, shown in **Interactions** |
| `files` | file | | Optional. Repeat the part once per file. At most 20 files of 20 MB each, 400 MB in total |

A rejected file answers with an `error` field instead of `detail`: `400` for too many files or a file type that is not supported (the answer lists the supported types), `413` for a file or a request that is too large.

### 202: the run handle

You get a run handle for `wait=false`, and in observe mode when the run outlives the window (it is still `queued`, `running` or `awaiting_input`):

```json theme={null}
{
  "run_id": "…",
  "chat_id": "…",
  "agent_id": "…",
  "status": "running",
  "durable": true,
  "stream_url": "/runs/…/stream",
  "interrupts": [],
  "enqueued_followup": null
}
```

* `interrupts` lists the pending requests for a person. It is empty unless the run is `awaiting_input`.
* `enqueued_followup` is set when your message was held behind an active run with `on_conflict=enqueue`.

A run that cannot start straight away comes back as a `queued` handle and starts as soon as it can. A run that still cannot start after several attempts ends `failed`, with the reason in its `error`.

### 200: the completed result

When `wait=true` and the run finishes within the window, the response is the agent's answer: the same object as the `result` field of `GET /runs/{run_id}`, plus `agent_id` and `usage_status`. The answer text is in its `result` field, and the sources it used, if any, in `documents`.

* A run cancelled within the window returns `200` with `{"run_id", "status": "cancelled", "agent_id"}`.
* A run that failed or timed out within the window returns `500` with the run's error in `detail`.

## Poll a run

`GET /runs/{run_id}` returns the run. Poll while the status is `queued` or `running`. Stop when it is final. When it is `awaiting_input`, act on it instead of polling: see [Pauses for a person](#pauses-for-a-person).

```bash theme={null}
curl https://api.neuralfactory.ai/runs/$RUN_ID \
  -H "Authorization: Bearer $NF_TOKEN"
```

| Field | Description |
| - | - |
| `run_id`, `chat_id`, `agent_id` | Identifiers |
| `status` | Where the run is. See [Run status](#run-status) |
| `question` | The message that started the run |
| `result` | The agent's answer once `completed`: the text in `result.result`, and the sources it used in `result.documents` when it used any |
| `files` | Files the run produced |
| `interrupts` | Requests for a person, pending or decided |
| `error` | Why the run ended, when `failed` or `timed_out` |
| `usage` | `{ prompt_tokens, completion_tokens }` |
| `cost` | What the run cost |
| `resume_attempts` | How many times the run was picked up again after a pause or an interruption |
| `active_seconds` | Time spent working. Time paused is not counted |
| `child_run_count` | Subagent tasks the run completed |
| `live_state` | The latest snapshot of a run in progress, to show it as it works. `null` once a finished run is billed: read the answer from `result` |
| `created_at`, `updated_at` | Timestamps |

The call answers `404` when the run does not exist and `403` when it is outside your key's scope.

A finished run is not removed after a fixed time. It stays readable until its conversation or the owning account is deleted, or until your organization's retention setting removes it. After that the call answers `404`.

### List a conversation's runs

`GET /chats/{chat_id}/runs` returns the conversation's 20 most recent runs. Add `active=true` to get only the run that is `queued`, `running` or `awaiting_input`, to reattach to a turn in progress.

```bash theme={null}
curl "https://api.neuralfactory.ai/chats/$CHAT_ID/runs?active=true" \
  -H "Authorization: Bearer $NF_TOKEN"
```

## Idempotency

A network retry of `POST /chat` could start a second run, and bill it. Send a stable `idempotency_key` and a retry reattaches to the original run instead.

* Derive the key from the unit of work, such as a request id or an order number. A new random value on each attempt defeats the purpose.
* An idempotency key belongs to the person the API key acts for (its creator) in their organization. The same string sent by someone else starts a separate run. Two API keys made by the same person share their idempotency keys.
* A matching `idempotency_key` reattaches to your own existing run instead of conflicting with it.

## One active run per conversation

A `chat_id` has at most one active run (`queued`, `running` or `awaiting_input`) at a time. Posting to a busy conversation answers `409` with the run that holds it:

```json theme={null}
{ "detail": { "message": "This chat already has a run in progress", "active_run_id": "…" } }
```

A message sent to a busy conversation is handled in this order:

1. If the active run is `awaiting_input` on a question from the agent, your message is the answer. It resumes that run instead of conflicting.
2. With `on_conflict=enqueue`, the message is held on the active run and started as its own turn as soon as that run ends. The response is the active run's handle with `enqueued_followup` set. Up to 5 messages can be held per run; past that you get the `409`.
3. Otherwise you get the `409`. Attach to `active_run_id` (poll or stream it) and send again once it ends.

To hold a message behind a run you already know, send `POST /runs/{run_id}/followups` with `{"message": "…"}`. It answers `409` when the run is no longer active or already holds 5 messages; send the message normally then. The held message becomes a new run, so the checks a new run passes apply when you send it: on SaaS a frozen account answers `403` and used-up usage `429`.

To work in parallel, use separate `chat_id`s, within your [concurrency limits](https://docs.neuralfactory.ai/api-reference/rate-limits.md).

## Pauses for a person

An agent can stop in the middle of a run to wait for a person. The run's status becomes `awaiting_input`, and `interrupts` lists what is pending. Each interrupt has an `interrupt_id`, a `kind` and a `payload` with what the agent asked. How you continue depends on the `kind`.

`clarification`: the agent asked a question. Send your answer to `POST /chat` as the next `message`, with the same `chat_id`. The run continues.

`browser_handoff`: the agent needs a person in its browser, for example to sign in to a site. Do what it asks in the web app's **Browser** tab, then resume the run, with an optional note for the agent. Replying with `POST /chat` also resumes it, with your message as the note.

```bash theme={null}
curl -X POST https://api.neuralfactory.ai/runs/$RUN_ID/resume \
  -H "Authorization: Bearer $NF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"resumes": {"<interrupt_id>": {"note": "Signed in, carry on"}}}'
```

* `resumes` must answer exactly the pending interrupt ids. A partial or different set answers `409` with `Resume must decide exactly the pending interrupts: […]`.
* A second submission, or a resume that loses to a cancel, answers `409` with `Run is not awaiting input or a decision was already recorded`.
* `decided_by` (optional) records who answered when a key relays someone else's decision. A signed-in person always decides as themselves.
* On success the run goes back to `queued` and continues. On SaaS a resume counts against your [concurrency limits](https://docs.neuralfactory.ai/api-reference/rate-limits.md) again, so it can answer `429`.

A pause left unanswered for 72 hours (by default) ends the run as `failed`, with `Human input request expired before a decision was recorded.` Work done before the pause is billed.

## Cancel a run

```bash theme={null}
curl -X POST https://api.neuralfactory.ai/runs/$RUN_ID/cancel \
  -H "Authorization: Bearer $NF_TOKEN"
```

You can repeat a cancel safely; it always returns the run.

* A `queued` or `awaiting_input` run stops at once.
* A `running` run finishes the step it is on, then becomes `cancelled`.
* A finished run is left as it is.

Work done before the stop is billed.

`GET /runs/{run_id}/audit` lists who did what to a run (created, cancelled, resumed), with the same access rule as reading the run.

## Run status

```mermaid theme={null}
stateDiagram-v2
  [*] --> queued
  queued --> running
  queued --> cancelled
  queued --> failed
  running --> awaiting_input
  awaiting_input --> queued: resume
  running --> completed
  running --> failed
  running --> timed_out
  running --> cancelled
  awaiting_input --> cancelled
  awaiting_input --> failed: expired
```

| Status | Kind | Meaning |
| - | - | - |
| `queued` | active | Waiting to start |
| `running` | active | Working |
| `awaiting_input` | active | Paused for a person: resume it or reply |
| `completed` | final | Finished. `result` holds the answer |
| `failed` | final | Ended with an error. See `error` |
| `cancelled` | final | Cancelled on request |
| `timed_out` | final | Reached its limit of one hour of active work, or of tokens for one run (2 million), both by default. `error` names the limit, for example `Run exceeded the maximum active execution time of 3600s and was terminated.` |

Any active run can be cancelled. Time limits count active work only: a paused run accrues no time, and an `awaiting_input` run does not count against the concurrency limits.

## Related

* [Streaming](https://docs.neuralfactory.ai/api-reference/streaming.md)
* [Webhooks](https://docs.neuralfactory.ai/api-reference/webhooks.md)
* [Errors](https://docs.neuralfactory.ai/api-reference/errors.md)
* [Rate and concurrency limits](https://docs.neuralfactory.ai/api-reference/rate-limits.md)


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