Conversations API

How to drive one of your bots from your own backend over HTTP: which token, every endpoint, the reply stream, and how a user's conversation is identified.

The Conversations API lets your own server talk to one of your bots over HTTP. You open a conversation for one of your users, send their messages, and get the bot's replies as a stream. You can also list and read conversations, hand a thread to a person, answer widgets, upload files, and give the bot facts about the user.

It runs the same bot, flows and tools as the chat widget. Only the way in is different.

Every path below is on your Oalo Base:

https://<base>.oalo.ai/api/v1/chat

When to use it

You wantUse
A chat window on a web page, with no code of your ownThe chat widget
That chat window, signed in as your app's own userThe chat widget with data-user-url and POST /api/chat/v1/sessions (see the chat widget)
Your backend to send messages and read replies, with your own UI or noneThis API, with a Bot API token
Your app to talk to the bot directly as one signed-in user, with no backend in betweenThis API, with a user-bound token from POST /api/v1/chat/token

The user token that POST /api/chat/v1/sessions gives you is for the widget only. This API does not accept it.

Tokens

Every call sends a bearer token in the Authorization header. Only the header is read. A token in the query string is ignored.

Authorization: Bearer oalo_bot_xxxxxxxx

Bot API token

This is the server token. See Tokens and credentials, section 3.

  • Create: in the dashboard, open the bot, then the API tab, then API access, then New token. It is shown once.
  • Per bot. The token decides which bot you talk to. There is no bot id in the URL.
  • Scopes. Pick any of three when you create it. All three are on by default. A scope does not include another.
    • chat:read: list and read conversations, messages and user context.
    • chat:write: create conversations, send messages, take over, submit widgets, call tools, upload files, write user context, erase a user.
    • chat:stream: the reply stream, over SSE or the WebSocket.
  • Expiry is optional.
  • Rotate issues a new token with the same name, scopes and expiry, and retires the old one at once. Revoke stops it at once.
  • Recent API activity on the same tab shows the latest calls made to the bot.

Keep it on your server. A Bot API token can read and write every conversation of its bot, for every user. The API answers browsers too (so the user-bound token below can work from an app), which means nothing stops a Bot API token working there. Don't put it in a web page or a mobile app.

User-bound token (token exchange)

This is the chat session token in Tokens and credentials, section 4. It is bound to one end user, so it is safe to hold in a client.

POST /api/v1/chat/token
Content-Type: application/json

{"public_bot_id": "bot_...", "token": "<the user's own sign-in token>"}

No Bot API token is needed for this call. The user's own credential is the proof. The bot must be published: a draft or archived bot answers 409 bot_not_published (test a draft with its own Bot API token). You can send the user's token in the body as token, or in an X-End-User-Token header. bot works in place of public_bot_id.

Oalo checks the credential in this order:

  1. Oalo sign-in. The access token of a person signed in to an app built on your Base (see Auth). Their user id becomes the external_ref.
  2. The bot's own auth tool, when the bot's Auth tab is set to custom. It checks a token from Firebase, Auth0 or your own system and returns the user's id.

On success:

{
  "token": "oalo_bot_...",
  "token_type": "Bearer",
  "expires_at": "2026-11-09T15:04:05Z",
  "expires_in": 3600,
  "external_ref": "user_42",
  "session_context": {"provider": "oalo", "email": "ana@example.com", "username": "ana", "org_id": "..."}
}
  • It lasts an hour. There is no refresh token. Exchange again before expires_at, or after the first 401.
  • It has all three scopes.
  • It acts only as its own external_ref. The external_ref you pass to other calls is ignored. Another user's conversation answers 404, and another user's context answers 403 forbidden.
StatusCodeWhy
404bot_not_foundNo bot with that public id
422invalid_requestNo end-user token sent
400auth_not_configuredNot an Oalo sign-in token, and the bot has no custom auth tool
401end_user_unauthorizedThe credential was rejected

Bots with custom auth

When a bot's Auth tab is set to custom, a call made with a Bot API token must also carry the user's own token:

X-End-User-Token: <the user's Firebase or other token>

The bot's auth tool checks it, and the call then acts as that user, as a user-bound token does. Without it the call answers 401 end_user_token_required. A rejected one answers 401 end_user_unauthorized. A user-bound token never needs this header.

