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
inputobject,agentId, andworkspaceIdfields are not accepted. Use themessagesarray instead.
Identifiers in response examples are synthetic UUIDs. Use the IDs returned by your requests.
Run Orchestration Walkthrough
- List the catalog (
GET /ai/features) to discover available feature keys. - Create a run (
POST /ai/features/:featureKey/runs) with amessagesarray containing the user prompt. - Watch the run status via
GET /ai/runs/:runIdorGET /ai/runs/:runId/steps, and stream the final response and settlement throughGET /ai/runs/:runId/stream. - Cancel (
POST /ai/runs/:runId/cancel) or retry (POST /ai/runs/:runId/retry) when a run stalls, then capture the finalresultfield once the run completes.
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
| Method | Path | Description | Auth |
|---|---|---|---|
| GET | /ai/features | List AI feature catalog | JWT + Entitlement |
| POST | /ai/features/:featureKey/runs | Create a run for a feature | JWT + Entitlement |
| GET | /ai/runs | List runs (filterable) | JWT + Entitlement |
| GET | /ai/runs/:runId | Get a run | JWT + Entitlement |
| GET | /ai/runs/:runId/steps | List steps of a run | JWT + Entitlement |
| GET | /ai/runs/:runId/stream | SSE stream for a run | JWT + Entitlement |
| POST | /ai/runs/:runId/cancel | Cancel a running run | JWT + Entitlement |
| POST | /ai/runs/:runId/retry | Create a new run from an existing feature run | JWT + Entitlement |
| POST | /ai/runs/:runId/resume | Resume a recoverable interrupted run | JWT + 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
[
{
"key": "ai.chat.multi_agent",
"aliases": [],
"isActive": true,
"isVisibleOnPlan": true
}
]Response Fields
| Field | Type | Description |
|---|---|---|
key | string | Feature identifier |
aliases | string[] | Alias names; the current catalog returns an empty list |
isActive | boolean | Whether the feature is active |
isVisibleOnPlan | boolean | Whether the caller's plan exposes the feature |
Code Examples
const res = await fetch(`https://api.chainabit.com/api/v1/ai/features`, {
headers: { Authorization: `Bearer ${TOKEN}` },
});
const features = await res.json();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
| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
messages | array | Yes | 1–50 items | Conversation messages to send |
messages[].role | string | Yes | "user" | Role of the message author |
messages[].content | string | Yes | Non-empty | Message content |
temperature | number | No | 0–2 | Sampling temperature |
maxOutputTokens | number | No | 1–200,000 | Maximum tokens in the response |
provider | string | No | Provider key | Provider selection, subject to plan access |
effortMode | string | No | basic, thinking, pro | Model 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
{
"requestId": "00000000-0000-4000-8000-000000000002",
"runId": "00000000-0000-4000-8000-000000000001",
"result": { "finishReason": "running", "text": "" }
}Response Fields
| Field | Type | Description |
|---|---|---|
requestId | string | Request identifier |
runId | string (optional) | New run ID, when a run was created |
result | object | Execution result; an accepted asynchronous run can report finishReason: "running" |
Code Examples
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();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, resultGET /ai/runs
List all runs, with optional filters.
Authentication: JWT Bearer token + active AI entitlement required.
Request
| Parameter | Type | Required | Description |
|---|---|---|---|
agentId | string | No | Filter by agent |
workspaceId | string | No | Filter by workspace |
featureKey | string | No | Filter by feature |
status | string | No | Filter by status: queued, running, completed, failed, cancelled |
limit | number | No | Items per page |
offset | number | No | Pagination offset |
Response
Response Example
{
"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
| Field | Type | Description |
|---|---|---|
id | string | Run ID |
featureKey | string | Feature that triggered the run |
status | string | queued, running, completed, failed, cancelled |
startedAt | string | ISO 8601 |
finishedAt | string | null | ISO 8601 or null |
Code Examples
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();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
{
"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
| Field | Type | Description |
|---|---|---|
id | string | Run ID |
featureKey | string | Feature that triggered the run |
status | string | queued, running, completed, failed, cancelled |
result | unknown | Public run result; access may be restricted |
startedAt | string | null | ISO 8601 |
finishedAt | string | null | ISO 8601 or null |
createdAt | string | ISO 8601 |
Code Examples
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();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
[
{
"id": "00000000-0000-4000-8000-000000000003",
"stepIndex": 0,
"stepType": "llm_call",
"tokensUsed": 1250,
"durationMs": 3400,
"createdAt": "2026-03-17T10:00:01.000Z"
}
]Response Fields
| Field | Type | Description |
|---|---|---|
id | string | Step ID |
stepIndex | number | Step order within the run |
stepType | string | Step type (e.g. llm_call) |
tokensUsed | number (optional) | Token usage |
durationMs | number (optional) | Duration in milliseconds |
createdAt | string | ISO 8601 |
contentRedacted | boolean (optional) | True when the caller cannot access step content |
Code Examples
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();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
| Field | Type | Description |
|---|---|---|
eventId | number | Monotonically increasing event counter for this run |
type | string | SSE event type — see SSE Streaming reference for the full catalog |
runId | string | Run UUID |
timestamp | string | ISO 8601 event timestamp |
payload | object | Event-specific data (e.g. { content } for message.completed) |
Code Examples
// 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()));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"}:
breakPOST /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
{
"cancelled": true
}Response Fields
| Field | Type | Description |
|---|---|---|
cancelled | boolean | true 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
runIdthat does not exist, or a run in another account or workspace that you did not start, is refused with403. 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
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();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.
{ "messages": [{ "role": "user", "content": "Try this task again" }] }Response
The response has the same requestId, optional runId, and result fields as run creation.
{
"requestId": "00000000-0000-4000-8000-000000000004",
"runId": "00000000-0000-4000-8000-000000000005",
"result": { "finishReason": "running", "text": "" }
}Code Examples
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();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