Skip to main content

Stream the answer

This is how the Personaas app shows answers: the text appears while the persona writes it. If your app cannot keep a connection open, check the conversation instead, as in Ask a persona a question.

The stream works the same way on both engines, but some events differ. The rules on this page handle both; you do not need to write code per engine. See Engines for what an engine is.

Flow​

  1. Have an activity_id (create a conversation; see Ask a persona a question).
  2. Open the event stream first.
  3. Send the message on your organisation's engine.
  4. Read events until the run is finished (see When is it finished?), then close the stream yourself.
  5. Fetch the messages (Continue a conversation) and show those as the final truth.
# 2. open the stream (server-sent events; stays open until you close it)
curl -N "$PERSONAAS_BASE_URL/api/v2/activity/$ACTIVITY_ID/stream" \
-H "x-personaas-key: $PERSONAAS_API_KEY"

# 3. in another connection: send the message on your engine (v1 or v3)
curl -X POST "$PERSONAAS_BASE_URL/api/$PERSONAAS_ENGINE/activity/$ACTIVITY_ID/message" \
-H "x-personaas-key: $PERSONAAS_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "input": "Draft a leave policy summary" }'

The stream path is always /api/v2. The send path uses your engine. Any 2xx from the send means it was accepted: v1 answers 200, v3 answers 202. If v3 answers 503 with "No runner available", send on v1 instead (see Engines); the stream stays the same.

Event format​

Standard server-sent events. Each event has a name and a JSON body:

event:RunContent
data:{"content":"You can carry ", ...}

event:WorkflowCompleted
data:{"content":"You can carry over up to 10 days…", ...}

What to do with each event​

EventWhat your app does
delta, RunContent, TeamRunContentA piece of answer text is in content. Append it.
WorkflowCompletedThe run is finished. content holds the whole answer: replace what you appended. If status is "failed" or error is true, the run failed.
error, RunError, WorkflowError, TeamRunError, container_timeoutThe run failed. Remember it; the run is finished at the next WorkflowCompleted or stream_end.
plan_suggested, plan_createdThe task makes a plan first. If a plan needs approval, no more events come for this message; tell the user to approve it in Personaas.
stream_endSee When is it finished?.
WorkflowStarted, ToolCallStarted, ToolCallCompleted and other …Started / …Completed eventsProgress. Optional: show "working…".
connected, iamalive, InputMessage, anything elseIgnore it. New event names can be added at any time.

Rely only on the event name and the fields named in this table. Other fields in the body may change.

When is it finished?​

The run is finished at the first of these:

  1. WorkflowCompleted arrives. Success, unless it says it failed or a failure event came before it.
  2. stream_end arrives after the run has started (after WorkflowStarted, a text event or a failure event). If no WorkflowCompleted came before it, the run failed or was stopped.

Ignore the stream_end that comes right after you send (it follows the InputMessage event). It marks the start of a turn, not the end.

The server does not close the stream when the run ends. Close it yourself once the run is finished.

Events by engine​

You do not need this table if you follow the rules above. It shows why the rules look the way they do.

v1v3
Answer textdeltaRunContent, TeamRunContent
SuccessWorkflowCompleted with the answerWorkflowCompleted with "status": "completed"
Failureerror, or WorkflowError / TeamRunError followed by WorkflowCompletederror, then WorkflowCompleted with "status": "failed"
TimeoutNot reportedcontainer_timeout, error, then WorkflowCompleted with "status": "failed"
Stopped with killstream_endstream_end

Rules​

  • If opening the stream fails, wait a second and open it again, as the Personaas app does.
  • The Personaas app reads the same events over a WebSocket (/api/v2/activity/{activity_id}/stream/wss) for organisations that turn server-sent events off. Apps using an API key use the stream above.
  • The request needs the authentication header. A client that cannot set headers on a streamed request (such as a browser's EventSource) will not work; use one that can.
  • If the connection drops before the run is finished, reconnect, and after a reasonable wait fall back to polling the messages endpoint.
  • Always do step 5. The stored messages are the final answer; text assembled from events is a preview.
  • Set no read timeout on the stream connection. When nothing happens for a minute the server may send iamalive; ignore it.

Example code​

In JavaScript, as an illustration. Any language that can read a streamed HTTP response works the same way.

const TEXT = new Set(["delta", "RunContent", "TeamRunContent"]);
const FAILED = new Set(["error", "RunError", "WorkflowError", "TeamRunError", "container_timeout"]);
const IGNORE = new Set(["connected", "iamalive", "InputMessage"]);

function parseFrame(frame) {
let name, raw;
for (const line of frame.split("\n")) {
if (line.startsWith("event:")) name = line.slice(6).trim();
else if (line.startsWith("data:")) raw = line.slice(5).trim();
}
return { name, raw };
}

// engine: the organisation's engine, "v1" or "v3" (see Engines)
async function streamAnswer(base, apiKey, engine, activityId, input, onText) {
const headers = { "x-personaas-key": apiKey };
const controller = new AbortController();

// open the stream first; if it fails, wait a second and try again
let stream;
for (let attempt = 1; ; attempt++) {
stream = await fetch(`${base}/api/v2/activity/${activityId}/stream`, {
headers,
signal: controller.signal,
});
if (stream.ok) break;
if (attempt === 3) throw new Error(`stream failed: ${stream.status}`);
await new Promise((r) => setTimeout(r, 1000));
}

// then send; if v3 has no free runner, send once on v1 (the stream stays the same)
const send = (eng) =>
fetch(`${base}/api/${eng}/activity/${activityId}/message`, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ input }),
});
let sent = await send(engine);
if (engine === "v3" && sent.status === 503) {
const detail = (await sent.clone().json().catch(() => ({}))).detail || "";
if (/no runner/i.test(detail)) sent = await send("v1");
}
if (!sent.ok) {
controller.abort();
throw new Error((await sent.json().catch(() => ({}))).detail || `send failed: ${sent.status}`);
}

let text = "";
let started = false;
let failed = false;
const finish = (result) => {
controller.abort(); // the server never closes the stream
return { result, text };
};

const decoder = new TextDecoder();
let buffer = "";
try {
for await (const chunk of stream.body) {
buffer += decoder.decode(chunk, { stream: true });
let end;
while ((end = buffer.indexOf("\n\n")) !== -1) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const { name, raw } = parseFrame(frame);
if (!name || IGNORE.has(name)) continue;
let data = {};
try { data = JSON.parse(raw); } catch {}

if (TEXT.has(name) && data.content) {
started = true;
text += data.content;
onText(text);
} else if (FAILED.has(name)) {
started = true;
failed = true;
} else if (name === "WorkflowStarted") {
started = true;
} else if (name === "WorkflowCompleted") {
if (typeof data.content === "string") text = data.content;
const ok = !failed && data.status !== "failed" && data.error !== true;
return finish(ok ? "completed" : "failed");
} else if (name === "stream_end" && started) {
return finish(failed ? "failed" : "stopped");
} else if (name === "plan_suggested" || name === "plan_created") {
// a plan that needs approval sends nothing more; let the caller check the messages
}
}
}
} catch (err) {
if (err.name !== "AbortError") throw err;
}
return { result: "disconnected", text }; // caller: reconnect or poll messages
}