# Streaming (/docs/entwickler/streaming)

> Show the answer while the model writes it, with the event format, complete consumers, errors during a stream and cancelling.

With `"stream": true`, the API sends the answer in small pieces while the model writes it, as Server-Sent Events (SSE). Your users see the first words after a moment instead of waiting for the whole answer.

Stream when a person waits for the answer: chat interfaces, assistants, long drafts. Streaming also helps with long answers, because without it PeakPrivacy waits at most 120 seconds for the model ([Timeouts](/docs/entwickler/errors#timeouts)). Don't stream batch jobs or [JSON extraction](/docs/entwickler/json-output): you need the complete answer before you can use it anyway.

All examples on this page were run against the live API on 11.11.2026.

## Pick a model
The chat completion examples use `mistral-small-swiss` [Schweiz]. It doesn't reason, so its stream carries only answer text, piece by piece.

Reasoning models such as `deepseek-v4-flash`, `glm5`, `gpt-eu` and `gpt-swiss` stream too, but they can mix reasoning and answer in the stream. Read [Reasoning › Streaming](/docs/entwickler/reasoning#streaming) before you stream from them.

## Stream a chat completion

**curl**

```bash
curl --no-buffer https://api.peakprivacy.ch/v1/ai/chat/completions \
  -H "Authorization: Bearer $PEAKPRIVACY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "model": "mistral-small-swiss",
    "stream": true,
    "messages": [{"role": "user", "content": "Write a three-sentence welcome note for Mira, who joins Office Management at Alpenblick Treuhand AG on Monday."}]
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.peakprivacy.ch/v1/ai",
    api_key=os.environ["PEAKPRIVACY_API_KEY"],
)

stream = client.chat.completions.create(
    model="mistral-small-swiss",
    messages=[{"role": "user", "content": "Write a three-sentence welcome note for Mira, who joins Office Management at Alpenblick Treuhand AG on Monday."}],
    stream=True,
)

finish_reason = None
usage = None
for chunk in stream:
    for choice in chunk.choices:
        print(choice.delta.content or "", end="", flush=True)
        finish_reason = choice.finish_reason or finish_reason
    usage = chunk.usage  # the last chunk carries the totals

print()
if finish_reason is None:
    raise RuntimeError("The stream ended early. The answer is incomplete.")
print(f"[{finish_reason}, {usage.total_tokens} tokens]")
```

**JavaScript**

```js
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.peakprivacy.ch/v1/ai",
  apiKey: process.env.PEAKPRIVACY_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "mistral-small-swiss",
  messages: [{ role: "user", content: "Write a three-sentence welcome note for Mira, who joins Office Management at Alpenblick Treuhand AG on Monday." }],
  stream: true,
});

let finishReason = null;
let usage = null;
for await (const chunk of stream) {
  for (const choice of chunk.choices) {
    process.stdout.write(choice.delta.content ?? "");
    finishReason = choice.finish_reason ?? finishReason;
  }
  usage = chunk.usage; // the last chunk carries the totals
}

console.log();
if (!finishReason) throw new Error("The stream ended early. The answer is incomplete.");
console.log(`[${finishReason}, ${usage.total_tokens} tokens]`);
```

The Python and JavaScript versions print the text as it arrives, then the totals:

```text
Welcome to Alpenblick Treuhand AG, Mira! We're excited to have you join our Office Management team and look forward to seeing the fresh ideas and skills you'll bring to the table. Starting Monday, you'll be part of a dynamic environment where teamwork and precision are key to our success.
[stop, 102 tokens]
```

Besides printing, the loop does two things you need in production:

- It checks `finish_reason`. If no chunk set it, the stream broke off and the text is incomplete. The SDKs don't raise an error in that case.
- It keeps the last `usage`. Only the last chunk is sure to hold the totals.

## The event format
### Chat completions
This is the curl output, shortened. Chunks also carry fields such as `logprobs` or `message` that are `null`. Ignore them.

```text
data: {"id":"725d1d45-…","object":"chat.completion.chunk","created":1794395462,"model":"mistral-small-swiss","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}

data: {"id":"5e3c3760-…","object":"chat.completion.chunk","created":1794395462,"model":"mistral-small-swiss","choices":[{"index":0,"delta":{"content":"Welcome to Alpenblick Treuhand AG, Mira! We're excited to"},"finish_reason":null}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}

…

data: {"id":"0c672170-…","object":"chat.completion.chunk","created":1794395463,"model":"mistral-small-swiss","choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}

data: {"id":"6d0f460a-…","object":"chat.completion.chunk","created":1794395463,"model":"mistral-small-swiss","choices":[],"usage":{"completion_tokens":117,"prompt_tokens":40,"total_tokens":157}}

data: [DONE]
```

- Each event is one `data:` line followed by a blank line.
- The first chunk sets `delta.role` to `assistant`. Text follows in `choices[].delta.content`, and one chunk can hold several words.
- The chunk that ends the text has `finish_reason`, for example `stop` or `length`.
- A last chunk with an empty `choices` array carries the final `usage`. `data: [DONE]` closes a complete stream.
- Every chunk has `usage`. Before the last chunk it shows zeros or a running count, depending on the model. `qwen-3-fast`, for example, counts up.
- `id` changes from chunk to chunk, so don't use it to group chunks.
- `ß` in the text is replaced by `ss`, as in non-streamed answers.

### Responses
On `POST /v1/ai/responses`, each event has an `event:` line with its type and a `data:` line with the event object. Text arrives in `response.output_text.delta` events. `response.completed` ends the stream and carries the full response with `usage`. There is no `data: [DONE]`.

```text
event: response.created
data: {"response":{"id":"resp_b44d33f7d2a64bc7",…,"model":"qwen-3-fast","status":"in_progress",…},"sequence_number":0,"type":"response.created"}

event: response.output_text.delta
data: {"content_index":0,"delta":"Z","item_id":"…","output_index":0,"sequence_number":4,"type":"response.output_text.delta"}

event: response.output_text.delta
data: {"content_index":0,"delta":"ür","item_id":"…","output_index":0,"sequence_number":5,"type":"response.output_text.delta"}

…

event: response.completed
data: {"response":{"id":"resp_b44d33f7d2a64bc7",…,"status":"completed","usage":{"input_tokens":17,"output_tokens":11,"total_tokens":28,…}},"sequence_number":17,"type":"response.completed"}
```

Between these, the stream also sends `response.in_progress`, `response.output_item.added`, `response.content_part.added` and the matching `….done` events. Reasoning models add `response.reasoning_text.delta` events. Read only the types you need.

The Swiss models that support `/responses` are reasoning models, so this example uses `qwen-3-fast` [EU].

**curl**

```bash
curl --no-buffer https://api.peakprivacy.ch/v1/ai/responses \
  -H "Authorization: Bearer $PEAKPRIVACY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "model": "qwen-3-fast",
    "stream": true,
    "input": "Name three Swiss cantons, comma-separated."
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.peakprivacy.ch/v1/ai",
    api_key=os.environ["PEAKPRIVACY_API_KEY"],
)

stream = client.responses.create(
    model="qwen-3-fast",
    input="Name three Swiss cantons, comma-separated.",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
    elif event.type == "response.completed":
        print(f"\n[{event.response.usage.total_tokens} tokens]")
```

**JavaScript**

```js
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.peakprivacy.ch/v1/ai",
  apiKey: process.env.PEAKPRIVACY_API_KEY,
});

const stream = await client.responses.create({
  model: "qwen-3-fast",
  input: "Name three Swiss cantons, comma-separated.",
  stream: true,
});

for await (const event of stream) {
  if (event.type === "response.output_text.delta") {
    process.stdout.write(event.delta);
  } else if (event.type === "response.completed") {
    console.log(`\n[${event.response.usage.total_tokens} tokens]`);
  }
}
```

```text
Zürich, Bern, Geneva
[25 tokens]
```

## Without an SDK
Any HTTP client that reads the body as it arrives can consume the stream. A correct consumer:

1. Checks the HTTP status first. Errors found before the first chunk come back as a normal JSON response with a `4xx` or `5xx` status.

2. Splits the body into events at blank lines and reads the `event:` and `data:` lines of each.

3. Stops at `data: [DONE]`, or after the `response.completed` event on `/responses`, and treats an `error` event as a failure.

4. Treats a body that ends before either of them as incomplete.

**Python (httpx)**

```python
# pip install httpx
import json
import os

import httpx

URL = "https://api.peakprivacy.ch/v1/ai/chat/completions"
HEADERS = {
    "Authorization": f"Bearer {os.environ['PEAKPRIVACY_API_KEY']}",
    "Accept": "application/json",
}
BODY = {
    "model": "mistral-small-swiss",
    "stream": True,
    "messages": [{"role": "user", "content": "Write a three-sentence welcome note for Mira, who joins Office Management at Alpenblick Treuhand AG on Monday."}],
}

done = False
with httpx.stream("POST", URL, headers=HEADERS, json=BODY, timeout=180) as response:
    if response.status_code != 200:
        # Errors before the first chunk are normal JSON responses.
        raise RuntimeError(f"{response.status_code}: {response.read().decode()}")

    event = "message"
    for line in response.iter_lines():
        if line == "":
            event = "message"  # a blank line ends the event
        elif line.startswith("event:"):
            event = line[6:].strip()
        elif line.startswith("data:"):
            data = line[5:].strip()
            if data == "[DONE]":
                done = True
                break
            payload = json.loads(data)
            if event == "error":
                error = payload["error"]
                raise RuntimeError(f"{error['type']}: {error['message']} (trace_id {payload['trace_id']})")
            for choice in payload["choices"]:
                print(choice["delta"].get("content") or "", end="", flush=True)

print()
if not done:
    raise RuntimeError("The stream ended without [DONE]. The answer is incomplete.")
```

**JavaScript (fetch)**

```js
// Node.js 18+, run as an ES module
const response = await fetch("https://api.peakprivacy.ch/v1/ai/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PEAKPRIVACY_API_KEY}`,
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  body: JSON.stringify({
    model: "mistral-small-swiss",
    stream: true,
    messages: [{ role: "user", content: "Write a three-sentence welcome note for Mira, who joins Office Management at Alpenblick Treuhand AG on Monday." }],
  }),
});
if (!response.ok) {
  // Errors before the first chunk are normal JSON responses.
  throw new Error(`${response.status}: ${await response.text()}`);
}

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

while (!done) {
  const { value, done: closed } = await reader.read();
  if (closed) break;
  buffer += decoder.decode(value, { stream: true });

  // A blank line ends each event.
  let end;
  while (!done && (end = buffer.indexOf("\n\n")) !== -1) {
    const block = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);

    let event = "message";
    let data = "";
    for (const line of block.split("\n")) {
      if (line.startsWith("event:")) event = line.slice(6).trim();
      if (line.startsWith("data:")) data += line.slice(5).trim();
    }
    if (data === "[DONE]") {
      done = true;
    } else if (data) {
      const payload = JSON.parse(data);
      if (event === "error") {
        const { type, message } = payload.error;
        throw new Error(`${type}: ${message} (trace_id ${payload.trace_id})`);
      }
      for (const choice of payload.choices) process.stdout.write(choice.delta.content ?? "");
    }
  }
}

