# Chat API

URL: https://docs.assistantcore.com/en/developers/chat-api

Create chat responses as JSON or an SSE stream, attach files, read history, rate messages, and erase end-user data.

Every example uses `$ASSISTANT_API_URL`, `$ASSISTANT_API_KEY`, and `$EXTERNAL_USER_ID` from the [Quickstart](/en/developers/quickstart). Each endpoint needs the scope shown next to it.

## Create a response [#create-a-response]

`POST /v1/responses` · scope `chat:write`

```bash
curl "$ASSISTANT_API_URL/v1/responses" \
  --request POST \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $(uuidgen)" \
  --data "{
    \"external_user_id\": \"$EXTERNAL_USER_ID\",
    \"input\": \"Summarize the attached policy.\",
    \"conversation_id\": \"a12d5e41-7ab7-4c8f-b024-c2c38b5c43f4\",
    \"file_ids\": [\"8d50c5c2-bf85-48a4-b252-8dc97410452c\"]
  }"
```

| Field | Required | Meaning and limits |
| :--- | :---: | :--- |
| `external_user_id` | Yes | 1–256 characters; your stable ID for the end user. |
| `input` | Yes | 1–100,000 characters. |
| `conversation_id` | No | UUID of a conversation owned by the same end user. Omit it to start a new conversation. |
| `file_ids` | No | Up to 10 file IDs uploaded for the same end user. |
| `model` | No | An active chat model code, for example `gemini-3.8-flash`. Omit it to use the assistant's model. An unknown code returns `400 MODEL_NOT_FOUND`. |
| `stream` | No | `false` (default) returns JSON; `true` returns an SSE stream. |
| `background` | No | `true` runs the response apart from the request, so it goes on if the client disconnects. `false` by default. See [Background responses](#background-responses). |

Unknown fields are rejected with `422 VALIDATION_ERROR`.

A non-streaming call returns `200` with a [Response object](/en/developers/reference):

```json
{
  "id": "resp_5f0c2a9e8b7d4c1fa3e6b2d9c8a7f104",
  "object": "response",
  "status": "completed",
  "conversation_id": "a12d5e41-7ab7-4c8f-b024-c2c38b5c43f4",
  "model": "gemini-3.8-flash",
  "output_text": "The policy allows returns within 30 days [1]...",
  "output_files": [],
  "sources": [
    {
      "n": 1,
      "kind": "pdf",
      "title": "Return policy.pdf",
      "url": null,
      "section": "Returns",
      "page": 2,
      "snippet": "Items can be returned within 30 days of delivery..."
    }
  ],
  "message_id": "b0f16c77-a275-46c8-9dc8-8fe9fd5991cc",
  "request_id": "3f9a1c0b7d2e"
}
```

Errors specific to this endpoint:

| Status and code | Cause |
| :--- | :--- |
| `404 CONVERSATION_NOT_FOUND` | `conversation_id` does not belong to this end user and assistant. |
| `404 FILE_NOT_FOUND` | A file ID was not uploaded by this end user; `details.file_id` names it. |
| `400 MODEL_NOT_FOUND` | `model` is not an active chat model; `details.model` repeats it. |
| `409 CONVERSATION_BUSY` | A background response is still being written in this conversation (background requests only); retry when it ends. |
| `402 INSUFFICIENT_CREDITS` | The assistant owner is out of credits. |
| `400 CONTEXT_TOO_LARGE` | The conversation no longer fits the model; start a new one. |
| `503 UPSTREAM_UNAVAILABLE` | The model provider failed or ended early; retry with backoff. |

## Stream with SSE [#stream-with-sse]

Set `"stream": true` to receive Server-Sent Events:

```bash
curl -N "$ASSISTANT_API_URL/v1/responses" \
  --request POST \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $(uuidgen)" \
  --data "{
    \"external_user_id\": \"$EXTERNAL_USER_ID\",
    \"input\": \"Explain the setup steps.\",
    \"stream\": true
  }"
```

Each event is an `event:` line and a `data:` line with JSON, followed by a blank line:

```text
event: response.created
data: {"type":"response.created","sequence":1,"response_id":"resp_5f0c…","status":"in_progress"}

event: response.output_text.delta
data: {"type":"response.output_text.delta","sequence":2,"response_id":"resp_5f0c…","delta":"First, "}

event: response.completed
data: {"type":"response.completed","sequence":9,"response_id":"resp_5f0c…","message_id":"b0f16c77-a275-46c8-9dc8-8fe9fd5991cc","finish_reason":"stop"}

```

Every event carries `type`, `sequence` (starts at 1 and increases by 1), and `response_id`. The stream always starts with `response.created` and ends with exactly one `response.completed` or `error`; a [background](#background-responses) stream can also end with `response.cancelled`. When nothing has been sent for 15 seconds, the server sends a `: heartbeat` comment line, which has no data.

| Event | Extra fields |
| :--- | :--- |
| `response.created` | `status`: `"in_progress"` |
| `conversation.created` | `conversation_id` (only when the request started a new conversation) |
| `response.output_text.delta` | `delta`: the next piece of answer text |
| `response.reasoning.delta` | `delta`: reasoning text, when the model exposes it |
| `response.tool_call.started` | `tool_call_id` (`call_…`), `name` |
| `response.tool_call.completed` | `tool_call_id`, `status` (`completed` or `failed`), `duration_ms` |
| `response.file.created` | `file`: `{ id, name, mime_type, bytes }` for a file the assistant created; download it with [`GET /v1/files/{id}/content`](#download-a-file) |
| `response.completed` | `message_id`, `finish_reason`, `sources` (see [Citations](#citations)) |
| `response.cancelled` | None. Ends a background response stopped with [cancel](#cancel). |
| `error` | `code`, `message`, `details`, `request_id`, `retryable` (same as REST errors) |

`finish_reason` is one of:

| Value | Meaning |
| :--- | :--- |
| `stop` | The model finished its answer. |
| `length` | The answer hit the model's output limit and may be cut off. |
| `refusal` | The model declined to answer. |
| `tool_limit` | The assistant reached its per-turn tool-call limit and answered with what it had. |

Mid-stream `error` codes are `UPSTREAM_UNAVAILABLE`, `CONTEXT_TOO_LARGE`, or `INTERNAL_SERVER_ERROR`. Errors found before the stream starts (auth, validation, credits) come back as a normal HTTP error instead.

### Tools in API responses [#tools-in-api-responses]

The assistant can call its tools during an API turn, and you see them as `response.tool_call.*` events. Nobody can approve a call over the API, so:

- Tools that delete or overwrite data are not offered on API turns.
- A call that one of the owner's approval rules sets to **Ask** or **Block** is refused, and its `response.tool_call.completed` has `status: "failed"`. The turn continues without it; there is no approval event to handle.
- Tools that need each user's own connected account are not offered.

See [Tool approvals](/en/tools-mcp/approvals) for how approval rules work.

### Citations [#citations]

When the assistant answers from its knowledge base or a web search, `output_text` marks each claim with a `[n]` citation, and `sources` lists what each number points to: `{ n, kind, title, url, section, page, snippet }`. `kind` is `web` or the knowledge file's type (`pdf`, `docx`, …). `url` is `null` for a knowledge file the owner does not share.

- `sources` holds only the numbers the text cites, in order of first citation.
- Numbers are unique across the conversation, so a reply can cite `[3]` from an earlier turn's search; `sources` still lists it.
- `output_text` keeps the markers as the model wrote them; render `sources` under the answer as its reference list.
- The stream delivers `sources` on `response.completed`; deltas carry the markers as plain text.

### Parse the stream [#parse-the-stream]

Keep a buffer across network chunks and decode with a streaming `TextDecoder`, because one chunk can hold part of an event or part of a multi-byte character:

<Tabs items={["JavaScript","Python"]}>
<Tab value="JavaScript">
```js
const response = await fetch(`${process.env.ASSISTANT_API_URL}/v1/responses`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.ASSISTANT_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({
    external_user_id: process.env.EXTERNAL_USER_ID,
    input: "Explain the setup steps.",
    stream: true,
  }),
})
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`)

const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ""

for (;;) {
  const { value, done } = await reader.read()
  buffer += decoder.decode(value, { stream: !done })

  let boundary
  while ((boundary = buffer.indexOf("\n\n")) >= 0) {
    const block = buffer.slice(0, boundary)
    buffer = buffer.slice(boundary + 2)
    const data = block
      .split("\n")
      .filter((line) => line.startsWith("data:"))
      .map((line) => line.slice(5).trimStart())
      .join("\n")
    if (!data) continue // heartbeat comment

    const event = JSON.parse(data)
    if (event.type === "response.output_text.delta") process.stdout.write(event.delta)
    if (event.type === "error") throw new Error(`${event.code}: ${event.message}`)
  }
  if (done) break
}
```
</Tab>

<Tab value="Python">
```python
import json
import os
import urllib.request
import uuid

request = urllib.request.Request(
    os.environ["ASSISTANT_API_URL"] + "/v1/responses",
    method="POST",
    headers={
        "Authorization": "Bearer " + os.environ["ASSISTANT_API_KEY"],
        "Content-Type": "application/json",
        "Idempotency-Key": str(uuid.uuid4()),
    },
    data=json.dumps({
        "external_user_id": os.environ["EXTERNAL_USER_ID"],
        "input": "Explain the setup steps.",
        "stream": True,
    }).encode(),
)

with urllib.request.urlopen(request, timeout=300) as response:
    data_lines = []
    for raw in response:  # one line at a time, already split on \n
        line = raw.decode("utf-8").rstrip("\r\n")
        if line.startswith("data:"):
            data_lines.append(line[5:].lstrip())
        elif line == "" and data_lines:
            event = json.loads("\n".join(data_lines))
            data_lines = []
            if event["type"] == "response.output_text.delta":
                print(event["delta"], end="", flush=True)
            elif event["type"] == "error":
                raise RuntimeError(f"{event['code']}: {event['message']}")
```
</Tab>
</Tabs>

If the connection drops before `response.completed`, the response stops and is saved with `status: "incomplete"`; fetch what was saved with [Retrieve a response](#retrieve-a-response). If your client may disconnect before a long answer ends, create it as a [background response](#background-responses) instead: it keeps running, and you can reconnect to its stream.

## Idempotency and retries [#idempotency-and-retries]

`Idempotency-Key` is optional but recommended on every `POST /v1/responses`. Keys are scoped to your API key.

| Situation | Result |
| :--- | :--- |
| Same key and body, first request still running | `409 REQUEST_IN_PROGRESS` (retryable). Wait and retry. |
| Same key, different body | `409 IDEMPOTENCY_CONFLICT`. Use a new key. |
| Same key and body, first request completed | `200` with the stored result and `Idempotent-Replayed: true`. The model is not called again. |
| Same key and body, first request was a background response | `200` with its in-progress Response and `Idempotent-Replayed: true`, as JSON even with `stream: true`. Follow or poll it by `id`. |
| First request failed, or a non-background client disconnected | The key is released; the retry runs again. |

A completed result is kept for 24 hours; a running request holds its key for at most 10 minutes. A replay never re-streams tokens: for a request that was streamed, the stored result has `id`, `conversation_id`, and `message_id` but an empty `output_text`, so fetch the text with `GET /v1/responses/{id}`.

## Retrieve a response [#retrieve-a-response]

`GET /v1/responses/{response_id}` · scope `chat:write`

```bash
curl "$ASSISTANT_API_URL/v1/responses/$RESPONSE_ID?external_user_id=$EXTERNAL_USER_ID" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
```

Returns the Response object with the full `output_text`, `output_files` (files the assistant created, such as images), and `sources` (see [Citations](#citations)). A background response reads `in_progress` while it runs (see [Poll](#poll)); add `stream=true` to [follow its stream](#follow-the-stream). Any other response becomes available when it finishes. Until then, and for IDs of another end user, the API returns `404 RESPONSE_NOT_FOUND`.

| `status` | Meaning |
| :--- | :--- |
| `in_progress` | A background response is still running. |
| `completed` | The response finished. |
| `failed` | The response ended with an error. |
| `incomplete` | The response ended early: a non-background stream lost its client, or the server stopped mid-response. |
| `cancelled` | A background response was stopped with [cancel](#cancel). |

## Background responses [#background-responses]

Set `"background": true` to run a response apart from the request. It goes on if your client disconnects, and you can follow, poll, or cancel it by `id`. Use it for long answers, or for clients on unreliable connections.

```bash
curl "$ASSISTANT_API_URL/v1/responses" \
  --request POST \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $(uuidgen)" \
  --data "{
    \"external_user_id\": \"$EXTERNAL_USER_ID\",
    \"input\": \"Write a detailed onboarding plan.\",
    \"background\": true
  }"
```

Without `stream`, the call returns at once with the Response in progress and no output yet:

```json
{
  "id": "resp_5f0c2a9e8b7d4c1fa3e6b2d9c8a7f104",
  "object": "response",
  "status": "in_progress",
  "conversation_id": null,
  "model": "gemini-3.8-flash",
  "output_text": "",
  "output_files": [],
  "sources": [],
  "message_id": null,
  "request_id": "3f9a1c0b7d2e"
}
```

With `"stream": true` as well, the call streams [SSE events](#stream-with-sse) live as usual, and the response keeps running if the connection drops.

- `conversation_id` is the one you sent, or `null` for a new conversation. A new conversation's ID arrives in the `conversation.created` event and in the finished Response.
- A conversation writes one background response at a time. Another background request with the same `conversation_id` returns `409 CONVERSATION_BUSY` (retryable) until the first one ends.
- An assistant runs a limited number of background responses at once (the `background_responses` limit in [Rate limits](/en/developers/errors-limits#rate-limits)). Past it, a background request returns `429 RATE_LIMITED` with `details.bucket` set to `background_responses`; retry when one of them ends.
- A retry with the same `Idempotency-Key` returns the same in-progress Response with `Idempotent-Replayed: true`, never a second run. It comes back as JSON even with `stream: true`; follow or poll it by `id`.

### Follow the stream [#follow-the-stream]

`GET /v1/responses/{response_id}?stream=true` · scope `chat:write`

```bash
curl -N "$ASSISTANT_API_URL/v1/responses/$RESPONSE_ID?external_user_id=$EXTERNAL_USER_ID&stream=true&starting_after=4" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
```

Replays the background response's events after `sequence` number `starting_after` (an integer from `0`, the default, which replays the whole stream), then follows live until the response ends. Sequence numbers are the same as in the original stream, so pass the last `sequence` you handled to resume without gaps or duplicates.

- Replay works while the response runs and for about 5 minutes after it ends. After that, and for a response that was not created with `background: true`, `stream=true` returns the saved Response as JSON instead, so check the `Content-Type`.
- Another end user's response returns `404 RESPONSE_NOT_FOUND`.
- If `starting_after` is already at or past the last event, the stream closes without sending anything.

A background stream ends with exactly one of these events:

| Event | Meaning |
| :--- | :--- |
| `response.completed` | The response finished. |
| `response.cancelled` | The response was stopped with [cancel](#cancel). |
| `error` | The response failed. If the server restarted mid-response, the code is `INTERNAL_SERVER_ERROR` with `retryable: true`; create the response again. |

### Poll [#poll]

Without `stream`, [Retrieve a response](#retrieve-a-response) returns `status: "in_progress"` while the background response runs, with `conversation_id` set to `null` and no output yet. Once it ends, the same call returns the saved Response. If the server stops before the response ends, it reads `incomplete` within about a minute. Poll every few seconds; each call counts against the `requests` rate-limit bucket.

### Cancel [#cancel]

`POST /v1/responses/{response_id}/cancel` · scope `chat:write`

```bash
curl "$ASSISTANT_API_URL/v1/responses/$RESPONSE_ID/cancel" \
  --request POST \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --header "Content-Type: application/json" \
  --data "{\"external_user_id\": \"$EXTERNAL_USER_ID\"}"
```

Stops a running background response and returns the Response as it stands. It may still read `in_progress` for a moment; once stopped it reads `cancelled`, and its stream ends with `response.cancelled`. Cancelling a finished response changes nothing and returns it. Another end user's response, an unknown ID, or a non-background response that is still running returns `404 RESPONSE_NOT_FOUND`.

## Upload a file [#upload-a-file]

`POST /v1/files` · scope `files:write` · `multipart/form-data`

```bash
curl "$ASSISTANT_API_URL/v1/files" \
  --request POST \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --form "external_user_id=$EXTERNAL_USER_ID" \
  --form "file=@./policy.pdf"
```

`201` response:

```json
{
  "id": "8d50c5c2-bf85-48a4-b252-8dc97410452c",
  "object": "file",
  "filename": "policy.pdf",
  "bytes": 182400,
  "mime_type": "application/pdf"
}
```

| Type | Formats | Max size |
| :--- | :--- | :--- |
| Images | PNG, JPEG, GIF, WebP, HEIC, HEIF | 10 MiB |
| Documents | PDF, DOCX, PPTX, XLSX, XLS, ODT, EPUB, RTF, CSV, TXT, MD, JSON, HTML, XML | 25 MiB |

- The type comes from the filename extension and must match the file's first bytes. A file with no extension falls back to its declared `Content-Type`. SVG is never accepted.
- HEIC and HEIF photos are stored as JPEG. Images longer than 8000 px on a side are scaled down. Images are stored without EXIF metadata (device, time, GPS position).
- Office, OpenDocument, and EPUB files may unpack to at most 200 MiB.
- File upload must be turned on for the assistant, or the call returns `403 FILE_UPLOAD_DISABLED`. The owner turns on **File Upload** in **Behavior → Features** in the Admin Panel.

Other errors: `415 UNSUPPORTED_FILE_TYPE` and `413 FILE_TOO_LARGE` (with the limit in `details.max_bytes`). Pass the returned `id` in `file_ids` for the same end user.

## Download a file [#download-a-file]

`GET /v1/files/{file_id}/content` · scope `conversations:read`

```bash
curl "$ASSISTANT_API_URL/v1/files/$FILE_ID/content?external_user_id=$EXTERNAL_USER_ID" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --output image.png
```

Returns the content of a file the end user uploaded or the assistant created for them: take the ID from `output_files` or a `response.file.created` event. `Content-Type` is the file's MIME type and `Content-Disposition` carries its name. Another end user's file, or an unknown ID, returns `404 FILE_NOT_FOUND`.

## Read a conversation [#read-a-conversation]

`GET /v1/conversations/{conversation_id}` · scope `conversations:read`

```bash
curl "$ASSISTANT_API_URL/v1/conversations/$CONVERSATION_ID?external_user_id=$EXTERNAL_USER_ID" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
```

```json
{
  "id": "a12d5e41-7ab7-4c8f-b024-c2c38b5c43f4",
  "object": "conversation",
  "created_at": "2026-10-20T08:30:00Z"
}
```

Returns `404 CONVERSATION_NOT_FOUND` when the conversation does not exist or belongs to another end user or assistant.

## List messages [#list-messages]

`GET /v1/conversations/{conversation_id}/messages` · scope `conversations:read`

```bash
curl "$ASSISTANT_API_URL/v1/conversations/$CONVERSATION_ID/messages?external_user_id=$EXTERNAL_USER_ID&limit=50" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
```

```json
{
  "object": "list",
  "data": [
    {
      "id": "c3e1a2b4-5d6f-4a7b-8c9d-0e1f2a3b4c5d",
      "object": "message",
      "role": "user",
      "content": "Summarize your return policy.",
      "sources": [],
      "created_at": "2026-10-20T08:30:00Z"
    },
    {
      "id": "b0f16c77-a275-46c8-9dc8-8fe9fd5991cc",
      "object": "message",
      "role": "assistant",
      "content": "Our return policy allows [1]...",
      "sources": [{ "n": 1, "kind": "pdf", "title": "Return policy.pdf", "url": null, "section": "Returns", "page": 2, "snippet": "Items can be returned within 30 days of delivery..." }],
      "created_at": "2026-10-20T08:30:04Z"
    }
  ],
  "has_more": true,
  "first_id": "c3e1a2b4-5d6f-4a7b-8c9d-0e1f2a3b4c5d",
  "last_id": "b0f16c77-a275-46c8-9dc8-8fe9fd5991cc"
}
```

- Messages are ordered oldest first. `limit` is 1–100 (default 50).
- While `has_more` is `true`, pass `last_id` as the `after` query parameter to get the next page.
- An `after` ID from another conversation returns `400 INVALID_CURSOR`.
- `content` holds the message text only; attachments are not listed.
- An assistant message lists the [sources](#citations) its `content` cites; other messages have an empty `sources`.

## Rate a message [#rate-a-message]

`PUT /v1/messages/{message_id}/feedback` · scope `feedback:write`

```bash
curl "$ASSISTANT_API_URL/v1/messages/$MESSAGE_ID/feedback" \
  --request PUT \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --header "Content-Type: application/json" \
  --data "{\"external_user_id\": \"$EXTERNAL_USER_ID\", \"rating\": \"down\", \"reason\": \"missing_info\", \"comment\": \"No price for the large size\"}"
```

`rating` is `up` or `down`. With `down` you may add `reason`, what went wrong: `incorrect`, `not_answered`, `missing_info`, `too_long`, `wanted_human` or `other`. `comment` (optional, up to 1,000 characters) holds the end user's own words, with either rating. Each call replaces the earlier rating, reason and comment. Success returns `204 No Content`; a message that is not this end user's returns `404 MESSAGE_NOT_FOUND`. Use the `message_id` from a response.

To remove the rating, send `DELETE` to the same path with `external_user_id` as a query parameter:

```bash
curl "$ASSISTANT_API_URL/v1/messages/$MESSAGE_ID/feedback?external_user_id=$EXTERNAL_USER_ID" \
  --request DELETE \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
```

It returns `204 No Content`, also when the message has no rating, and `404 MESSAGE_NOT_FOUND` for a message that is not this end user's.

## Erase an end user [#erase-an-end-user]

`DELETE /v1/users/{external_user_id}` · scope `users:delete`

```bash
curl "$ASSISTANT_API_URL/v1/users/$EXTERNAL_USER_ID" \
  --request DELETE \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
```

Permanently deletes the end user's conversations, messages, memories, uploaded files, and usage records for this assistant. It returns `204 No Content`, also for an ID that never existed, so you can safely retry it. The owner's billing records are not affected. Use it for account deletion and data-erasure requests.

<Cards>
<Card title="Errors and limits" description="All error codes, retries, and rate limits." href="/en/developers/errors-limits" />

<Card title="Voice API" description="Add speech with a WebSocket voice session." href="/en/developers/voice-api" />
</Cards>