Skip to content

AI Messages ​

Messages within a session. Sending a user message triggers an AI run that generates the assistant response.

Chat Flow Walkthrough ​

  1. Fetch existing messages for the session (GET /ai/sessions/:sessionId/messages) to display the conversation history or pagination cursor.
  2. Send a new user message (POST /ai/sessions/:sessionId/messages) and capture both the userMessage and the assistantMessage.runId.
  3. Stream the assistant output via GET /ai/sessions/:sessionId/messages/:messageId/stream (or the run stream) and append message.delta events to the UI as they arrive.
  4. If the user interrupts the assistant, call POST /ai/sessions/:sessionId/messages/:assistantMessageId/stop to finalize the partial content and show status: stopped.
  5. If the assistant pauses on a question card (clarification.required), render it and submit the answers or skip it. See AI Question Cards.

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

javascript
import { EventSource } from "eventsource";

const startChat = async (sessionId) => {
  const history = await fetch(
    `https://api.chainabit.com/api/v1/ai/sessions/${sessionId}/messages`,
    { headers: { Authorization: `Bearer ${TOKEN}` } }
  );
  console.log("Existing messages:", (await history.json()).data);

  const reply = await fetch(
    `https://api.chainabit.com/api/v1/ai/sessions/${sessionId}/messages`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ content: "Show me a recap of today's tasks." }),
    }
  );
  const {
    assistantMessage: { id: assistantId },
  } = (await reply.json()).data;

  const stream = new EventSource(
    `https://api.chainabit.com/api/v1/ai/sessions/${sessionId}/messages/${assistantId}/stream`,
    {
      fetch: (input, init) => fetch(input, {
        ...init,
        headers: { ...init.headers, Authorization: `Bearer ${TOKEN}` },
      }),
    },
  );
  stream.addEventListener("message.delta", (event) => {
    const { payload } = JSON.parse(event.data);
    console.log("Delta:", payload.delta);
  });
  ["run.settlement.completed", "run.failed", "run.error", "run.cancelled", "run.degraded"]
    .forEach((type) => stream.addEventListener(type, () => stream.close()));
};

Automatic recovery during provider interruptions ​

If a model times out or its provider is temporarily unavailable or rate limited, the conversation can continue on another eligible model. The account's provider permissions, model capabilities and execution budget still apply.

If every eligible route is unavailable, the task waits with its progress saved. Temporary provider interruptions are retried automatically. Completed tool results and the original objective remain available to the continuation, including conversations addressed to an agent. Execution limits and permanent refusals retain their own bounded recovery behavior.

The run.paused event carries status: "waiting_user" and recovery: { mode: "automatic", retryAt } for this automatic wait. retryAt is an ISO timestamp for the next scheduled attempt, not a guaranteed completion time. Message history exposes the same recovery object while the run is waiting, so a page reload can restore the waiting indicator. Human approval and clarification waits do not carry this automatic-recovery marker.

Display an automatic retry indicator instead of continuing to show stale thinking text. On run.resumed, follow resumeRunId and messageId to the continuation; the user does not need to submit another message. The continuation eventually produces its own final message and settlement events.

Long messages and model capacity ​

A message has no character limit of its own. Three limits apply instead, and each fails in a different place.

LimitCheckedWhat you see
Request body sizeBefore anything is created413 with payload_too_large in the standard error envelope. No message and no run exist. Shorten the text and send it again.
The context budget of the model route for your planWhen you send the message, before a run exists403 with prompt_context_limit_exceeded. The message Requested route exceeds the <n> token context budget gives the budget. Shorten the message.
The model's context windowAfter the message is accepted, when the run startsPOST succeeds as usual and returns the run. The run then moves to a model with a larger window, or fails with financial_execution_input_exceeds_capacity.

When the message is larger than the model's window ​