How a conversation is identified

You name each of your users with an external_ref: any stable id your system already has, such as your own user id. Your users never sign in to Oalo for this. The external_ref is how Oalo tells them apart.

  • One active conversation per user per bot. Creating a conversation with an external_ref that already has an active one gives you that one back. That is how a returning user continues their thread.
  • Use an id that never changes. A new external_ref each session, or an email the user can edit, splits one person's history over many threads.
  • Same thread as the widget. When the chat widget is signed in as your app's user through POST /api/chat/v1/sessions, its conversation is keyed by the same external_ref on the same bot. So the widget and this API reach the same active thread.
  • Same contact. Your external_ref is the same id that app events use for a contact, and user context you write here lands on that contact.

What counts as your app's signed-in user is narrower. A tool that calls your app gets the user's id (the X-Oalo-User header), and a tool marked as needing a signed-in user can run, only when Oalo knows who the user is:

  • The thread was made by the chat widget with a user token from POST /api/chat/v1/sessions. This is decided when the thread is made. A thread this API made first stays as it is when the widget later opens it.
  • Or the external_ref is the user id of a person signed in to an app built on your Base, as the Oalo sign-in exchange above gives you. The conversation is then linked to that person.

A conversation you create here with any other external_ref is that user's thread, but tools do not treat it as a signed-in user of your app.

Quick start

Set two variables first:

export OALO_BASE_URL=https://yourbase.oalo.ai
export OALO_BOT_TOKEN=oalo_bot_xxxxxxxx

Create or resume a conversation:

curl -X POST "$OALO_BASE_URL/api/v1/chat/conversations" -H "Authorization: Bearer $OALO_BOT_TOKEN" -H "Content-Type: application/json" -d '{"external_ref": "user_42"}'

In a second terminal, watch the stream (use the id from the first call):

curl -N "$OALO_BASE_URL/api/v1/chat/conversations/123/stream" -H "Authorization: Bearer $OALO_BOT_TOKEN"

Send a message. The reply arrives on the stream:

curl -X POST "$OALO_BASE_URL/api/v1/chat/conversations/123/messages" -H "Authorization: Bearer $OALO_BOT_TOKEN" -H "Content-Type: application/json" -H "Idempotency-Key: $(uuidgen)" -d '{"text": "What are your opening hours?"}'

Read the history:

curl "$OALO_BASE_URL/api/v1/chat/conversations/123/messages" -H "Authorization: Bearer $OALO_BOT_TOKEN"

Endpoints

All paths are under /api/v1/chat. Bodies are JSON.

MethodPathScopeDoes
POST/tokennoneExchange a user's sign-in for a user-bound token
POST/conversationschat:writeCreate or resume a user's conversation
GET/conversationschat:readList conversations
GET/conversations/:idchat:readRead one conversation
GET/conversations/:id/messageschat:readRead its messages
POST/conversations/:id/messageschat:writeSend a user message
GET/conversations/:id/streamchat:streamStream events (SSE)
POST/conversations/:id/autopilotchat:writeHand to a person, or back to the bot
POST/conversations/:id/widget/submitchat:writeAnswer a widget
POST/conversations/:id/widget/call_toolchat:writeCall one of the bot's tools
POST/conversations/:id/upload/presignchat:writeGet an upload address
POST/conversations/:id/upload/registerchat:writeRecord an uploaded file
POST/conversations/:id/upload/completechat:writeAnswer an upload request with files
POST/conversations/:id/upload/cancelchat:writeDecline an upload request
GET, PUT, PATCH, DELETE/users/:external_ref/contextread: chat:read, others: chat:writeThe user's stored facts
DELETE/members/:external_refchat:writeErase everything about a user
GET/calendar, /calendar/changes, /calendar/streamThe user's calendar, see Calendar sync for your apps

A conversation that belongs to another bot, or to another user when the token is user-bound, answers 404 not_found. Errors always look like this:

{"error": {"code": "not_found", "message": "conversation not found"}}

Create or resume a conversation

