Zum Inhalt springen
PeakPrivacyDocs
AnwendenVerwaltenEinführenSicherheit & DatenschutzEntwickler

Streaming

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

Als Markdown anzeigen

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). Don't stream batch jobs or JSON extraction: 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 before you stream from them.

Stream a chat completion

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."}]
  }'

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

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.

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].

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 --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."
  }'
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:

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

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

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

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

# 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.")

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.

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

ClientWhat happens
Python SDKRaises openai.APIError. message holds the message, body the inner error object. The trace_id is lost.
JavaScript SDKThrows OpenAI.APIError with message and error. The trace_id is lost.
Raw consumers aboveRaise 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). 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.

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)

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.

See also

Auf dieser Seite