# Streaming chat answers over Server-Sent Events

> The chat API's streaming endpoint runs the same pipeline as `/v1/chat/respond` but delivers the answer as Server-Sent Events, so your UI can show progress instead of a spinner. It is a POST, so the browser's `EventSource` cannot call it; you read the stream on your server and relay it.

Source: https://astronode.dev/recipes/streaming-chat-answers · Updated: 2026-12-01

**What you build:** A server-side SSE client that renders the answer progressively and ends with the full structured envelope. (Node.js, Python)

## The event protocol

| Event | Payload | What to do |
| --- | --- | --- |
| (comment) | A `:` line padded to about 2 KB, sent first | Ignore. It exists so proxies flush the stream open immediately. |
| `tool` | `{ name, phase: "start" \| "result", label }` | Optional progress indicator ("Looking at…"). Safe to ignore. |
| `delta` | `{ text }` | Append to the visible answer. |
| `replace` | `{ text }` | A safety rewrite: discard everything shown so far and show this. |
| `done` | `{ envelope }` | The same JSON `/v1/chat/respond` returns: message, tone, follow-ups, reasoning, meta. |
| `error` | `{ code, message }` | Terminal failure after the stream started. |

[`POST /v1/chat/respond/stream`](https://astronode.dev/capabilities/chat/chat-respond-stream) lives on the chat host, `chatbot-api.astronode.dev`, and takes the same body as [`/v1/chat/respond`](https://astronode.dev/capabilities/chat/chat-respond): a `conversation_id`, the `user`'s birth data and the `message`.

## Node: parse frames from fetch

```javascript
// stream-chat.mjs - Node 18+, server-side. Relay these events to your own client.
const CHAT = "https://chatbot-api.astronode.dev";

const res = await fetch(`${CHAT}/v1/chat/respond/stream`, {
  method: "POST",
  headers: {
    authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`,
    "content-type": "application/json",
    accept: "text/event-stream",
  },
  body: JSON.stringify({
    conversation_id: "user-42-main", // reuse it: earlier turns are replayed into the prompt
    user: { date: "1973-04-24", time: "17:25:00", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 },
    message: "What does my 7th house say about partnership?",
  }),
});

// Auth, validation and rate-limit failures arrive BEFORE the stream, as plain JSON.
if (!res.ok) {
  const { error } = await res.json();
  console.log(res.status, error.code, "retry-after:", res.headers.get("retry-after"));
  process.exit(0);
}

let text = "";
let buffer = "";
const decoder = new TextDecoder();
for await (const chunk of res.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);
    if (frame.startsWith(":")) continue; // SSE comment (the opening padding frame)
    const event = frame.match(/^event: (.*)$/m)?.[1];
    const data = JSON.parse(frame.match(/^data: (.*)$/m)?.[1] ?? "null");
    if (event === "tool") console.log(`[tool ${data.phase}] ${data.label}`);
    if (event === "delta") text += data.text; // append and render
    if (event === "replace") text = data.text; // safety rewrite: discard what you showed
    if (event === "error") throw new Error(`${data.code}: ${data.message}`);
    if (event === "done") {
      const { response, meta } = data.envelope;
      console.log({ chars: text.length, matches_done: text === response.message, tone: response.tone, provider: meta.llm_provider });
    }
  }
}
```

```text
$ node stream-chat.mjs
[tool start] Looking at marriage & partnership
[tool result] Looking at marriage & partnership
{ chars: 67, matches_done: true, tone: 'reflective', provider: 'stub' }
```

Frames are separated by a blank line and can be split across network chunks, so buffer and cut on `\n\n` rather than parsing each chunk. The final check - the concatenated deltas equal `envelope.response.message` - is worth keeping in tests: when it fails, a `replace` was missed.

> **Note:** This output was recorded against the chat API running in memory with a stub model (`provider: "stub"`), so the text is placeholder and arrives as one delta. Event names, their order and the `done` envelope are the production ones. With a live model the answer may arrive in many deltas or in a few large ones, depending on the provider; code that appends deltas handles both.

## Python: line by line with urllib

```python
# stream_chat.py - Python 3.9+, standard library only.
import json, os, urllib.error, urllib.request

CHAT = "https://chatbot-api.astronode.dev"
KEY = os.environ["ASTRONODE_API_KEY"]

body = {
    "conversation_id": "user-42-main",
    "user": {"date": "1973-04-24", "time": "17:25:00", "tz_offset_minutes": 330, "lat": 19.076, "lng": 72.8777},
    "message": "And what about my 10th house?",
}
req = urllib.request.Request(
    CHAT + "/v1/chat/respond/stream",
    data=json.dumps(body).encode(),
    headers={"Authorization": "Bearer " + KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)
try:
    res = urllib.request.urlopen(req, timeout=60)
except urllib.error.HTTPError as e:  # 400/401/429 come back as JSON, never as a stream
    print(e.code, json.load(e)["error"]["code"], "Retry-After:", e.headers.get("Retry-After"))
    raise SystemExit(0)

event, text = None, ""
for raw in res:  # one line at a time, as the server flushes them
    line = raw.decode("utf-8").rstrip("\n")
    if line.startswith(":"):
        continue  # comment / padding frame
    if line.startswith("event: "):
        event = line[7:]
    elif line.startswith("data: "):
        data = json.loads(line[6:])
        if event == "delta":
            text += data["text"]
        elif event == "replace":
            text = data["text"]
        elif event == "done":
            env = data["envelope"]
            print("events ok;", len(text), "chars; conversation", env["conversation_id"], "| provider", env["meta"]["llm_provider"])
```

A Hobby key, then a Free key that has used its 5 messages today:

```text
$ python3 stream_chat.py   # Hobby key
events ok; 67 chars; conversation user-42-main | provider stub

$ python3 stream_chat.py   # Free key
429 QUOTA_EXCEEDED Retry-After: 27815
```

## Errors before and after the first byte

- **Before the stream:** authentication, validation and limits fail as ordinary JSON with a normal status - `401`, `400`, `429`. Check `res.ok` before reading the body as a stream.
- **The Free daily cap** is 5 chat messages per UTC day, shared by `/v1/chat/respond` and the stream. The 429 says `QUOTA_EXCEEDED` with `details.kind: "daily_chat_cap"`, `resets_at` midnight UTC, and `Retry-After` in seconds until then - show a message, do not retry in a loop. Paid plans have no daily cap.
- **After the stream starts** the status is already 200; failures arrive as an `error` event. Close the connection on it and show what you have.
- Reuse `conversation_id` per user thread: the service replays recent turns into the prompt, which is what makes "and my 10th house?" a follow-up.

## Questions

**What do I end up with?**

A server-side SSE client that renders the answer progressively and ends with the full structured envelope. The code is in Node.js and Python.

**Which endpoints does this recipe call, and in what order?**

2 endpoints, in this order: AI Astrologer Chat (Streaming) (`POST /v1/chat/respond/stream`), then AI Astrologer Chat (`POST /v1/chat/respond`).

## Endpoints, in call order

- [`POST /v1/chat/respond/stream`](https://astronode.dev/capabilities/chat/chat-respond-stream) - AI Astrologer Chat (Streaming) API
- [`POST /v1/chat/respond`](https://astronode.dev/capabilities/chat/chat-respond) - AI Astrologer Chat API
