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

# API Reference

> Integrate Neural Factory into your applications with the REST API.

# API Reference

The Neural Factory REST API lets you programmatically interact with the platform — send messages to agents, manage knowledge bases, and retrieve analytics data.

Agent work runs as a **durable run**: `POST /chat` enqueues a run that a background worker executes, so a request can outlive any single HTTP connection. This page documents that contract end-to-end — how to start a run, the three ways to get its result, human-in-the-loop pauses, cancellation, idempotency, and webhooks.

## Base URL

All API requests are made to your Neural Factory instance:

```
https://app.neuralfactory.ai/api/v1
```

For enterprise deployments, replace with your custom domain.

## Authentication

All API requests are authenticated with an API key. A program first trades the key's secret for a token, then sends that token as a Bearer token in the `Authorization` header. The secret itself is never sent on other requests.

```bash theme={null}
NF_TOKEN=$(curl -s -X POST https://app.neuralfactory.ai/api/v1/apikeys/token \
  -H "Content-Type: application/json" \
  -d "{\"key_secret\": \"$NF_API_KEY\"}" | jq -r .access_token)
```

The token is valid for 24 hours (`expires_in` in the response); trade the secret again for a new one. The exchange answers `401` when the secret is wrong, the key is turned off or deleted, or (on SaaS) the person who created it no longer has a seat in its organization.

```bash theme={null}
curl -X POST https://app.neuralfactory.ai/api/v1/chat \
  -H "Authorization: Bearer $NF_TOKEN" \
  -F "agent_id=agt_123" \
  -F "message=What is our remote work policy?"
```

