Skip to content

AI Runs ​

AI features are predefined capabilities (e.g., summarization, analysis, coaching). Each invocation creates a run that tracks execution through steps.

Contract update (2026-04): The POST request body was corrected to match the live API. The input object, agentId, and workspaceId fields are not accepted. Use the messages array instead.

Identifiers in response examples are synthetic UUIDs. Use the IDs returned by your requests.

Run Orchestration Walkthrough ​

  1. List the catalog (GET /ai/features) to discover available feature keys.
  2. Create a run (POST /ai/features/:featureKey/runs) with a messages array containing the user prompt.
  3. Watch the run status via GET /ai/runs/:runId or GET /ai/runs/:runId/steps, and stream the final response and settlement through GET /ai/runs/:runId/stream.
  4. Cancel (POST /ai/runs/:runId/cancel) or retry (POST /ai/runs/:runId/retry) when a run stalls, then capture the final result field once the run completes.
javascript
const orchestrateFeature = async () => {
  const featureRes = await fetch(`https://api.chainabit.com/api/v1/ai/features`, {
    headers: { Authorization: `Bearer ${TOKEN}` },
  });
  if (!featureRes.ok) throw new Error(`Feature catalog request failed: ${featureRes.status}`);
  const feature = (await featureRes.json()).find(
    (f) => f.key === "ai.chat.multi_agent" && f.isActive && f.isVisibleOnPlan
  );
  if (!feature) throw new Error("The selected AI feature is unavailable on this account");

  const idempotencyKey = crypto.randomUUID(); // Reuse this key only for retries of this request.
  const runRes = await fetch(
    `https://api.chainabit.com/api/v1/ai/features/${feature.key}/runs`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${TOKEN}`,
        "Content-Type": "application/json",
        "Idempotency-Key": idempotencyKey,
      },
      body: JSON.stringify({
        messages: [
          { role: "user", content: "Help me maintain my daily vocabulary completion history" }
        ],
      }),
    }
  );
  if (!runRes.ok) throw new Error(`Run creation failed: ${runRes.status}`);
  const { runId } = await runRes.json();
  if (!runId) throw new Error("Run ID missing from response");
  const streamController = new AbortController(); // Call abort() to stop viewing.
  const streamRes = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${runId}/stream`, {
    signal: AbortSignal.any([streamController.signal, AbortSignal.timeout(60_000)]),
    headers: { Authorization: `Bearer ${TOKEN}`, Accept: "text/event-stream" },
  });
  if (!streamRes.ok || !streamRes.body) throw new Error("Could not open run stream");
  const reader = streamRes.body.getReader();
  const decoder = new TextDecoder();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      console.log(decoder.decode(value, { stream: true })); // raw SSE frames
    }
  } finally {
    try { await reader.cancel(); } finally { reader.releaseLock(); }
  }
};

Endpoints ​

MethodPathDescriptionAuth
GET/ai/featuresList AI feature catalogJWT + Entitlement
POST/ai/features/:featureKey/runsCreate a run for a featureJWT + Entitlement
GET/ai/runsList runs (filterable)JWT + Entitlement
GET/ai/runs/:runIdGet a runJWT + Entitlement
GET/ai/runs/:runId/stepsList steps of a runJWT + Entitlement
GET/ai/runs/:runId/streamSSE stream for a runJWT + Entitlement
POST/ai/runs/:runId/cancelCancel a running runJWT + Entitlement
POST/ai/runs/:runId/retryCreate a new run from an existing feature runJWT + Entitlement
POST/ai/runs/:runId/resumeResume a recoverable interrupted runJWT + Entitlement

GET /ai/features ​

List all available AI features in the catalog.

Authentication: JWT Bearer token required.

Request ​

No path or query parameters. No request body.

Response ​

Response Example ​
json
[
  {
    "key": "ai.chat.multi_agent",
    "aliases": [],
    "isActive": true,
    "isVisibleOnPlan": true
  }
]
Response Fields ​
FieldTypeDescription
keystringFeature identifier
aliasesstring[]Alias names; the current catalog returns an empty list
isActivebooleanWhether the feature is active
isVisibleOnPlanbooleanWhether the caller's plan exposes the feature

Code Examples ​

javascript
const res = await fetch(`https://api.chainabit.com/api/v1/ai/features`, {
  headers: { Authorization: `Bearer ${TOKEN}` },
});
const features = await res.json();
python
import requests