A message that was accepted can still be larger than the context window of the model chosen for it. The run is refused before any model is called, and the refused step is not charged. Work completed before the refusal is billed as usual.

  • You did not set model or provider. The run moves to a model your plan can use that has a larger context window, and carries on. The stream emits run.model.switched with reason: "financial_execution_input_exceeds_capacity", and you are billed for the replacement model as for any other run. If no such model is available, the run fails as below.
  • You set model or provider on the request. Your choice is kept, so the run fails. Send a shorter message, or leave the model unpinned.

A refused run is terminal. It ends with the stream event run.failed, which carries the code and the sizes behind it:

json
{
  "runId": "00000000-0000-4000-8000-000000000001",
  "messageId": "00000000-0000-4000-8000-000000000002",
  "code": "financial_execution_input_exceeds_capacity",
  "capacity": {
    "requiredInputTokens": 78464,
    "contextWindowTokens": 65536,
    "modelId": "00000000-0000-4000-8000-000000000003"
  }
}

code is the field to branch on. capacity appears only with this code: requiredInputTokens is a safe upper bound for the request in tokens, contextWindowTokens is the window of the model that was too small, and modelId names that model. Compare the two numbers to see how much shorter the message must be.

A client that reconnects after the stream closed reads the same outcome from the message list: the assistant message has status: "failed" and errorCode: "financial_execution_input_exceeds_capacity". Its content holds a short explanation for people; do not parse it.

Endpoints ​

MethodPathDescriptionAuth
GET/ai/sessions/:sessionId/messagesList messages (cursor/page paginated)JWT + Entitlement
POST/ai/sessions/:sessionId/messagesSend a message (triggers AI run)JWT + Entitlement
GET/ai/sessions/:sessionId/messages/:messageId/streamSSE message streamJWT + Entitlement
POST/ai/sessions/:sessionId/messages/:assistantMessageId/stopStop generationJWT + Entitlement
POST/ai/clarifications/:clarificationId/answerAnswer a question card (details)JWT + Entitlement
POST/ai/clarifications/:clarificationId/skipSkip a question card (details)JWT + Entitlement

GET /ai/sessions/:sessionId/messages ​

Description ​

List the newest messages first, in fixed pages of 10. Use meta.nextCursor to load older messages. A limit parameter does not change the page size.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

  • Headers: Authorization: Bearer <token>
  • Path params: sessionId
Query Parameters ​
ParameterTypeRequiredDescription
cursorstringNoMessage ID from meta.nextCursor; returns older messages
offsetnumberNoOffset for page-based pagination
pagenumberNoOne-based page fallback; ignored when cursor is set
chainyIdstring (uuid)NoFilter by Project. Returns 404 if the session is not associated with this Project.

Response ​

Response Example ​
json
{
  "data": [
    {
      "id": "cm5msg001",
      "role": "user",
      "content": "How can I improve my vocabulary retention rate?",
      "createdAt": "2026-03-17T10:05:00.000Z"
    },
    {
      "id": "cm5msg002",
      "role": "assistant",
      "content": "Spaced repetition is one of the most effective techniques...",
      "status": "completed",
      "toolCalls": [
        {
          "id": "tc_abc123",
          "toolKey": "memory.search",
          "input": { "query": "vocabulary retention" },
          "status": "completed",
          "output": { "total": 2 },
          "error": null,
          "executionMs": 64
        }
      ],
      "suggestions": [
        {
          "suggestion": "Can you turn that into a 7-day vocabulary executable workflow?",
          "priority": 1
        },
        {
          "suggestion": "What should I do when I keep forgetting the same words?",
          "priority": 2
        }
      ],
      "tokensUsed": 850,
      "createdAt": "2026-03-17T10:05:00.000Z"
    }
  ],
  "meta": {
    "limit": 10,
    "offset": 0,
    "page": 1,
    "hasMore": false,
    "hasNextPage": false
  }
}
Response Fields ​

