Streaming

Stream agent replies from the Askocto API as server-sent events and read message.delta, message.done, tool.call and error events in JavaScript.

Working draft. These docs are illustrative: names, endpoints and examples describe the intended behaviour and can change before launch.

Streaming sends the reply of an agent while it is being written, so your interface can show text right away instead of waiting for the full answer. You turn it on with "stream": true on Chat with an agent. The response then has the content type text/event-stream and carries server-sent events.

Start a stream

curl -N -X POST https://api.askocto.co/v2/agents/agt_8f3k2m/chat \
  -H "Authorization: Bearer $OCTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [{ "role": "user", "content": "Where is my order?" }],
    "stream": true
  }'

Every other field of the chat request works as usual, including conversationId, userId and metadata.

Event format

Each event is a block of lines that ends with an empty line. The event line names the type and the data line holds a JSON payload:

event: message.delta
data: {"conversationId":"conv_5n2p8w","messageId":"msg_7c1k9s","delta":"I can check "}

event: message.delta
data: {"conversationId":"conv_5n2p8w","messageId":"msg_7c1k9s","delta":"that for you."}

event: message.done
data: {"conversationId":"conv_5n2p8w","message":{"id":"msg_7c1k9s","role":"assistant","content":"I can check that for you.","sources":[{"id":"src_91xa7d","title":"Shipping and delivery"}]},"usage":{"credits":1}}

data: [DONE]
Event Payload Meaning
message.delta conversationId, messageId, delta A piece of the reply. Append delta to the text so far.
message.done conversationId, message, usage The reply is complete. The payload matches a non-streaming response.
tool.call conversationId, toolCallId, name, arguments The agent asks your app to run a client action. See Client actions.
error error The stream failed after it started. The error object has code, message and requestId.

The last frame is always data: [DONE]. Close the connection when you read it.

Read the stream in JavaScript

This example uses fetch in Node 20 or later and prints the reply as it arrives:

async function streamReply(text) {
  const response = await fetch("https://api.askocto.co/v2/agents/agt_8f3k2m/chat", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.OCTO_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      messages: [{ role: "user", content: text }],
      stream: true,
    }),
  })

  if (!response.ok) {
    const { error } = await response.json()
    throw new Error(`${error.code}: ${error.message}`)
  }

  const decoder = new TextDecoder()
  let buffer = ""

  for await (const chunk of response.body) {
    buffer += decoder.decode(chunk, { stream: true })
    const frames = buffer.split("\n\n")
    buffer = frames.pop()

    for (const frame of frames) {
      const event = /^event: (.+)$/m.exec(frame)?.[1]
      const data = /^data: (.+)$/m.exec(frame)?.[1]
      if (data === "[DONE]") return
      if (!data) continue

      const payload = JSON.parse(data)
      if (event === "message.delta") process.stdout.write(payload.delta)
      if (event === "tool.call") console.log("\nTool call:", payload.name, payload.arguments)
      if (event === "message.done") console.log("\nCredits used:", payload.usage.credits)
      if (event === "error") throw new Error(payload.error.message)
    }
  }
}

await streamReply("Where is my order?")

Frames can be split across network chunks, so the code keeps a buffer and only parses complete frames.

Errors and reconnecting

A request that fails before the stream begins, such as a 401 or a 404, returns a normal JSON error. See Error handling. If the connection drops mid-reply, use the conversationId you already received to read the stored messages with List conversation messages, or send the question again.

Something unclear or missing? Tell us and we will fix the page.