Skip to content

How to Stream AI Responses ​

Chainabit streams AI work through Server-Sent Events (SSE). Use the stream to append assistant text, render Chao tool cards, handle approval prompts, and detect terminal run states.

Set up authentication and the shared environment in Prerequisites.

Streaming Endpoints ​

EndpointPurpose
GET /ai/sessions/:sessionId/messages/:messageId/streamStream a conversation response
GET /ai/runs/:runId/streamStream an AI feature run

Both endpoints use the same event envelope.

Create a Session and Send a Message ​

SESSION=$(curl -s -X POST "https://api.chainabit.com/api/v1/ai/sessions" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title": "Planning session", "assistantType": "chao"}')

SESSION_ID=$(echo "$SESSION" | jq -r '.data.id')

MESSAGE=$(curl -s -X POST "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"content": "Help me plan my week"}')

MESSAGE_ID=$(echo "$MESSAGE" | jq -r '.data.assistantMessage.id')
RUN_ID=$(echo "$MESSAGE" | jq -r '.data.run.id')

Connect to the Stream ​

The JavaScript example uses eventsource v4 (npm install eventsource@4).

Tip: The message POST response contains data.assistantMessage.id and data.run.id. Use the assistant message ID for the message stream, or the run ID for the run stream.

curl -N "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages/$MESSAGE_ID/stream" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Accept: text/event-stream"

Event Format ​

The connection begins with a preamble containing the reconnection interval. Subsequent event frames carry an ID, event type, and data:

retry: 3000
event: stream.connected
data: {"runId":"..."}

id: 1
event: message.delta
data: {"eventId":1,"type":"message.delta","runId":"...","timestamp":"...","payload":{"delta":"Here is"}}

Common events:

EventDescription
run.startedInference has begun. Show an active indicator.
run.status.changedA run status transition. Read payload.status; do not assume every transition is successful completion.
message.deltaAppend payload.delta to the assistant text
message.completedFull assistant content is available in payload.content
run.heartbeatThe assistant is between steps in a multi-tool run. payload.reason is 'planning_next_step' (reviewing tool results, deciding next action) or 'continuation' (response was truncated, requesting continuation). payload.activity.detail contains a user-safe description — use it to show a status card or thinking indicator.
tool.started / tool.progress / tool.completedRender or update a tool card. payload.activity.label (e.g. "Web Search") and payload.activity.detail are safe to show users.
tool.failedMark a tool card failed; the run may still continue
tool.degradedRender a graceful fallback state
tool.approval_requiredShow approve/reject controls
run.thinking.startedExtended reasoning phase began. Show a thinking indicator using payload.activity.label.
run.thinking.completedExtended reasoning phase ended. Hide the thinking indicator.
plan.step_addedAdd a planned action card
capability.resolvedShow selected capability/tool route when useful
cot.stepAn eligible, policy-approved visible-reasoning summary. Follow the disclosure contract in Visible reasoning.
message.partially_completedThe assistant produced partial content
run.failed / run.errorTerminal error. payload.error contains a machine-readable error key.
run.settlement.completedTerminal settlement; inspect the run's actual outcome rather than inferring success from a closed connection.

Visible reasoning ​

An eligible session can provide short, policy-approved reasoning summaries. Render a summary only when it carries disclosure: "visible_reasoning_v1". These summaries help explain the work without exposing raw private reasoning. The visible-reasoning reference owns the exact event contract.

Extended thinking events ​

The public stream can report run.thinking.started and run.thinking.completed for eligible sessions. Use these lifecycle events for an application-owned progress indicator. Do not expect raw message.thinking.delta events or reconstruct reasoning from provider payloads; those deltas are not public stream content.

Approval Buttons ​

When you receive tool.approval_required, submit the decision with the toolCallId from the event. The approve request must include the digest and nonce from payload.approval, and the approval window is 120 seconds by default. See Approval Gates for the request body, the typed refusal codes (approval_expired, approval_digest_mismatch and others) and the preview to render.

Reconnection ​

If the connection drops before a terminal event, reconnect to the same stream. When your client can set headers, pass Last-Event-ID with the latest received SSE id:

curl -N "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages/$MESSAGE_ID/stream" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Last-Event-ID: $LAST_EVENT_ID"

Keep the latest actual event ID as LAST_EVENT_ID; do not substitute the message or run UUID. See reconnection details.

After page reload, fetch message history and rebuild tool cards from message.toolCalls. Then reconnect to the stream if the assistant message still has an active runId.

Tips ​

  • Use curl -N or --no-buffer while testing.
  • Listen to named events with addEventListener; do not rely only on the default message event.
  • Render eligible cot.* summaries only when they carry the approved disclosure marker. Never reconstruct reasoning from raw provider text or tool arguments.
  • Do not close the run on tool.failed, message.completed, or message.partially_completed. Wait for a terminal run event such as run.failed, run.error, run.cancelled, run.degraded.completed, or run.settlement.completed.

Built with purpose. chainabit.com