# 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 | Field | Type | Required | Description | | - | - | - | - | | `message` | `string` | Yes, unless `conversationId` is sent | The customer's message. Leave it out to let the agent continue after you submit a [client action](/docs/api-reference/v2/client-actions) result. | | `stream` | `boolean` | No | Stream the reply as Server-Sent Events. Defaults to `true`. | | `conversationId` | `string` | No | Continue this conversation. Leave it out to start a new one. | | `userId` | `string` | No | Your 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. > [!NOTE] > > A conversation's `userId` is fixed when the conversation starts. See [User Conversations](/docs/api-reference/v2/user-conversations). 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]`: ``` 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 > [tab] Text Events > > #### `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" } > ``` > [tab] Action Events > > The agent can run [actions](/docs/user-guides/chatbot/actions/actions-overview) while it answers. Each action call shows up as these events; `toolName` is the action's name. > > #### `tool-input-start` > > An action call begins. > > ```json > { "type": "tool-input-start", "toolCallId": "a7c4e9d2-3b1f-4a68-8e5c-0f9d2b6a1c37", "toolName": "lookup_order" } > ``` > > #### `tool-input-available` > > The call's complete input. It arrives right after `tool-input-start`; there are no partial input events. > > ```json > { "type": "tool-input-available", "toolCallId": "a7c4e9d2-3b1f-4a68-8e5c-0f9d2b6a1c37", "toolName": "lookup_order", "input": { "orderNumber": "1042" } } > ``` > > #### `tool-output-available` > > The action's result, for actions QwryAI runs itself. > > ```json > { "type": "tool-output-available", "toolCallId": "a7c4e9d2-3b1f-4a68-8e5c-0f9d2b6a1c37", "output": { "status": "shipped", "carrier": "UPS" } } > ``` > > > [!NOTE] > > > > A [client action](/docs/api-reference/v2/client-actions) has no `tool-output-available`: your app runs it, and the stream finishes with `finishReason: "tool-calls"`. > [tab] Step & Completion Events > > #### `start-step` > > A processing step begins. A new step starts after each action call. > > ```json > { "type": "start-step" } > ``` > > #### `finish-step` > > The step is complete. > > ```json > { "type": "finish-step" } > ``` > > #### `finish` > > Sent once, last before `[DONE]`. Carries why the agent stopped and the answer's metadata. See [Metadata](#metadata). > > ```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 } > } > } > ``` > > #### `error` > > Something went wrong after the stream started. Part of the answer may already have arrived. A `finish` with `finishReason: "error"` and `[DONE]` follow. > > ```json > { "type": "error", "errorText": "Something went wrong, please try again" } > ``` ## 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 } } } ``` | Field | Type | Description | | - | - | - | | `finishReason` | `string` | `stop` when the answer is complete, `tool-calls` when the agent is waiting for a [client action](/docs/api-reference/v2/client-actions) result, `error` when generation failed. | | `messageMetadata.messageId` | `string` | The answer's id. Pass it to the retry endpoint to regenerate this answer. | | `messageMetadata.conversationId` | `string` | The conversation's id. Send it with your next message. | | `messageMetadata.userMessageId` | `string` | The customer message this answer replies to. | | `messageMetadata.userId` | `string \| null` | The conversation's `userId`, or `null`. | | `messageMetadata.usage.credits` | `number` | Message credits this answer used. | The stream ends with `data: [DONE]`. > [!WARNING] > > An answer that isn't finished after 10 minutes ends with an `error` event reading `Response deadline exceeded`. ## 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']}") ``` > [!TIP] > > If the request fails before the stream starts, for example with a bad key or an empty `message`, you get an ordinary JSON error with an HTTP status instead of a stream. Check `response.ok` before reading events. See [Error Handling](/docs/api-reference/v2/error-handling). ## Non-Streaming Mode With `"stream": false`, the API waits until the answer is complete and returns it as one JSON object: > [tab] Text Response > > ```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 } > } > } > } > ``` > [tab] Action Response > > When the agent ran actions, `parts` lists each call and, for actions QwryAI ran, its result. A client action leaves a `tool-call` part with no result and `finishReason: "tool-calls"`: > > ```json > { > "data": { > "id": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10", > "role": "assistant", > "parts": [ > { "type": "text", "text": "Let me look at your cart." }, > { "type": "tool-call", "toolCallId": "a7c4e9d2-3b1f-4a68-8e5c-0f9d2b6a1c37", "toolName": "get_cart", "input": {} } > ], > "metadata": { > "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3", > "userMessageId": "0c4f6a2e-8d13-4b7a-b0e9-1a2c3d4e5f60", > "userId": "customer_1042", > "finishReason": "tool-calls", > "usage": { "credits": 1 } > } > } > } > ``` > > See [Client Actions](/docs/api-reference/v2/client-actions) for how to return the result and continue.