res = requests.get(
    f"{BASE_URL}/ai/features",
    headers={"Authorization": f"Bearer {TOKEN}"},
)
features = res.json()

POST /ai/runs/:runId/resume ​

Resume a run that stopped in a recoverable state. The request has no body.

A successful request returns 200 OK with the run id, its new status, and a replayed boolean. The API returns 403 when the run is outside the caller's permitted scope and 409 conversation_run_not_resumable when the run is not in a recoverable state.


POST /ai/features/:featureKey/runs ​

Create a new run for the specified AI feature. An active subscription or eligible purchased credits, plus access to the feature, is required.

Authentication: JWT Bearer token + active AI entitlement required.

Funding required. Entitlement and available credits do not by themselves authorize inference. Billable work is paused until its funding and maximum cost can be verified. An accepted asynchronous run can subsequently finish as failed; check its terminal status before reporting success. Repeated requests do not resolve a funding pause.

Request ​

FieldTypeRequiredConstraintsDescription
messagesarrayYes1–50 itemsConversation messages to send
messages[].rolestringYes"user"Role of the message author
messages[].contentstringYesNon-emptyMessage content
temperaturenumberNo0–2Sampling temperature
maxOutputTokensnumberNo1–200,000Maximum tokens in the response
providerstringNoProvider keyProvider selection, subject to plan access
effortModestringNobasic, thinking, proModel selection effort tier

Send a unique Idempotency-Key header for each logical create request. Reuse that key only when retrying the same HTTP request. The header is required; a body field does not replace it. Missing the header returns 428 missing_idempotency_key.

Response ​

Response Example ​
json
{
  "requestId": "00000000-0000-4000-8000-000000000002",
  "runId": "00000000-0000-4000-8000-000000000001",
  "result": { "finishReason": "running", "text": "" }
}
Response Fields ​
FieldTypeDescription
requestIdstringRequest identifier
runIdstring (optional)New run ID, when a run was created
resultobjectExecution result; an accepted asynchronous run can report finishReason: "running"

Code Examples ​

javascript
const idempotencyKey = crypto.randomUUID(); // Keep this key when retrying the same request.
const res = await fetch(`https://api.chainabit.com/api/v1/ai/features/ai.chat.multi_agent/runs`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${TOKEN}`,
    "Content-Type": "application/json",
    "Idempotency-Key": idempotencyKey,
  },
  body: JSON.stringify({
    messages: [
      {
        role: "user",
        content: "I have been struggling to maintain my daily vocabulary practice completion history",
      },
    ],
  }),
});
const { requestId, runId, result } = await res.json();
python
import requests
import uuid

idempotency_key = str(uuid.uuid4())  # Keep for retries of this request.
res = requests.post(
    f"{BASE_URL}/ai/features/ai.chat.multi_agent/runs",
    headers={
        "Authorization": f"Bearer {TOKEN}",
        "Content-Type": "application/json",
        "Idempotency-Key": idempotency_key,
    },
    json={
        "messages": [
            {
                "role": "user",
                "content": "I have been struggling to maintain my daily vocabulary practice completion history",
            }
        ]
    },
)
result = res.json()  # requestId, optional runId, result

GET /ai/runs ​

List all runs, with optional filters.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

ParameterTypeRequiredDescription
agentIdstringNoFilter by agent
workspaceIdstringNoFilter by workspace
featureKeystringNoFilter by feature
statusstringNoFilter by status: queued, running, completed, failed, cancelled
limitnumberNoItems per page
offsetnumberNoPagination offset

Response ​

Response Example ​
json
{
  "data": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "featureKey": "ai.chat.multi_agent",
      "status": "completed",
      "startedAt": "2026-03-17T10:00:00.000Z",
      "finishedAt": "2026-03-17T10:00:12.000Z"
    }
  ],
  "meta": {
    "total": 1,
    "limit": 10,
    "offset": 0
  }
}
Response Fields ​
FieldTypeDescription
idstringRun ID
featureKeystringFeature that triggered the run
statusstringqueued, running, completed, failed, cancelled
startedAtstringISO 8601
finishedAtstring | nullISO 8601 or null

Code Examples ​

javascript
const params = new URLSearchParams({
  featureKey: "ai.chat.multi_agent",
  status: "completed",
  limit: "10",
});
const res = await fetch(`https://api.chainabit.com/api/v1/ai/runs?${params}`, {
  headers: { Authorization: `Bearer ${TOKEN}` },
});
const { data, meta } = await res.json();
python
import requests