meta.nextCursor, when present, is the message ID to pass as cursor for older messages. It is omitted on the last page. No total count is returned. With a cursor, offset and page are omitted. An empty history page currently returns 404 rather than an empty data array.

FieldTypeDescription
idstringMessage ID
rolestringuser or assistant
contentstring | nullMessage content (null while generating)
statusstringAssistant messages: running, completed, stopped, failed. A reply paused on a question card is waiting_user, and superseded once its card is answered and the conversation has continued in a new reply.
suggestionsobject[]Follow-up suggestion cards returned separately from the assistant markdown. Empty when disabled, unavailable, or not generated.
errorCodestringPresent only when status is failed: the typed reason, for example financial_execution_input_exceeds_capacity (see Long messages and model capacity). Branch on it, not on content.
runIdstring | nullID of the AI run that produced this message. Use this to attach a stream listener on page reload. Present on all assistant messages once the run is created.
clarificationsobject[]Question cards the assistant asked in this message, with their answers once given. Empty when there are none. See AI Question Cards.
toolCallsobject[] | nullFor Chao sessions: list of tool calls made during this message. See Tool Call Fields below.
modelIdstring | nullID of the model that generated the response
modelNamestring | nullDisplay name of the model
providerKeystring | nullProvider identifier (e.g. "anthropic", "openai")
createdAtstringISO 8601
Tool Call Fields ​

Each entry in toolCalls represents one tool invoked by Chao during this message:

FieldTypeDescription
idstringTool call ID (matches SSE callId, toolCallId, or stepId)
toolKeystringTool name (e.g. "bits.create", "chainies.list")
inputobjectArguments Chao passed to the tool
statusstringpending, executing, completed, failed, degraded, rejected, or skipped
outputobject | nullTool result (present when status is completed)
errorstring | nullError message (present when status is failed)
executionMsnumber | nullExecution duration in milliseconds

toolCalls is persisted and returned on every history request. On page reload, reconstruct tool cards from this field and re-attach a stream listener when the assistant message still has an active runId.

Normalize live SSE payloads into the same card shape:

Normalized fieldPreferred lookup
toolKeypayload.toolKey ?? payload.key
callIdpayload.callId ?? payload.toolCallId ?? envelope.stepId
inputpayload.input ?? payload.args
outputpayload.data ?? payload.output

When payload.activity exists, render card title, detail, status, and subject from that object.

Code Examples ​

Use the id from Create a Session's response (data.id) as $SESSION_ID. For the Project filter, use the id from Create Project as $CHAINY_ID.

curl "https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages" \
  -H "Authorization: Bearer $TOKEN"

POST /ai/sessions/:sessionId/messages ​

Description ​

Send a user message to a session, which triggers an AI run to generate the assistant response.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

  • Headers: Authorization: Bearer <token>, Content-Type: application/json
  • Path params: sessionId
Request Body ​
FieldTypeRequiredConstraintsDescription
contentstringYesNon-emptyMessage content. There is no character limit of its own: the request body size limit bounds the request, and the model's context budget bounds what a run can read. See Long messages and model capacity. This applies to every caller, including the seed message returned by feature endpoints such as POST /productivity/priority-analysis/runs.
modelstringNoActive model keyOverride the model for this message
effortModestringNo"basic", "thinking", or "pro"High-level model tier preference. basic uses a standard model, thinking selects a thinking-capable model, pro selects the highest-capability tier. Overrides the session-level effortMode if both are set. Exact model selection remains a backend hint.
providerstringNoLowercase identifier (e.g. openai)AI provider key. Requires a paid plan with the corresponding provider entitlement.
capabilityKeystringNoai.search.web, ai.research.deep, ai.image.generate, ai.video.generate, ai.audio.generateExplicit Chao capability to execute deterministically. When set, the matching capability-specific parameters are accepted (see Capability Parameters).
attachmentIdsstring[]NoValid file IDs (UUID v4)Array of file IDs to attach
memoryIdsstring[]NoValid memory IDs (UUID v4)Optional memory items to pin into the run
idempotencyKeystringNo—Client-side dedupe key for retries
parametersobjectNoCapability-specific paramsLong-term contract for capability-specific parameters. See Capability Parameters.
structuredBlocksobject[]NoMention/media blocksStructured user-side blocks such as agent mentions or media references
renderCapabilityobjectNo{ surface, renders }What your client can draw. Include "question_form" in renders to let the assistant ask choice questions as cards. See AI Question Cards.