console.log();
if (!done) throw new Error("The stream ended without [DONE]. The answer is incomplete.");
```

## Errors during a stream
Once the first chunk is out, the HTTP status is already `200`. A later failure arrives as an `error` event, and the stream ends. The event and its `type` values are described in [Errors during a stream](/docs/entwickler/errors#streaming).

We checked how each client reports such an event with a simulated stream:

| Client | What happens |
|---|---|
| Python SDK | Raises `openai.APIError`. `message` holds the message, `body` the inner `error` object. The `trace_id` is lost. |
| JavaScript SDK | Throws `OpenAI.APIError` with `message` and `error`. The `trace_id` is lost. |
| Raw consumers above | Raise an error with type, message and `trace_id`. |

The text you received before the error is incomplete. Discard it or mark it as cut off, then send the request again ([Retries](/docs/entwickler/errors#retry)). If you need the `trace_id` to report a problem, use a raw consumer.

A stream that simply stops, for example after a network failure, sends no `error` event, and the SDK loops end without an error. That is why the examples check `finish_reason` or `[DONE]`.

## Cancel a stream
Stop reading when the user clicks Stop or you have what you need. Closing the connection ends the transfer. A cancelled stream sends no final `usage`.

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.peakprivacy.ch/v1/ai",
    api_key=os.environ["PEAKPRIVACY_API_KEY"],
)

text = ""
with client.chat.completions.create(
    model="mistral-small-swiss",
    messages=[{"role": "user", "content": "List twenty tips for a tidy shared drive."}],
    stream=True,
) as stream:
    for chunk in stream:
        for choice in chunk.choices:
            text += choice.delta.content or ""
        if len(text) > 200:
            break  # leaving the with block closes the connection

print(text)
```

