AIDiscount优汇智
Home / Blog

How to Stream AI API Responses in Python and Node.js

How token streaming works over an OpenAI-compatible API, with working Python and Node.js code for server-sent events, and how to handle a dropped connection.

2026-11-25 · 3 min read · AIDiscount team

StreamingPythonNode.jsAPI

Streaming sends a model's answer as it is generated, instead of waiting for the full response. The app can show words as they arrive, like a chat interface typing them out. It also lets long answers start rendering immediately instead of waiting until the whole thing is done.

How it works

A normal API call returns one JSON object after the model finishes. A streaming call keeps the HTTP connection open and sends a sequence of small events using server-sent events (SSE): each event is a line starting with data: , followed by a JSON chunk, ending with a line data: [DONE]. Every chunk carries a small piece of the answer (a "delta"), not the full text so far, so your code appends each piece to a buffer.

To turn streaming on with an OpenAI-compatible API, set "stream": true in the request body.

Python with the OpenAI SDK

from openai import OpenAI

client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])

stream = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": "Write a short poem about rivers."}],
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

Python with raw SSE (no SDK)

import json, os, requests

with requests.post(
    "https://aidiscount.ai/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['AIDISCOUNT_API_KEY']}"},
    json={"model": "gpt-6-luna", "stream": True,
          "messages": [{"role": "user", "content": "Write a short poem about rivers."}]},
    stream=True, timeout=120,
) as r:
    r.raise_for_status()
    for line in r.iter_lines():
        if not line or not line.startswith(b"data: "):
            continue
        payload = line[len(b"data: "):]
        if payload == b"[DONE]":
            break
        delta = json.loads(payload)["choices"][0]["delta"].get("content")
        if delta:
            print(delta, end="", flush=True)

Node.js with the OpenAI SDK

import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://aidiscount.ai/v1", apiKey: process.env.AIDISCOUNT_API_KEY });

const stream = await client.chat.completions.create({
  model: "gpt-6-luna",
  messages: [{ role: "user", content: "Write a short poem about rivers." }],
  stream: true,
});
for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
}

Node.js with fetch (no SDK)

const res = await fetch("https://aidiscount.ai/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIDISCOUNT_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-6-luna",
    stream: true,
    messages: [{ role: "user", content: "Write a short poem about rivers." }],
  }),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buf += decoder.decode(value, { stream: true });
  const lines = buf.split("\n");
  buf = lines.pop();
  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const data = line.slice(6);
    if (data === "[DONE]") continue;
    const delta = JSON.parse(data).choices[0]?.delta?.content;
    if (delta) process.stdout.write(delta);
  }
}

Anthropic Messages format

The event shape is different: each SSE event has a named event: line, and text arrives in content_block_delta events.

import anthropic

client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
with client.messages.stream(
    model="claude-opus-4-8",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a short poem about rivers."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Handling a dropped connection

A streaming request can fail partway through, after some text has already been shown. Tokens generated before the drop are usually still billed, so avoid retrying in a tight loop. In your UI, catch the error, keep whatever text arrived, and show a retry action instead of silently restarting from the beginning. If you do retry, send the same request again; a fresh request starts a fresh stream.

Behind a proxy or load balancer, make sure the connection is not buffered or closed early. Nginx needs proxy_buffering off; for routes that stream, and client timeouts should be long enough for a slow model to finish (streaming responses count as active traffic, not an idle connection, so most clients do not need special timeout handling for them).

Streaming with tool calls

When the model streams a tool call, the function name and arguments arrive in pieces too, split across multiple chunks. Buffer the tool_calls deltas by index and concatenate the arguments string until the stream ends, then parse it as JSON. Most SDKs do this buffering for you.

Try it with AIDiscount. One API key works with OpenAI- and Anthropic-compatible tools. Pay as you go, no monthly fee.
Create a free accountRead the API docs

Related guides

Languages

English · 简体中文 · 繁體中文 · 日本語 · 한국어 · Español · Français · Deutsch · Português · Русский