POST /conversations
{"external_ref": "user_42", "context": {"page": "/pricing"}, "persist_context": false, "metadata": {}}
  • external_ref is required (422 invalid_request without it). A user-bound token uses its own and ignores this one.
  • context (optional object) is session context for this conversation. Flows read it as {{session.*}}.
  • persist_context: true also stores context as the user's lasting facts, read as {{user.*}} (see User context).
  • metadata (optional object) is kept with a new conversation. Keys Oalo sets itself (channel, phone_number_id, wa_id, app_user, preview and the like) are dropped.
  • resume defaults to true. With false, Oalo still gives you the active conversation if there is one, because a user can only have one active conversation per bot.

Answers 201 with "resumed": false for a new conversation, or 200 with "resumed": true for the active one:

{
  "conversation": {
    "id": 123,
    "external_ref": "user_42",
    "status": "active",
    "channel": null,
    "autopilot": null,
    "started_at": "2026-11-09T14:00:00Z",
    "completed_at": null
  },
  "resumed": false
}
  • status is active while the thread is open. Other values are completed, closed and abandoned.
  • channel is the channel a conversation came in on, such as "whatsapp" or "instagram", and usually null for one made through this API.
  • autopilot is null when the conversation follows the bot's default, or true or false when it was set on this conversation.

This call counts toward the per-user rate limit (see Limits and errors).

Send a message

POST /conversations/:id/messages
Idempotency-Key: <a new unique value per message>
{"text": "What are your opening hours?", "context": {"page": "/hours"}, "persist_context": false, "flow": null}

The text is the user's message. The call answers at once, before the bot replies:

{"queued": true, "cost_warning": null}

The reply comes on the stream. Open the stream before you send, because a fresh stream starts from now and does not replay earlier events. If you missed it, read it with GET /messages.

  • Idempotency-Key is required (400 idempotency_key_required). A retry with the same key, from the same token, within 48 hours is not sent again. It answers 202 {"queued": true} with the header idempotent-replayed: true. A refused send does not use up its key, so you can retry it.
  • text is required (422 invalid_request).
  • context (optional) replaces this conversation's session context before the turn. persist_context: true also stores it as the user's facts.
  • flow (optional) is the name of one of the bot's enabled flows. The flow runs on this message instead of the bot's normal reply, with the text in {{state.user_input}}. Its output streams back as the reply. It answers 202 {"queued": true, "flow": "refunds", "flow_run_id": 1234}, or 404 flow_not_found, or 409 flow_active when a flow is already running on the conversation. A named flow runs even when autopilot is off.
  • When autopilot is off, the message is saved and shows in the inbox, and the bot does not reply. A person answers from there.
  • 409 conversation_closed when the conversation is not active. Create a conversation again to get the user's active one.
  • When the bot has passed its soft daily cost cap, cost_warning is "soft_cap_exceeded" and the header x-cost-warning is set. The message is still sent.

Read conversations and messages

GET /conversations?external_ref=user_42&status=active&limit=50&before=123

Newest first. limit is 50 by default, at most 200. All filters are optional. A user-bound token only sees its own. To page back, pass next_before as before.

{"conversations": [{"id": 123, "external_ref": "user_42", "status": "active", "...": "..."}], "next_before": 123}
GET /conversations/:id

