Skip to content

Streaming

Send "stream": true and the answer arrives as it's written, as server-sent events. The JSON in each event repeats the event name in type and numbers the events in sequence_number.

On the wire, each event is two lines followed by a blank line. The data: line is always one line of JSON:

event: response.output_text.delta
data: {"type": "response.output_text.delta", "sequence_number": 3, "delta": "There are "}

A typical answer sends these, in order. Here is each event's data, formatted to read:

{
  "type": "response.created",
  "sequence_number": 0,
  "response": {
    "id": "resp_6f1c…",
    "object": "response",
    "status": "in_progress",
    "conversation": {
      "id": "conv_93ab…"
    },
    "output": [],
    "output_text": "",
    "usage": {
      "input_tokens": 0,
      "input_tokens_details": {
        "cached_tokens": 0,
        "cache_write_tokens": 0
      },
      "output_tokens": 0,
      "total_tokens": 0,
      "cost_usd": null
    },
    "error": null,
    "metadata": {}
  }
}
{
  "type": "response.tool.started",
  "sequence_number": 1,
  "call_id": "call_1",
  "name": "query",
  "summary": "Run a query on Warehouse: select carrier, count(*) …"
}
{
  "type": "response.tool.finished",
  "sequence_number": 2,
  "call_id": "call_1",
  "name": "query",
  "ok": true
}
{
  "type": "response.output_text.delta",
  "sequence_number": 3,
  "delta": "There are "
}
{
  "type": "response.completed",
  "sequence_number": 9,
  "response": {
    "id": "resp_6f1c…",
    "object": "response",
    "status": "completed",
    "conversation": {
      "id": "conv_93ab…"
    },
    "output": [],
    "output_text": "There are three renewals due this week…",
    "usage": {
      "input_tokens": 4120,
      "input_tokens_details": {
        "cached_tokens": 3800,
        "cache_write_tokens": 0
      },
      "output_tokens": 186,
      "total_tokens": 4306,
      "cost_usd": "0.012870"
    },
    "error": null,
    "metadata": {}
  }
}

The response in the last event is the whole response, exactly as POST /responses returns it without streaming.

The events

Event Carries What to do
response.created response Keep response.id and response.conversation.id.
response.thinking.delta delta Optional: a summary of the agent's thinking, as it thinks. Show it apart from the answer (e.g. collapsed under "Show thinking"). Only sent when the workspace shows thinking and the model provides it.
response.output_text.delta delta Add the text to what you're showing.
response.tool.started call_id, name, summary Optional: show the step. summary says it in plain words ("Run a query on Warehouse: select …"), or "Using " for a tool without its own wording.
response.display.added call_id, item_id, display Draw the table, chart, number or file a tool made. item_id is the stored tool result it belongs to (the function_call_output item's id). See Displays.
response.tool.finished call_id, name, ok Optional: clear that line.
response.approval_requested approval Show it and ask the person. See Approvals.
response.completed response The end. The whole response, as POST /responses returns it without streaming.
response.requires_approval response The end, for now: waiting for a person's yes or no.
response.failed response The end. response.error says what went wrong.
response.cancelled response The end. You stopped it.

The stream always closes after one of the last four. New event types may be added later, so ignore any you don't know.

Examples

curl -N "$KLARIS_API/responses" \
  -H "Authorization: Bearer $KLARIS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "nick@example.com",
    "input": "Summarise the renewals due this week",
    "stream": true
  }'
import json, os
import requests

API, KEY = os.environ["KLARIS_API"], os.environ["KLARIS_KEY"]

with requests.post(f"{API}/responses", stream=True, timeout=300,
                   headers={"Authorization": f"Bearer {KEY}"},
                   json={
                       "user": "nick@example.com",
                       "input": "Summarise the renewals due this week",
                       "stream": True,
                   }) as res:
    res.raise_for_status()
    for line in res.iter_lines(decode_unicode=True):
        if not line or not line.startswith("data: "):
            continue
        event = json.loads(line[len("data: "):])
        if event["type"] == "response.output_text.delta":
            print(event["delta"], end="", flush=True)
        elif event["type"] in ("response.completed", "response.requires_approval",
                               "response.failed", "response.cancelled"):
            final = event["response"]
print("\nCost:", final["usage"]["cost_usd"])
const res = await fetch(`${API}/responses`, {
  method: "POST",
  headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    user: "nick@example.com",
    input: "Summarise the renewals due this week",
    stream: true,
  }),
});
const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
const ENDS = ["response.completed", "response.requires_approval", "response.failed", "response.cancelled"];
let buffer = "", final: any = null;
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  const blocks = buffer.split("\n\n");
  buffer = blocks.pop()!;               // keep a half-received event for the next read
  for (const block of blocks) {
    const data = block.split("\n").find((l) => l.startsWith("data: "));
    if (!data) continue;
    const event = JSON.parse(data.slice(6));
    if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
    if (ENDS.includes(event.type)) final = event.response;
  }
}

Behind a proxy

If your server passes the stream on to a browser, turn off response buffering on that route (for nginx, proxy_buffering off). Otherwise the text arrives all at once at the end.