# Chat Completions streaming responses

Source: [Chat Completions streaming responses](<https://docs.gptunnel.ru/en/api/chat-completions/streaming/>)

<a id="_top"></a>
Pass [`stream: true`](<https://docs.gptunnel.ru/en/api/chat-completions/#chat-request-stream>) in `POST /v1/chat/completions`. The server opens a `text/event-stream` stream. You can show the first text before generation finishes.

<a id="open-the-stream"></a>
## Open the stream

Set `GPTUNNEL_API_KEY` and run one of the examples. Each prints raw SSE events. The cURL flag `--no-buffer` lets you see an event as soon as it arrives.

<a id="tab-panel-0-0"></a>
**Python**

```python
import json
import os
from urllib.request import Request, urlopen

body = {
    'model': "gpt-6-luna",
    'messages': [{"role":"user","content":"What's 2 + 2? Answer with a digit."}],
    'max_completion_tokens': 128,
    'stream': True,
}
request = Request(
    'https://gptunnel.ru/v1/chat/completions',
    method='POST',
    headers={
        'Authorization': os.environ['GPTUNNEL_API_KEY'],
        'Content-Type': 'application/json',
    },
    data=json.dumps(body).encode('utf-8'),
)
with urlopen(request, timeout=30) as response:
    for line in response:
        print(line.decode('utf-8'), end='', flush=True)
```

<a id="tab-panel-0-1"></a>
**cURL**

```bash
curl --fail-with-body --silent --show-error --no-buffer \
  --url 'https://gptunnel.ru/v1/chat/completions' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --json '{
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "What'\''s 2 + 2? Answer with a digit."
    }
  ],
  "max_completion_tokens": 128,
  "stream": true
}'
```

<a id="tab-panel-0-2"></a>
**JavaScript (Node.js)**

```javascript
const apiKey = process.env.GPTUNNEL_API_KEY
if (!apiKey) throw new Error("Set GPTUNNEL_API_KEY")

const response = await fetch('https://gptunnel.ru/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: apiKey,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  "model": "gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "What's 2 + 2? Answer with a digit."
    }
  ],
  "max_completion_tokens": 128,
  "stream": true
}),
})

if (!response.ok) throw new Error(await response.text())
for await (const chunk of response.body) process.stdout.write(chunk)
```

<a id="read-text-and-usage"></a>
## Read text and usage

In the verified response from `gpt-6-luna`, the first event contained the digit `4`. The second reported the finish reason and usage. The example shows these fields and the end-of-stream marker.

```text
data: {"choices":[{"index":0,"delta":{"content":"4"},"finish_reason":null}]}

data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":19,"total_tokens":39,"total_cost":0.0023}}

data: [DONE]
```

- Append `delta.content` to the response for the matching `choices[].index` when the event carries text.
- Keep the last non-empty `usage`. The contents of `choices` and the placement of usage data can vary. In a separate request with [`stream_options`](<https://docs.gptunnel.ru/en/api/chat-completions/#chat-request-stream_options>) set to `{"include_usage": true}`, usage also arrived with `finish_reason: "stop"`.
- `data: [DONE]` closes the stream. Before treating the answer as complete, check earlier events for `error` and check `finish_reason`. For example, `tool_calls` means the model requested a tool.

<a id="parse-the-stream-in-python"></a>
### Parse the stream in Python

A blank line ends an SSE event. A network chunk can end in the middle of a UTF-8 character. The script reads lines and accumulates `data:` fields until it reaches a blank line, then parses the JSON. It prints the first choice’s text to stdout and the final `usage` to stderr.

Save the cURL example above to `request.sh` and the following code to `read-chat-stream.py` , then run `sh request.sh | python3 read-chat-stream.py` (Python 3.9 or later).

```python
import json
import sys
from io import TextIOWrapper


STREAM_ERROR = "Stream error"
EARLY_EOF = "Connection closed before [DONE]"
INCOMPLETE_RESPONSE = "Incomplete response"

def read_reply(lines):
    data = []
    usage = None
    for line in lines:
        line = line.rstrip("\r\n")
        if line.startswith("data:"):
            data.append(line[5:].removeprefix(" "))
        if line or not data:
            continue

        payload = "\n".join(data)
        data.clear()
        if payload == "[DONE]":
            return usage

        frame = json.loads(payload)
        if "error" in frame:
            error = frame["error"]
            message = error.get("message") if isinstance(error, dict) else error
            raise RuntimeError(message or STREAM_ERROR)
        if frame.get("usage"):
            usage = frame["usage"]
        for choice in frame.get("choices", []):
            if choice["index"] == 0:
                print(choice.get("delta", {}).get("content") or "", end="", flush=True)

    raise EOFError(EARLY_EOF)


if __name__ == "__main__":
    try:
        usage = read_reply(TextIOWrapper(sys.stdin.buffer, encoding="utf-8-sig"))
    except (EOFError, OSError, ValueError, RuntimeError) as error:
        sys.exit(f"{INCOMPLETE_RESPONSE}: {error}")
    print()
    if usage:
        print(json.dumps(usage), file=sys.stderr)
```

<a id="handle-a-tool-call"></a>
## Handle a tool call

In the same request, replace the body with the example below. The `gpt-6-luna` model returned a call to `show_sum` and sent the arguments across multiple events.

```json
{
  "model": "gpt-6-luna",
  "messages": [{"role": "user", "content": "Вызови show_sum для суммы 2 и 2."}],
  "max_completion_tokens": 128,
  "stream": true,
  "stream_options": {"include_usage": true},
  "tools": [{
    "type": "function",
    "function": {
      "name": "show_sum",
      "description": "Передать результат сложения.",
      "parameters": {
        "type": "object",
        "properties": {"sum": {"type": "integer"}},
        "required": ["sum"],
        "additionalProperties": false
      }
    }
  }],
  "tool_choice": {"type": "function", "function": {"name": "show_sum"}}
}
```

Group the `choices[].delta.tool_calls[]` entries by choice index and tool call index. Save the returned `id` and `function.name`, then concatenate the `function.arguments` fragments in order. This example produces `{"sum":4}`, and the model ends the response with `finish_reason: "tool_calls"`. When the stream finishes normally, parse the string as JSON, validate the tool name and arguments against the schema, and call the matching function in your application.

<a id="if-the-stream-is-interrupted"></a>
## If the stream is interrupted

| What happened | What to do |
| --- | --- |
| The request returned an HTTP error before the stream started | Read the error body and look up the cause in [API troubleshooting](<https://docs.gptunnel.ru/en/getting-started/api-errors/>). |
| HTTP `200` was followed by an event containing `error` | Keep the text already shown and mark it as incomplete. The `[DONE]` marker can arrive after an error. |
| The connection closed before `[DONE]` | Mark the answer as incomplete. If the client retries, process the new response separately from the beginning. |

The [Anthropic Messages](<https://docs.gptunnel.ru/en/api/anthropic-messages/>) format has its own event types. A normal stream in that format ends with the event `message_stop`.