Capability-specific fields (such as durationSeconds, aspectRatio, generateAudio, etc.) may also be sent at the top level for backward compatibility. See the section below.

Capability Parameters ​

When capabilityKey is set, the message endpoint accepts the parameters that capability declares. Two equivalent request shapes are supported:

  1. Top-level fields (current client compatibility):
    json
    {
      "content": "lo-fi beat with a deep bass line",
      "capabilityKey": "ai.audio.generate",
      "durationSeconds": 20,
      "bpm": 90,
      "styleTokens": ["lo-fi", "chill"]
    }
  2. Nested parameters object (long-term contract, recommended for new code):
    json
    {
      "content": "lo-fi beat with a deep bass line",
      "capabilityKey": "ai.audio.generate",
      "parameters": {
        "durationSeconds": 20,
        "bpm": 90,
        "styleTokens": ["lo-fi", "chill"]
      }
    }
    When both forms are present, nested values win on collision.

Accepted parameters per capability:

capabilityKeyAccepted parameters
ai.audio.generatedurationSeconds (5–30), bpm (40–220), styleTokens (string[], ≤16 items, ≤64 chars each). See Audio Generation.
ai.image.generateaspectRatio (W:H), quality (standard|hd|auto), numImages / numberOfImages (alias for count, 1–4), seed (int), negativePrompt (≤4000 chars), size (1024x1024|1792x1024|1024x1792), style (vivid|natural), resolution, provider, model, activeImageId. See Generative Media.
ai.video.generateaspectRatio (16:9|9:16|1:1|4:3|3:4|21:9), duration (1–60, accepts numeric strings), resolution (480p|720p|1080p|4k), size (WxH), generateAudio (boolean), negativePrompt, seed (int), styleTokens, inputImageUrl, inputVideoUrl, referenceImages[], referenceVideos[], provider (kling|veo|sora), model. See Video Generation.
ai.search.webmaxResults (1–20)
ai.research.deepdepth (standard|deep)

Capability fields belonging to a different capability than the one selected are rejected with a precise error (bpm is only valid for ai.audio.generate). Truly unknown fields are also rejected with unknown property X. Plain chat (no capabilityKey) keeps the original DTO contract — extra fields are still rejected.

Response ​

Response Example ​
json
{
  "data": {
    "sessionId": "$SESSION_ID",
    "userMessage": {
      "id": "cm5msg001",
      "role": "user",
      "content": "How can I improve my vocabulary retention rate? I keep forgetting words after a few days.",
      "createdAt": "2026-03-17T10:05:00.000Z"
    },
    "assistantMessage": {
      "id": "cm5msg002",
      "role": "assistant",
      "content": "",
      "suggestions": [],
      "createdAt": "2026-03-17T10:05:00.000Z"
    },
    "run": {
      "id": "cm5run003",
      "status": "queued"
    }
  }
}

The assistant message shell is returned immediately with suggestions: []. Suggestions are generated together with the assistant reply and are delivered via history reads and the message.suggestions SSE event in the same tick as message.completed.

Response Fields ​
FieldTypeDescription
userMessage.idstringUser message ID
userMessage.rolestringAlways user
userMessage.contentstringMessage content
userMessage.createdAtstringISO 8601
assistantMessage.idstringAssistant message ID
assistantMessage.rolestringAlways assistant
assistantMessage.contentstringEmpty string while generating
assistantMessage.suggestionsobject[]Always [] in the immediate POST response shell
run.idstringAssociated AI run ID
run.statusstringInitial run status, usually queued
Pending question card ​