res = requests.get(
    f"{BASE_URL}/ai/runs",
    headers={"Authorization": f"Bearer {TOKEN}"},
    params={"featureKey": "ai.chat.multi_agent", "status": "completed", "limit": 10},
)
body = res.json()

GET /ai/runs/:runId ​

Get details of a single run.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

Use runId from the Create a Run response as $RUN_ID.

Response ​

Response Example ​
json
{
  "id": "00000000-0000-4000-8000-000000000001",
  "featureKey": "ai.chat.multi_agent",
  "status": "completed",
  "result": {
    "text": "The response is complete."
  },
  "startedAt": "2026-03-17T10:00:00.000Z",
  "finishedAt": "2026-03-17T10:00:12.000Z",
  "createdAt": "2026-03-17T10:00:00.000Z"
}
Response Fields ​
FieldTypeDescription
idstringRun ID
featureKeystringFeature that triggered the run
statusstringqueued, running, completed, failed, cancelled
resultunknownPublic run result; access may be restricted
startedAtstring | nullISO 8601
finishedAtstring | nullISO 8601 or null
createdAtstringISO 8601

Code Examples ​

javascript
const runId = process.env.RUN_ID; // id of the run to fetch

const res = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${runId}`, {
  headers: { Authorization: `Bearer ${TOKEN}` },
});
const run = await res.json();
python
import os
import requests

run_id = os.environ["RUN_ID"]  # id of the run to fetch

res = requests.get(
    f"{BASE_URL}/ai/runs/{run_id}",
    headers={"Authorization": f"Bearer {TOKEN}"},
)
run = res.json()

GET /ai/runs/:runId/steps ​

List all steps executed within a run.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

Use runId from the Create a Run response as $RUN_ID.

Response ​

Response Example ​
json
[
  {
    "id": "00000000-0000-4000-8000-000000000003",
    "stepIndex": 0,
    "stepType": "llm_call",
    "tokensUsed": 1250,
    "durationMs": 3400,
    "createdAt": "2026-03-17T10:00:01.000Z"
  }
]
Response Fields ​
FieldTypeDescription
idstringStep ID
stepIndexnumberStep order within the run
stepTypestringStep type (e.g. llm_call)
tokensUsednumber (optional)Token usage
durationMsnumber (optional)Duration in milliseconds
createdAtstringISO 8601
contentRedactedboolean (optional)True when the caller cannot access step content

Code Examples ​

javascript
const runId = process.env.RUN_ID; // id of the run to list steps for

const res = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${runId}/steps`, {
  headers: { Authorization: `Bearer ${TOKEN}` },
});
const steps = await res.json();
python
import os
import requests

run_id = os.environ["RUN_ID"]  # id of the run to list steps for

res = requests.get(
    f"{BASE_URL}/ai/runs/{run_id}/steps",
    headers={"Authorization": f"Bearer {TOKEN}"},
)
steps = res.json()

GET /ai/runs/:runId/stream ​

Connect to a Server-Sent Events stream to receive real-time updates as a run executes.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

Use runId from the Create a Run response as $RUN_ID.

Response ​

Response Example ​

Feature runs send the completed response with message.completed, followed by the terminal run.settlement.completed event.

event: message.completed
data: {"eventId":1,"type":"message.completed","runId":"00000000-0000-4000-8000-000000000001","timestamp":"...","payload":{"content":"Based on your completion history data, I recommend starting with smaller goals.","deliveryState":"committed"}}

event: run.settlement.completed
data: {"eventId":2,"type":"run.settlement.completed","runId":"00000000-0000-4000-8000-000000000001","timestamp":"...","payload":{"status":"completed"}}
Response Fields ​
FieldTypeDescription
eventIdnumberMonotonically increasing event counter for this run
typestringSSE event type — see SSE Streaming reference for the full catalog
runIdstringRun UUID
timestampstringISO 8601 event timestamp
payloadobjectEvent-specific data (e.g. { content } for message.completed)

Code Examples ​

javascript
// Node.js: npm install eventsource@4
import { EventSource } from 'eventsource';

const runId = process.env.RUN_ID; // id of the run to stream