**JavaScript**

```js
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.peakprivacy.ch/v1/ai",
  apiKey: process.env.PEAKPRIVACY_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "mistral-small-swiss",
  messages: [{ role: "user", content: "List twenty tips for a tidy shared drive." }],
  stream: true,
});

// Stop from elsewhere, for example a "Stop" button. Here: after two seconds.
const timer = setTimeout(() => stream.controller.abort(), 2000);

let text = "";
for await (const chunk of stream) {
  text += chunk.choices[0]?.delta?.content ?? "";
  if (text.length > 5000) break; // or stop the loop yourself
}
clearTimeout(timer);

// abort() and break both end the loop without an error.
console.log(stream.controller.signal.aborted ? "[stopped]" : "[complete]", text.length, "characters");
```

In Python, use the `with` block or call `stream.close()`. A plain `break` can leave the connection open. With `fetch`, pass the `signal` of an `AbortController` and call `abort()`. The pending `reader.read()` then rejects with an `AbortError`.

## Anonymisation turns streaming off
A request with `"anonymize": true` never streams. You get one JSON chat completion, even with `"stream": true`.

> **Known limitation:** an SDK call with `stream` and `anonymize` together returns no chunks and raises no error, so your application shows an empty answer. **Workaround:** send anonymised requests without `stream` and show the answer once it is complete. See [Anonymisation › Limits](/docs/entwickler/anonymisation#limits).

## See also
- [Chat completions › Streaming](/docs/entwickler/chat-completions#streaming)
- [Errors and limits](/docs/entwickler/errors#streaming)
- [Conversations and system prompts](/docs/entwickler/conversations)
- [Reasoning › Streaming](/docs/entwickler/reasoning#streaming)