Answers {"conversation": {...}} with the fields above plus collected_data (what the bot's flows collected), autopilot_changed_at and autopilot_changed_by.

GET /conversations/:id/messages?after=0&limit=100

Oldest first. limit is 100 by default, at most 500. To read on, pass next_after as after. Stop when messages comes back empty.

{
  "messages": [
    {"id": 9001, "role": "user", "content": "What are your opening hours?", "widget_ref": null, "tool_call": null, "tool_result": null, "created_at": "2026-11-09T14:00:05Z"},
    {"id": 9002, "role": "assistant", "content": "We're open 9 to 6, Monday to Saturday.", "widget_ref": null, "tool_call": null, "tool_result": null, "created_at": "2026-11-09T14:00:07Z"}
  ],
  "next_after": 9002
}

role is one of user, assistant, widget_render, widget_submit, tool_call, tool_result, system and info (a progress line a flow showed, such as "Analyzing media").

Stream replies (SSE)

GET /conversations/:id/stream?layers=text,lifecycle,action&flow_run_id=1234
Last-Event-ID: 57

A plain HTTP stream of text/event-stream frames:

id: 58
event: delta
data: {"text":"We're open ","run_id":null}
  • Layers. layers picks what you get: text (the reply), lifecycle (flow steps and progress) and action (widgets, upload requests, tool payloads). All three by default.
  • flow_run_id keeps only one flow run's events.
  • Keep-alive. When nothing happens for 15 seconds the server sends event: ping. Your client sends nothing.
  • Reconnect. Send the last id you saw as Last-Event-ID (or ?last_event_id=) and the events you missed are replayed. Oalo keeps the last 300 events of a conversation, for about 30 minutes after it goes quiet. If your id is older than that you get event: gap. Then read what you missed with GET /messages.
  • Several frames can share one id.

Stream events

Every event's data carries run_id: the flow run it came from, or null for the bot's normal reply.

Text layer:

EventData
delta{"text"}: a piece of the reply. A flow sends its whole output as one delta.
done{"message_id", "usage"}: the reply is saved. A failed flow adds "failed": true.
tool_status{"tool", "status", "summary"}: a tool started or finished
field:updated{"field", "value"}: the bot collected a field
message{"message_id", "text", "source": "direct"}: a person or a workflow wrote into the conversation
error{"code", "message"}

Lifecycle layer: flow:started (flow_id, flow_name), flow:node_entered (node_id, node_type), flow:node_done (node_id, output), flow:node_failed (node_id, reason), flow:completed (state), flow:failed (reason), flow:halted_cost, and info (message, node_id), a progress line that is safe to show the user as it is. A flow waiting for input stays at flow:node_entered until it gets it.

Action layer:

EventData
widget:renderrender_id, widget_id, widget_name, kind, config, field_bindings, intro_message, endpoint_token, render_mode, bundle_url
widget:render_flownode_id, widget_id, resume_token, values, widget_token, kind, render_id, fields, render_mode, bundle_url
widget:update_flownode_id, patch
upload:requestnode_id, resume_token, prompt, accept, max_bytes, max_files, timeout_ms
tool:emitWhatever the tool sent. Switch on its type.

The full text of a reply is always in GET /messages. Use done's message_id to find it, rather than relying only on the deltas.

WebSocket

The same events also come over a WebSocket, which can carry many conversations on one connection. It uses the Phoenix channels protocol.

  • Address: wss://<base>.oalo.ai/chat-api-ws. The token goes in the connect params as token, not in a header, and needs chat:stream. A bad token, or one without that scope, is refused.
  • A bot with custom auth: a server token must also send the user's own token in the connect params as end_user_token, as HTTP calls send X-End-User-Token. Without it, or with one the bot's auth tool rejects, the connection is refused. The socket then reaches only that user's conversations. A user-bound token needs nothing more.
  • Join chat:api:<conversation id>. A conversation that isn't this bot's (or this user's, for a user-bound token) fails with {"code": "not_found"}.
  • What differs from SSE: every layer comes, with no filter, no replay, no ping and no gap. It only delivers events. Send messages over HTTP.
  • Heartbeat. An idle socket is closed after about five minutes. Send a heartbeat at least every 30 seconds. The Phoenix JavaScript client does this for you. If you can't, use SSE.
import { Socket } from "phoenix";

const socket = new Socket("wss://yourbase.oalo.ai/chat-api-ws", { params: { token: process.env.OALO_BOT_TOKEN } });
socket.connect();
const channel = socket.channel("chat:api:123");
channel.on("delta", (d) => process.stdout.write(d.text));
channel.on("done", (d) => console.log(`\n(saved as message ${d.message_id})`));
channel.join().receive("error", (e) => console.error("join failed:", e.code));

The same socket serves the user's calendar on chat:api:calendar. See Calendar sync for your apps.

Hand a conversation to a person

POST /conversations/:id/autopilot
{"on": false}

Answers {"autopilot": false}. With autopilot off the bot stops replying in this conversation. New user messages are saved and show in the inbox, where a person answers. Their replies come on the stream as message events. {"on": true} gives the conversation back to the bot. on must be true or false (422 invalid_request). See Inbox for how takeover looks there.

Widgets and tools

When a flow shows a widget, widget:render_flow arrives on the stream. Answer it with the run and the token it gave you:

POST /conversations/:id/widget/submit
{"flow_run_id": 1234, "resume_token": "...", "values": {"size": "M"}}

Use the event's run_id as flow_run_id (a number). It answers 202 {"resumed": true}, and the flow's next output streams. Errors: 403 invalid_resume_token (the token doesn't match the waiting step), 409 not_waiting (that run isn't waiting for a widget), 404 (no such run in this conversation), 422 invalid_request (missing flow_run_id or values not an object).

When the bot shows a widget in chat, widget:render arrives. Answer it with its render_id:

POST /conversations/:id/widget/submit
{"render_id": "...", "values": {"email": "ana@example.com"}}

It answers 202 {"submitted": true}. A body with render_id is always handled this way, so don't send render_id for a flow widget.

Both answer 409 conversation_closed when the conversation is not active. See Widgets for building them.

To call one of the bot's tools directly:

POST /conversations/:id/widget/call_tool
{"tool_name": "check_availability", "args": {"date": "2026-11-12"}}

It answers {"result": ...}, or 422 tool_error with the tool's message. A Bot API token can call any of its bot's tools. A user-bound token can call only the tools that a widget shown in this conversation declares, plus the user's own calendar and booking tools. The rate limit and the daily cost cap apply.

File uploads

Uploading takes two calls and a PUT, and works when the bot accepts files (otherwise 403 media_disabled).

  1. POST /conversations/:id/upload/presign with {"filename": "demo.mp4", "content_type": "video/mp4"}. It answers {"upload_url", "s3_key", "public_url"}. The address works for an hour.
  2. PUT the file's bytes to upload_url, with the same Content-Type.
  3. POST /conversations/:id/upload/register with {"s3_key", "public_url", "filename", "content_type", "size_bytes"}. It answers {"media_id", "url", "content_type", "filename"}.

If a flow asked for the file (upload:request on the stream), add its resume_token to the register call and the flow carries on with the file. Without one, the file counts as the user attaching it, which starts the bot's upload flow if it has one.

To answer an upload request with files you already registered, call POST /conversations/:id/upload/complete with {"resume_token", "media_ids": [...]} (answers 202 {"resumed": true}). To decline it, call POST /conversations/:id/upload/cancel with {"resume_token"} (answers 202 {"cancelled": true}), and the flow can take its "cancelled" path.

User context

Facts about a user that the bot and your workflows can read as {{user.*}}, such as their plan or name. They belong to the external_ref across the whole workspace, not to one conversation, and you can write them before the user has ever chatted.

PUT    /users/:external_ref/context    {"data": {"plan": "pro", "name": "Ana"}}   replaces
PATCH  /users/:external_ref/context    {"data": {"plan": "team"}}                 merges top-level keys
GET    /users/:external_ref/context
DELETE /users/:external_ref/context
  • PUT, PATCH and GET answer {"external_ref", "data"}. DELETE answers {"deleted": true}.
  • data must be an object (422 invalid_request), at most 64 KB (413 payload_too_large).
  • A write also goes onto the user's contact in the CRM, found or made by external_ref.
  • A user-bound token can only reach its own (403 forbidden).

Erase a user

When one of your users deletes their account:

DELETE /members/:external_ref

It deletes what this bot holds about that user: their conversations and messages with it, what it remembered about them, their API activity and tokens for this bot, and the files in those conversations. Other bots keep theirs. Their stored context (/users/:external_ref/context) is shared by every bot in the workspace, so it goes for all of them. It answers with the counts, for example {"deleted": {"conversations": 2, "messages": 41, "memories": 3, "profiles": 1, "personas": 0, "api_context": 1, "api_activity": 12, "api_tokens": 1, "media": 0}}. Calling it again is safe. The contact in the CRM is not in that list. Remove it there if you need to. A user-bound token can only erase its own user, and it stops working afterwards.

Limits and errors

You set the limits in the bot's API tab, under Limits.

LimitDefaultApplies toRefused with
Requests per minute, per user30create conversation, send message, call tool429 rate_limited
Messages per user per daynonesend message429 daily_limit_reached
Soft cap per day ($)nonesend messagea warning only
Hard cap per day ($)nonesend message, call tool429 cost_cap_exceeded
  • "Per user" means per external_ref on this bot. The minute is a fixed window, and every attempt counts.
  • Every 429 carries Retry-After in seconds. The daily limits reset at the start of the UTC day.

Other errors you may see on any call:

StatusCodeWhy
401invalid_tokenNo token, a wrong one, an expired one, or a revoked one
403forbidden_scopeThe token lacks the scope this call needs
401end_user_token_requiredThe bot uses custom auth and no X-End-User-Token was sent
401end_user_unauthorizedThe X-End-User-Token was rejected
404not_foundNo such conversation for this bot (or this user)
422invalid_requestA required field is missing or the wrong type

Example: a send-and-read loop in Node

This chats with your bot from a terminal. It needs Node 18 or later and nothing else. Save it as chat.mjs, set the two variables from Quick start, and run node chat.mjs. An empty line quits.

import readline from "node:readline/promises";
import { randomUUID } from "node:crypto";

const API = `${process.env.OALO_BASE_URL}/api/v1/chat`;
const auth = { Authorization: `Bearer ${process.env.OALO_BOT_TOKEN}` };

async function call(method, path, body, headers = {}) {
  const res = await fetch(API + path, {
    method,
    headers: { ...auth, "Content-Type": "application/json", ...headers },
    body: body ? JSON.stringify(body) : undefined,
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${json.error?.code}: ${json.error?.message}`);
  return json;
}

// Read SSE frames and hand each event to onEvent(name, data).
async function readStream(res, onEvent) {
  const decoder = new TextDecoder();
  let buf = "";
  for await (const chunk of res.body) {
    buf += decoder.decode(chunk, { stream: true });
    let i;
    while ((i = buf.indexOf("\n\n")) !== -1) {
      const frame = buf.slice(0, i);
      buf = buf.slice(i + 2);
      let event = "message";
      let data = "";
      for (const line of frame.split("\n")) {
        if (line.startsWith("event: ")) event = line.slice(7);
        else if (line.startsWith("data: ")) data += line.slice(6);
      }
      if (data) onEvent(event, JSON.parse(data));
    }
  }
}

const { conversation, resumed } = await call("POST", "/conversations", { external_ref: "user_42" });
console.log(`${resumed ? "Resumed" : "Started"} conversation ${conversation.id}`);

// Open the stream once, before the first message, and keep it open.
let endTurn = null;
const stream = await fetch(`${API}/conversations/${conversation.id}/stream?layers=text`, { headers: auth });
if (!stream.ok) throw new Error(`stream: ${stream.status}`);
readStream(stream, (event, data) => {
  if (event === "delta") process.stdout.write(data.text);
  if (event === "error") process.stdout.write(`[${data.code}: ${data.message}]`);
  if ((event === "done" || event === "error") && endTurn) {
    process.stdout.write("\n");
    endTurn();
    endTurn = null;
  }
}).catch((e) => console.error("stream closed:", e.message));

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
while (true) {
  const text = (await rl.question("you> ")).trim();
  if (!text) break;
  const turn = new Promise((resolve) => (endTurn = resolve));
  process.stdout.write("bot> ");
  await call("POST", `/conversations/${conversation.id}/messages`, { text }, { "Idempotency-Key": randomUUID() });
  await turn;
}
rl.close();
process.exit(0);

If the conversation is handed to a person (autopilot off), no reply comes and the loop waits. Turn autopilot back on, or answer from the inbox.

Common mistakes

  • A Bot API token in a browser or an app. It reaches every user's conversations. Use a user-bound token from POST /api/v1/chat/token.
  • Opening the stream after sending. A fresh stream starts from now, so a fast reply is missed. Open it first, or read GET /messages.
  • A new Idempotency-Key on a retry. The retry is then a second message. Reuse the key when you retry the same message.
  • A changing external_ref. It splits a user's history and their contact.
  • Expecting resume: false to start over. It returns the active conversation while there is one.
  • Assuming a thread is your app's signed-in user because it has the same external_ref. See How a conversation is identified.
Related
Try it on your own Base

Sign up, install the CLI, and deploy your repo in a few minutes.

bring your repo