API keys are created and managed in the [API Keys](https://docs.neuralfactory.ai/user-guide/admin/api-keys.md) section of the admin panel.

A key reaches only what its permissions allow: a call outside them answers `403`. Agents and workflows (including starting runs and scheduling workflows) need **Agents**; chatting needs **Chat**; reading the interactions (`GET /interactions`), which hold every turn of the organization, needs **Admin**. Agent schedules are managed by signed-in people only.

Keys are **organization-scoped**. A key can only reach agents and runs belonging to its organization; a key with no organization (an individual account's) can reach only resources its owner created, and never the administration of users and groups, which answers `403`. Every request is also subject to per-user and per-organization concurrency caps (see [Concurrency limits](#concurrency-limits)).

## Request format

* `POST /chat` is **`multipart/form-data`** — it accepts file uploads, so send fields as form parts (`-F` in curl), not a JSON body.
* Run-control endpoints that take a body (e.g. `POST /runs/{id}/resume`) accept **`application/json`**.
* Dates are ISO 8601 strings; IDs are strings.

***

## The durable-run model

`POST /chat` **enqueues** a run and returns a `run_id`. How the initial response behaves depends on two form params, `streaming` and `wait`:

| Mode | Params | Response |
| - | - | - |
| **Stream** | `streaming=true` | An NDJSON stream relayed from the run. Response carries an `x-agent-run-id` header so you can reattach later. |
| **Observe** (default) | `streaming=false`, `wait=true` | The request holds open and returns the **completed result** (`200`) if the run finishes within the observe window; otherwise a **`202` run handle** (the run keeps executing). |
| **Fire-and-forget** | `streaming=false`, `wait=false` | Returns a **`202` run handle immediately**. |

Whichever mode you choose, there are **three ways to obtain the result** of a run that is still executing:

1. **Poll** `GET /runs/{run_id}` until the status is terminal.
2. **Stream** `GET /runs/{run_id}/stream` (Server-Sent Events).
3. **Webhook** — pass `callback_url` on `POST /chat` to receive a terminal push.

> [!NOTE]
>
> A dropped connection never cancels a run. Whether you stream, poll, or disconnect, the worker finishes, saves the result, and bills exactly once. Reattach any time with the `run_id`.

***

## POST /chat

Start (or continue) an agent run. Encode the body as `multipart/form-data`.

### Form fields

| Field | Type | Default | Description |
| - | - | - | - |
| `message` | string | — | **Required.** The user message. It may take at most half of the context window of the agent's model, in tokens, and at most eight characters per token of that; a longer message is refused with `400` and a `detail` naming its size and the limit. |
| `agent_id` | string | — | **Required.** Target agent. |
| `chat_id` | string | generated | Conversation id. Omit to start a new conversation (the server returns/uses a new UUID); reuse it to continue one. |
| `streaming` | bool | `false` | `true` streams the run as NDJSON. |
| `wait` | bool | `true` | Non-streaming only. `false` returns a `202` immediately instead of observing. |
| `idempotency_key` | string | — | Retried POSTs with the same key re-attach to the existing run — no duplicate run and **no double billing**. |
| `callback_url` | string | — | HTTPS URL to receive terminal/HITL webhooks for this run. |
| `on_conflict` | string | `reject` | What to do when the chat already has an active run: `reject` → `409`; `enqueue` → park this message behind it (see [One active run per conversation](#one-active-run-per-conversation)). |
| `save_interactions` | bool | `true` | `false` redacts the stored message/response, and also keeps the message, the answer and its sources out of the chat transcript. |
| `name`, `email`, `client` | string | — | Optional caller/attribution metadata. |
| `files` | file\[] | — | Optional file uploads (repeat the part per file). |

### 202 — run handle

Returned by `wait=false`, or by the default observe mode when the run outlives the observe window (still `queued`, `running`, or `awaiting_input`):

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

`interrupts` lists any **pending** human-in-the-loop requests (empty unless the run paused as `awaiting_input`).

A run whose task queue is briefly unreachable is returned the same way, as a `queued` run handle, and starts when the queue recovers. A run that cannot be started within minutes ends `failed`, with the reason in its `error`.

### 200 — completed result

When `wait=true` and the run finishes within the observe window, the response is the agent's answer object (the same payload as the `result` field of `GET /runs/{id}`), plus `agent_id` and `usage_status`. A run cancelled within the window returns `{ "run_id", "status": "cancelled", "agent_id" }`; a failed run returns `500` with the error in `detail`.

### One active run per conversation

A `chat_id` may have only **one** active run (`queued`, `running`, or `awaiting_input`) at a time — the conversation's checkpoint thread has a single writer. Posting to a chat that is already busy returns `409` with the run that holds it:

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

A message arriving into a busy chat is resolved in a fixed order:

1. **It answers a pending clarification.** If the active run is `awaiting_input` on a clarification, your message *is* the answer: posting it resumes that run rather than conflicting.
2. **`on_conflict=enqueue`.** The message is parked on the active run and started as its own turn the moment that run reaches a terminal status. The response is the **active** run's handle plus the parked record — so a client can send without waiting, and without polling for a gap to slot into. Up to 5 messages may be parked per run; past that you get the `409`.
3. **Otherwise** — `409` as above. Handle it by attaching to `active_run_id` (poll or stream it) and sending once it finishes.

A matching `idempotency_key` re-attaches to your own existing run rather than conflicting with it.

`POST /runs/{run_id}/followups` with `{"message": "…"}` parks a message against a known run directly — the same behavior addressed by run id. It returns `409` if the run is no longer active or its queue is full, in which case send normally.

To run work in parallel, use separate `chat_id`s — subject to the [concurrency limits](#concurrency-limits).

### Streaming (`streaming=true`)

Returns `application/x-ndjson` — one JSON object per line — with response headers including `x-agent-run-id: <run_id>`. Capture that header to reattach (poll/stream/cancel) if the connection drops. Lines with a `response` are progress snapshots of the run, except the one marked `"terminal": true`, which holds the finished run's result.

```bash theme={null}
curl -N -X POST https://app.neuralfactory.ai/api/v1/chat \
  -H "Authorization: Bearer $NF_TOKEN" \
  -F "agent_id=agt_123" \
  -F "message=Summarize the attached report" \
  -F "files=@./report.pdf" \
  -F "streaming=true"
```

### Fire-and-forget with a webhook

```bash theme={null}
curl -X POST https://app.neuralfactory.ai/api/v1/chat \
  -H "Authorization: Bearer $NF_TOKEN" \
  -F "agent_id=agt_123" \
  -F "message=Draft the Q3 board deck" \
  -F "wait=false" \
  -F "idempotency_key=draft-q3-2026-0001" \
  -F "callback_url=https://example.com/hooks/nf"
```

***

## Getting the result

### Poll — GET /runs/{run_id}

Returns the run's public view. Poll while the status is `queued` or `running`; stop when it is terminal, and **act** (don't poll) when it is `awaiting_input`.

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

| Field | Description |
| - | - |
| `run_id`, `chat_id`, `agent_id` | Identifiers. |
| `status` | Lifecycle status (see [Run status lifecycle](#run-status-lifecycle)). |
| `question` | The initiating message. |
| `result` | The agent's answer object once `completed`. |
| `files` | Files produced by the run. |
| `interrupts` | Pending/decided human-in-the-loop requests. |
| `error` | Failure reason when `failed`/`timed_out`. |
| `usage` | `{ prompt_tokens, completion_tokens }`. |
| `cost` | Billed cost breakdown. |
| `resume_attempts` | Times the run was re-dispatched (resume/recovery). |
| `active_seconds` | Accumulated active execution time (paused time excluded). |
| `child_run_count` | Number of sub-agent tasks this run completed. |
| `live_state` | Latest truncated in-flight state snapshot (for rendering an in-progress turn). `null` once a finished run has been billed; read the answer from `result`. |
| `created_at`, `updated_at` | Timestamps. |

Returns `404` if the run does not exist, `403` if it is outside your org scope.

A terminal run is not removed after a fixed period. It stays readable until its chat or the owning account is deleted, or until your organization's retention override removes it; after that the request returns `404`.

### Stream — GET /runs/{run_id}/stream

Server-Sent Events over the run's lifecycle. Heartbeat comments arrive roughly every 15 s to keep proxies open.

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

| Event | Payload | Meaning |
| - | - | - |
| `init` | `{ run_id, chat_id, agent_id, status, live_state, interrupts }` | Full snapshot sent first (also on every reconnect). `live_state` is `null` for a finished run that has been billed; read the answer from `result` on `GET /runs/{run_id}`. |
| `step` | `{ run_id, live_state }` | The in-flight state advanced. |
| `awaiting_input` | `{ run_id, interrupts }` | The run paused for human input. |
| `status` | `{ run_id, status }` | A non-terminal status change. |
| `done` | `{ run_id, status, error, cost, files }` | Terminal — fires exactly once, then the stream ends. |
| `stream_error` | `{ run_id, error }` | Run not found, or the connection cap (\~1 h) was reached — reconnect or poll. |

> [!NOTE]
>
> `Last-Event-ID` is tolerated but is **not** a replay cursor: every reconnect gets a fresh `init` snapshot that supersedes prior state, so clients merge idempotently. There is no missed-event gap to backfill.

### Webhook — callback\_url

Pass `callback_url` (HTTPS) on `POST /chat` to receive a push at each **terminal** transition (`completed`, `failed`, `cancelled`, `timed_out`) and at each **pause** (`awaiting_input`). Delivery is exactly-once per state, best-effort with bounded retry on `5xx`, and can never affect the run.

```json theme={null}
{
  "event": "agent_run.terminal",
  "run_id": "run_a1b2c3",
  "chat_id": "chat_xyz",
  "agent_id": "agt_123",
  "status": "completed",
  "record_id": "rec_789",
  "error": null,
  "cost": { "total_cost": 0.0123 },
  "interrupts": [],
  "ts": "2026-07-22T10:00:00Z"
}
```

`event` is `agent_run.awaiting_input` when the run pauses (with `interrupts` populated), otherwise `agent_run.terminal`.

**Verify the signature.** When a webhook secret is configured, each delivery carries an HMAC over the raw request body:

```
X-NF-Event: agent-run
X-NF-Signature: sha256=<hex>
```

Recompute `HMAC-SHA256(secret, raw_body)` and compare (constant-time) against the `sha256=` value before trusting the payload.

***

## Idempotency

Network retries of `POST /chat` can otherwise create duplicate runs — and duplicate billing. Send a stable `idempotency_key` and a retried enqueue re-attaches to the original run instead of starting a new one. Use a key derived from the unit of work (e.g. a request id), not a random value per attempt.

***

## Human-in-the-loop (HITL)

An agent can pause mid-run for a human decision. The run's status becomes `awaiting_input` and its `interrupts` array lists what is pending. There are two ways to continue, depending on what the agent asked for:

**Approvals** — resume with the decision(s):

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

The body must decide **exactly** the currently pending interrupt ids — a partial or mismatched set returns `409`, as does a double-submit or a resume that races a cancel. On success the run flips back to `queued` and re-dispatches. An optional `decided_by` records who decided.

**Clarifications** — when the agent asked a follow-up question, simply `POST /chat` the next `message` with the **same `chat_id`**; the conversation continues.

***

## Cancelling a run

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

Cancellation is **idempotent** and always returns the run's public view. A `queued` or `awaiting_input` run stops immediately; a `running` run receives a cooperative stop and settles to `cancelled` shortly after; a terminal run is unchanged.

***

## Run status lifecycle

```
queued ──▶ running ──▶ completed | failed | timed_out
              │  ▲
              ▼  │  (resume)
         awaiting_input ──▶ cancelled
```

| Status | Kind | Meaning |
| - | - | - |
| `queued` | active | Enqueued, awaiting a worker. |
| `running` | active | Executing. |
| `awaiting_input` | active | Paused for human input (resume or reply). |
| `completed` | terminal | Finished successfully; `result` is populated. |
| `failed` | terminal | Errored; see `error`. |
| `cancelled` | terminal | Cancelled by request. |
| `timed_out` | terminal | Exceeded its active-time cap (1 h by default) **or** its per-run token ceiling. `error` reads "Run stopped at its execution limit." |

`awaiting_input` is an active status but does **not** count against concurrency caps — it is a human queue, not worker load. A pause left undecided for 72 hours expires and the run is cancelled.

Time limits apply to **active** execution only: a run accrues no time while paused for input, and a crashed-then-resumed run is not charged for the gap.

### List a chat's runs — GET /chats/{chat_id}/runs

Returns the chat's most recent runs (public view). Pass `active=true` to return only runs that are `queued`, `running`, or `awaiting_input` — useful to reattach to an in-flight turn.

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

***

## Error handling

Error responses carry an HTTP status and a `detail` message:

```json theme={null}
{ "detail": "Description of what went wrong" }
```

### Common status codes

| Code | Meaning |
| - | - |
| `200` | Success (completed result, or an idempotent cancel/resume view). |
| `202` | Accepted — durable run enqueued; use the `run_id` handle to poll/stream/await. |
| `400` | Bad request — invalid parameters or malformed resume body. |
| `401` | Unauthorized — missing or invalid API key. |
| `403` | Forbidden — resource outside your organization scope. |
| `404` | Not found. |
| `409` | Conflict — the chat already has an active run (body carries `active_run_id`), or a resume did not match the pending interrupts / lost a race. |
| `429` | Concurrency/rate limited — includes a `Retry-After` header. |
| `500` | Internal server error (also returned when a synchronously observed run failed). |

## Concurrency limits

Each API key is capped on concurrently active runs **per user** and **per organization** (`queued` + `running`; `awaiting_input` is excluded). For direct-API keys the per-user cap is attributed to the key owner, so varying `name`/`email` cannot escape it.

Exceeding a cap returns `429 Too Many Requests` with a `Retry-After` header (seconds):

```
HTTP/1.1 429 Too Many Requests
Retry-After: 30
```

Back off for the indicated interval, or wait for an in-flight run to finish, before retrying.


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