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

# Streaming

> Follow a run as it works, either on the POST /chat response or on the run's own event stream.

Streaming lets you show a run's progress while the agent works, for example a "searching the knowledge base" line in your own chat window, instead of waiting for the final answer. There are two streams:

| Stream | How you open it | Format | Use it when |
| - | - | - | - |
| The chat stream | `POST /chat` with `streaming=true` | NDJSON, one JSON object per line | You start the run and want its progress on the same request |
| The run stream | `GET /runs/{run_id}/stream` | Server-Sent Events | You already have a `run_id`, or your connection dropped and you want to reattach |

Closing either stream never cancels the run. The run finishes, its result is saved and it is billed once. To stop it, [cancel it](https://docs.neuralfactory.ai/api-reference/runs.md#cancel-a-run).

## The chat stream

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

`-N` turns off curl's buffering so lines show as they arrive.

The response is `application/x-ndjson` and carries the header `x-agent-run-id: <run_id>`. Keep that id: if the connection drops, you can poll, stream or cancel the run with it.

Authentication, validation and limit errors come back as a normal JSON error response before the stream starts. See [Errors](https://docs.neuralfactory.ai/api-reference/errors.md).

### Lines on the chat stream

Read the body line by line and parse each line as JSON. A line is one of these:

| Line | Shape | Meaning |
| - | - | - |
| Progress | `{"response": {…}, "agent_id", "streaming": true}` | A snapshot of the run so far. Each one replaces the previous one |
| Status | `{"run_status": "queued", "run_id", "agent_id", "streaming": true}` | The run's status changed. Also sent first when the run has produced nothing yet, for example while it waits to start |
| Paused | `{"awaiting_input": [ …interrupts ], "run_id", "agent_id", "streaming": false}` | The run is waiting for a person. See [Pauses for a person](https://docs.neuralfactory.ai/api-reference/runs.md#pauses-for-a-person) |
| Final answer | `{"response": {…}, "agent_id", "streaming": true, "terminal": true}` | The finished run's result. Its `result` field is the answer text. Take this as the answer even if a progress line already showed the same text |
| Files | `{"session_id", "file_count", "files": […], "agent_id", "streaming": false, "final": true}` | Files the run produced, after the final answer |
| Usage | `{"usage_status": {"can_use", "message", "in_overflow"}, "record_id", "final": true}` | Whether you can keep sending messages, and the id of the interaction record. The last line of a completed run |
| Error | `{"error": "…", "agent_id", …}` | The run failed, was cancelled (`Run was cancelled`), or the stream could not continue, for example after its one-hour cap. The stream ends after it; the run itself goes on unless it ended |

### Read the chat stream in Python

```python theme={null}
import json, os, requests

API = os.environ["NF_API"]
headers = {"Authorization": f"Bearer {os.environ['NF_TOKEN']}"}

with requests.post(
    f"{API}/chat",
    headers=headers,
    data={"agent_id": os.environ["AGENT_ID"], "message": "Summarize last week's sales", "streaming": "true"},
    stream=True,
    timeout=(10, None),
) as resp:
    resp.raise_for_status()
    run_id = resp.headers["x-agent-run-id"]
    for raw in resp.iter_lines():
        if not raw:
            continue
        line = json.loads(raw)
        if line.get("terminal"):
            print(line["response"].get("result"))
        elif "awaiting_input" in line:
            print("The agent is waiting for a person:", line["awaiting_input"])
        elif "error" in line:
            print("Run ended:", line["error"])
```

Turn off the read timeout, or set it high. A run can be quiet for a while before its first progress line, while it waits to start or works on a long step.

## The run stream

`GET /runs/{run_id}/stream` sends Server-Sent Events over the run's life. It needs the same access as [polling the run](https://docs.neuralfactory.ai/api-reference/runs.md#poll-a-run).

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

Each event has an `id`, an `event` name and a JSON `data` line:

```
id: 1
event: init
data: {"run_id": "…", "chat_id": "…", "agent_id": "…", "status": "running", "live_state": {…}, "interrupts": []}
```

| Event | Payload | Meaning |
| - | - | - |
| `init` | `{ run_id, chat_id, agent_id, status, live_state, interrupts }` | The full snapshot. Sent first, and again on every reconnect |
| `step` | `{ run_id, live_state }` | The run moved on |
| `awaiting_input` | `{ run_id, interrupts }` | The run paused for a person |
| `status` | `{ run_id, status }` | A status change that is not the end |
| `done` | `{ run_id, status, error, cost, files }` | The end. Sent exactly once, then the stream closes. Read the answer with `GET /runs/{run_id}` |
| `stream_error` | `{ run_id, error }` | The run was not found, your access ended, or the connection reached its one-hour cap. Reconnect or poll |

A comment line (`: heartbeat`) arrives about every 15 seconds to keep proxies from closing the connection.

### Reconnecting

Reconnect whenever the stream closes before `done`. Every connection starts with a fresh `init` snapshot that replaces what you had, so nothing is lost in between. `Last-Event-ID` (or the `last_event_id` query parameter) is accepted to keep event ids increasing, but it does not replay missed events. Access is checked again every minute while the stream is open, so a key that is turned off mid-run gets a `stream_error` within about a minute.

## Related

* [Runs and results](https://docs.neuralfactory.ai/api-reference/runs.md)
* [Webhooks](https://docs.neuralfactory.ai/api-reference/webhooks.md)


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