Skip to content
QwryAI
Documentation
Pages

Getting Started

Streaming

Read your agent's answer word by word as it's written, over Server-Sent Events

The Chat API streams by default. Your app can show the answer while the agent writes it, the way the Chat bubble does, instead of waiting for the whole reply.

Enabling Streaming

Streaming is on unless you send "stream": false. It works on the chat and retry endpoints:

Bash
curl -N -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "message": "Where is my order?",
    "stream": true,
    "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3",
    "userId": "customer_1042"
  }'

Request Body

FieldTypeRequiredDescription
messagestringYes, unless conversationId is sentThe customer's message. Leave it out to let the agent continue after you submit a client action result.
streambooleanNoStream the reply as Server-Sent Events. Defaults to true.
conversationIdstringNoContinue this conversation. Leave it out to start a new one.
userIdstringNoYour id for the customer, on a new conversation. Up to 128 characters from a-z A-Z 0-9 . _ -. Ignored when conversationId is sent.

Any other field is refused with VALIDATION_INVALID_BODY. The body can be at most 1 MB.

The response has Content-Type: text/event-stream and follows the AI SDK UIMessage stream format. Each event is a data: line holding a JSON object with a type, followed by a blank line. The stream ends with data: [DONE]:

Code
data: {"type":"start","messageId":"5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10"}

data: {"type":"start-step"}

data: {"type":"text-start","id":"text_0"}

data: {"type":"text-delta","id":"text_0","delta":"Your order"}

data: [DONE]

Event Types

start

Sent once, first. Carries the id of the answer being written.

JSON
{ "type": "start", "messageId": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10" }

text-start

A block of text begins. Ids count up: text_0, text_1…

JSON
{ "type": "text-start", "id": "text_0" }

text-delta

The next piece of text. Join every delta to build the answer.

JSON
{ "type": "text-delta", "id": "text_0", "delta": "Your order shipped on" }

text-end

The text block is complete.

JSON
{ "type": "text-end", "id": "text_0" }

Metadata

The finish event carries the finish reason and, under messageMetadata, the answer's details:

JSON
{
  "type": "finish",
  "finishReason": "stop",
  "messageMetadata": {
    "messageId": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10",
    "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3",
    "userMessageId": "0c4f6a2e-8d13-4b7a-b0e9-1a2c3d4e5f60",
    "userId": "customer_1042",
    "usage": { "credits": 1 }
  }
}
FieldTypeDescription
finishReasonstringstop when the answer is complete, tool-calls when the agent is waiting for a client action result, error when generation failed.
messageMetadata.messageIdstringThe answer's id. Pass it to the retry endpoint to regenerate this answer.
messageMetadata.conversationIdstringThe conversation's id. Send it with your next message.
messageMetadata.userMessageIdstringThe customer message this answer replies to.
messageMetadata.userIdstring | nullThe conversation's userId, or null.
messageMetadata.usage.creditsnumberMessage credits this answer used.

The stream ends with data: [DONE].

Code Examples

JavaScript
const response = await fetch(
  "https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat",
  {
    method: "POST",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      message: "Where is my order?",
      // conversationId: "fd5ae9e1-...", // continue a conversation
      // userId: "customer_1042",         // name the customer on a new one
    }),
  }
);

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let conversationId;

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const events = buffer.split("\n\n");
  buffer = events.pop();

  for (const chunk of events) {
    if (!chunk.startsWith("data: ")) continue;
    const data = chunk.slice("data: ".length);
    if (data === "[DONE]") continue;
    const event = JSON.parse(data);

    switch (event.type) {
      case "text-delta":
        process.stdout.write(event.delta);
        break;
      case "tool-input-available":
        console.log("\nAction called:", event.toolName, event.input);
        break;
      case "finish":
        conversationId = event.messageMetadata.conversationId;
        console.log("\nFinish reason:", event.finishReason);
        console.log("Credits used:", event.messageMetadata.usage.credits);
        break;
      case "error":
        console.error("Stream error:", event.errorText);
        break;
    }
  }
}
Python
import json
import requests

response = requests.post(
    "https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat",
    headers={
        "Authorization": "Bearer YOUR_API_KEY",
        "Content-Type": "application/json",
    },
    json={
        "message": "Where is my order?",
        # "conversationId": "fd5ae9e1-...",  # continue a conversation
        # "userId": "customer_1042",          # name the customer on a new one
    },
    stream=True,
)

conversation_id = None
for line in response.iter_lines():
    if not line or not line.startswith(b"data: "):
        continue
    data = line[len(b"data: "):].decode()
    if data == "[DONE]":
        break
    event = json.loads(data)
    if event["type"] == "text-delta":
        print(event["delta"], end="", flush=True)
    elif event["type"] == "tool-input-available":
        print(f"\nAction called: {event['toolName']}", event["input"])
    elif event["type"] == "finish":
        metadata = event["messageMetadata"]
        conversation_id = metadata["conversationId"]
        print(f"\nFinish reason: {event['finishReason']}")
        print(f"Credits used: {metadata['usage']['credits']}")
    elif event["type"] == "error":
        print(f"Stream error: {event['errorText']}")

Non-Streaming Mode

With "stream": false, the API waits until the answer is complete and returns it as one JSON object:

JSON
{
  "data": {
    "id": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10",
    "role": "assistant",
    "parts": [
      { "type": "text", "text": "Your order shipped on Monday with UPS and should arrive by Friday." }
    ],
    "metadata": {
      "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3",
      "userMessageId": "0c4f6a2e-8d13-4b7a-b0e9-1a2c3d4e5f60",
      "userId": "customer_1042",
      "finishReason": "stop",
      "usage": { "credits": 1 }
    }
  }
}

Explore the documentation