const es = new EventSource(
  `https://api.chainabit.com/api/v1/ai/runs/${runId}/stream`,
  {
    fetch: (input, init) => fetch(input, {
      ...init,
      headers: { ...init.headers, Authorization: `Bearer ${TOKEN}` },
    }),
  }
);

es.addEventListener('message.completed', (e) => {
  const { payload } = JSON.parse(e.data);
  process.stdout.write(payload.content);
});

es.addEventListener('run.settlement.completed', () => es.close());
es.addEventListener('run.failed', (e) => {
  console.error('Run failed:', JSON.parse(e.data));
  es.close();
});
['run.error', 'run.cancelled', 'run.degraded']
  .forEach((type) => es.addEventListener(type, () => es.close()));
python
import os
import sseclient
import requests
import json

run_id = os.environ["RUN_ID"]  # id of the run to stream

with requests.get(
    f"{BASE_URL}/ai/runs/{run_id}/stream",
    headers={
        "Authorization": f"Bearer {TOKEN}",
        "Accept": "text/event-stream",
    },
    stream=True,
) as response:
    response.raise_for_status()
    client = sseclient.SSEClient(response)
    for event in client.events():
        if event.event == "message.completed":
            data = json.loads(event.data)
            print(data["payload"]["content"], end="", flush=True)
        elif event.event in {"run.settlement.completed", "run.failed", "run.error", "run.cancelled", "run.degraded"}:
            break

POST /ai/runs/:runId/cancel ​

Cancel a currently running run.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

Use runId from the Create a Run response as $RUN_ID.

Response ​

Response Example ​
json
{
  "cancelled": true
}
Response Fields ​
FieldTypeDescription
cancelledbooleantrue if the run was cancelled; false if you may not cancel the run or it has already finished

Who can cancel. Account owners and admins can cancel any run in the workspace the request acts in; other members can cancel only runs they started. A member who has been removed from the account or suspended cannot cancel any run there, including runs they started. A runId that does not exist, or a run in another account or workspace that you did not start, is refused with 403. Every other refusal returns { "cancelled": false } — the same answer as for a run that has already finished — so the response does not reveal which case applied. Cancellation is best-effort; tokens already streamed are not retracted and may still be billed.

Code Examples ​

javascript
const runId = process.env.RUN_ID; // id of the run to cancel

const res = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${runId}/cancel`, {
  method: "POST",
  headers: { Authorization: `Bearer ${TOKEN}` },
});
const cancellation = await res.json();
python
import os
import requests

run_id = os.environ["RUN_ID"]  # id of the run to cancel

res = requests.post(
    f"{BASE_URL}/ai/runs/{run_id}/cancel",
    headers={"Authorization": f"Bearer {TOKEN}"},
)
cancellation = res.json()

POST /ai/runs/:runId/retry ​

Start a new run using the feature key of an existing run and new user messages. An active subscription or eligible purchased credits, plus access to the feature, is required.

Authentication: JWT Bearer token + active AI entitlement required.

Request ​

Use runId from the Create a Run response as $RUN_ID. Send an Idempotency-Key header and a messages array containing 1–50 user messages.

json
{ "messages": [{ "role": "user", "content": "Try this task again" }] }

Response ​

The response has the same requestId, optional runId, and result fields as run creation.

json
{
  "requestId": "00000000-0000-4000-8000-000000000004",
  "runId": "00000000-0000-4000-8000-000000000005",
  "result": { "finishReason": "running", "text": "" }
}

Code Examples ​

javascript
const runId = process.env.RUN_ID;
const idempotencyKey = crypto.randomUUID(); // Keep this key when retrying the same request.
const res = await fetch(`https://api.chainabit.com/api/v1/ai/runs/${runId}/retry`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${TOKEN}`,
    "Content-Type": "application/json",
    "Idempotency-Key": idempotencyKey,
  },
  body: JSON.stringify({ messages: [{ role: "user", content: "Try this task again" }] }),
});
const { requestId, runId: newRunId, result } = await res.json();
python
import os
import requests
import uuid

run_id = os.environ["RUN_ID"]
idempotency_key = str(uuid.uuid4())  # Keep for retries of this request.
res = requests.post(
    f"{BASE_URL}/ai/runs/{run_id}/retry",
    headers={"Authorization": f"Bearer {TOKEN}", "Idempotency-Key": idempotency_key},
    json={"messages": [{"role": "user", "content": "Try this task again"}]},
)
result = res.json()  # requestId, optional runId, result

Built with purpose. chainabit.com