Chat Completions streaming responses
Pass stream: true in
POST /v1/chat/completions. The server opens a text/event-stream stream. You can show the first text before generation finishes.
Open the stream
Section titled “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.
import jsonimport osfrom 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)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}'const apiKey = process.env.GPTUNNEL_API_KEYif (!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)Read text and usage
Section titled “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.
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.contentto the response for the matchingchoices[].indexwhen the event carries text. - Keep the last non-empty
usage. The contents ofchoicesand the placement of usage data can vary. In a separate request withstream_optionsset to{"include_usage": true}, usage also arrived withfinish_reason: "stop". data: [DONE]closes the stream. Before treating the answer as complete, check earlier events forerrorand checkfinish_reason. For example,tool_callsmeans the model requested a tool.
Parse the stream in Python
Section titled “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).
import jsonimport sysfrom 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)Handle a tool call
Section titled “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.
{ "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.
If the stream is interrupted
Section titled “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. |
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 format has its own event types. A normal stream in that format ends with the event message_stop.