Skip to Content
Assistant Core

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. Each endpoint needs the scope shown next to it.

Create a response

POST /v1/responses ยท scope chat:write

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\"]
  }"
FieldRequiredMeaning and limits
external_user_idYes1โ€“256 characters; your stable ID for the end user.
inputYes1โ€“100,000 characters.
conversation_idNoUUID of a conversation owned by the same end user. Omit it to start a new conversation.
file_idsNoUp to 10 file IDs uploaded for the same end user.
modelNoAn 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.
streamNofalse (default) returns JSON; true returns an SSE stream.
backgroundNotrue runs the response apart from the request, so it goes on if the client disconnects. false by default. See Background responses.

Unknown fields are rejected with 422 VALIDATION_ERROR.

A non-streaming call returns 200 with a Response object:

{
  "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 codeCause
404 CONVERSATION_NOT_FOUNDconversation_id does not belong to this end user and assistant.
404 FILE_NOT_FOUNDA file ID was not uploaded by this end user; details.file_id names it.
400 MODEL_NOT_FOUNDmodel is not an active chat model; details.model repeats it.
409 CONVERSATION_BUSYA background response is still being written in this conversation (background requests only); retry when it ends.
402 INSUFFICIENT_CREDITSThe assistant owner is out of credits.
400 CONTEXT_TOO_LARGEThe conversation no longer fits the model; start a new one.
503 UPSTREAM_UNAVAILABLEThe model provider failed or ended early; retry with backoff.

Stream with SSE

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

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:

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

EventExtra fields
response.createdstatus: "in_progress"
conversation.createdconversation_id (only when the request started a new conversation)
response.output_text.deltadelta: the next piece of answer text
response.reasoning.deltadelta: reasoning text, when the model exposes it
response.tool_call.startedtool_call_id (call_โ€ฆ), name
response.tool_call.completedtool_call_id, status (completed or failed), duration_ms
response.file.createdfile: { id, name, mime_type, bytes } for a file the assistant created; download it with GET /v1/files/{id}/content
response.completedmessage_id, finish_reason, sources (see Citations)
response.cancelledNone. Ends a background response stopped with cancel.
errorcode, message, details, request_id, retryable (same as REST errors)

finish_reason is one of:

ValueMeaning
stopThe model finished its answer.
lengthThe answer hit the model's output limit and may be cut off.
refusalThe model declined to answer.
tool_limitThe 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

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 for how approval rules work.

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

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:

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
}

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

Idempotency and retries

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

SituationResult
Same key and body, first request still running409 REQUEST_IN_PROGRESS (retryable). Wait and retry.
Same key, different body409 IDEMPOTENCY_CONFLICT. Use a new key.
Same key and body, first request completed200 with the stored result and Idempotent-Replayed: true. The model is not called again.
Same key and body, first request was a background response200 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 disconnectedThe 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

GET /v1/responses/{response_id} ยท scope chat:write

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). A background response reads in_progress while it runs (see Poll); add stream=true to follow its 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.

statusMeaning
in_progressA background response is still running.
completedThe response finished.
failedThe response ended with an error.
incompleteThe response ended early: a non-background stream lost its client, or the server stopped mid-response.
cancelledA background response was stopped with cancel.

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.

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:

{
  "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 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). 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

GET /v1/responses/{response_id}?stream=true ยท scope chat:write

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:

EventMeaning
response.completedThe response finished.
response.cancelledThe response was stopped with cancel.
errorThe response failed. If the server restarted mid-response, the code is INTERNAL_SERVER_ERROR with retryable: true; create the response again.

Poll

Without stream, 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

POST /v1/responses/{response_id}/cancel ยท scope chat:write

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

POST /v1/files ยท scope files:write ยท multipart/form-data

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:

{
  "id": "8d50c5c2-bf85-48a4-b252-8dc97410452c",
  "object": "file",
  "filename": "policy.pdf",
  "bytes": 182400,
  "mime_type": "application/pdf"
}
TypeFormatsMax size
ImagesPNG, JPEG, GIF, WebP, HEIC, HEIF10 MiB
DocumentsPDF, DOCX, PPTX, XLSX, XLS, ODT, EPUB, RTF, CSV, TXT, MD, JSON, HTML, XML25 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

GET /v1/files/{file_id}/content ยท scope conversations:read

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

GET /v1/conversations/{conversation_id} ยท scope conversations:read

curl "$ASSISTANT_API_URL/v1/conversations/$CONVERSATION_ID?external_user_id=$EXTERNAL_USER_ID" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
{
  "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

GET /v1/conversations/{conversation_id}/messages ยท scope conversations:read

curl "$ASSISTANT_API_URL/v1/conversations/$CONVERSATION_ID/messages?external_user_id=$EXTERNAL_USER_ID&limit=50" \
  --header "Authorization: Bearer $ASSISTANT_API_KEY"
{
  "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 its content cites; other messages have an empty sources.

Rate a message

PUT /v1/messages/{message_id}/feedback ยท scope feedback:write

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:

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

DELETE /v1/users/{external_user_id} ยท scope users:delete

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.

Last updated on