While the assistant is waiting for an answer to a question card, the session accepts no new message. The request is refused with 409 and clarification_answer_required, and error.details names the clarificationId and runId to answer, skip or stop. See AI Question Cards.

Error Example ​
json
{
  "error": {
    "code": "bad_request",
    "message": "bpm is only valid for ai.audio.generate; unknown property foo",
    "details": {
      "fields": [
        { "field": "bpm", "message": "bpm is only valid for ai.audio.generate", "capabilityKey": "ai.audio.generate" },
        { "field": "foo", "message": "unknown property foo" }
      ]
    }
  },
  "meta": { "requestId": "<request-id>" }
}

Code Examples ​

Use the id from Create a Session's response (data.id) as $SESSION_ID.

curl -X POST https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "How can I improve my vocabulary retention rate? I keep forgetting words after a few days."
  }'

GET /ai/sessions/:sessionId/messages/:messageId/stream ​

Description ​

Connect to a Server-Sent Events stream to receive incremental content as an assistant message is generated.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

  • Headers: Authorization: Bearer <token>, Accept: text/event-stream
  • Path params: sessionId, messageId
Query Parameters ​
ParameterTypeRequiredDescription
parkstringNoSet to 1 to let the server close the connection while the reply waits on a question card. The stream then ends with a stream.parked event that says when to connect again. Without it the connection stays open while the card is pending. See Waiting without an open connection.

Response ​

Response Example ​
event: message.delta
data: {"eventId":1,"type":"message.delta","runId":"cm5run003","payload":{"delta":"Spaced repetition is one of the most "}}

event: message.delta
data: {"eventId":2,"type":"message.delta","runId":"cm5run003","payload":{"delta":"effective techniques for long-term retention. "}}

event: message.delta
data: {"eventId":3,"type":"message.delta","runId":"cm5run003","payload":{"delta":"Here are some strategies tailored to your chain..."}}

event: message.completed
data: {"eventId":4,"type":"message.completed","runId":"cm5run003","payload":{"messageId":"cm5msg002","content":"Spaced repetition is one of the most effective techniques for long-term retention. Here are some strategies tailored to your chain..."}}
Response Fields ​
FieldTypeDescription
eventstringSSE event type such as message.delta, message.completed, tool.started, tool.completed, run.error
data.payload.deltastringIncremental content token(s) for message.delta
data.payload.contentstringFull assistant content for message.completed
data.payload.messageIdstringAssistant message ID when present

Code Examples ​

Use $SESSION_ID from Create a Session's response (data.id), and use the id from Send a Message's response (data.assistantMessage.id) as $MESSAGE_ID.

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"

POST /ai/sessions/:sessionId/messages/:assistantMessageId/stop ​

Description ​

Stop an in-progress assistant message generation.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

  • Headers: Authorization: Bearer <token>
  • Path params: sessionId, assistantMessageId

Response ​

Response Example ​
json
{
  "data": {
    "id": "cm5msg002",
    "status": "stopped",
    "content": "Spaced repetition is one of the most effective techniques for long-term retention. ",
    "stoppedAt": "2026-03-17T10:05:05.000Z"
  }
}
Response Fields ​
FieldTypeDescription
idstringMessage ID
statusstringAlways stopped
contentstringPartial content generated before stopping
stoppedAtstringISO 8601 timestamp of stop

Code Examples ​

Use $SESSION_ID from Create a Session's response (data.id), and use the id from Send a Message's response (data.assistantMessage.id) as $ASSISTANT_MESSAGE_ID.

curl -X POST https://api.chainabit.com/api/v1/ai/sessions/$SESSION_ID/messages/$ASSISTANT_MESSAGE_ID/stop \
  -H "Authorization: Bearer $TOKEN"

Built with purpose. chainabit.com