How LLM APIs Implement Streaming Output: A Practical Guide to Python Streaming and SSE

Streaming output is an important interaction method for AI chatbots, intelligent customer service, and AI Agent applications. This article uses Python code examples to introduce LLM API streaming calls, SSE data transfer, response processing, and common issues in production environments.

llm-api-streaming-python-sse

Key takeaways

  • Streaming output principle: LLMs return generated content incrementally through streaming responses. A common implementation uses the SSE protocol, which reduces the time users wait for the first chunk of content.
  • Python practical integration: Use an OpenAI-compatible SDK with stream=True to receive content in real time, concatenate the full response, and track token usage statistics.

How LLM APIs Implement Streaming Output: A Practical Guide to Python Streaming and SSE

When developing AI chatbots, intelligent customer service, or AI Agent applications, developers often encounter a problem: LLMs may take several seconds or longer to generate a complete response. If users must wait until the full content is generated, the interaction experience is affected.

Streaming output provides a solution better suited to real-time interaction.

Through streaming APIs, applications can receive and display results incrementally as the model generates content, without waiting for the complete response.

This article explains how LLM API streaming output works and uses Python code examples to demonstrate streaming calls, response concatenation, token usage statistics, and exception handling.

01 What Is LLM API Streaming Output?

LLM API streaming output is a data transfer method in which the model service returns incremental content in batches to the client through a persistent connection while generating the response.

Traditional non-streaming calls require waiting for the model to finish generating all content before the client receives the complete response.

Streaming calls allow the client to receive partial content during generation and display it to users in real time.

For example, when a user asks the AI to introduce MaaS, a non-streaming API returns the complete introduction at once, while a streaming API may return multiple text chunks in sequence:

MaaS
(Model as a Service)
是一种通过服务接口
提供 AI 模型能力的方式。

The client can concatenate these chunks in order to form the complete answer.

Note that each data chunk returned in streaming mode does not necessarily correspond to one token; it may contain multiple tokens, empty content, or other event information.

Streaming output mainly improves the response speed perceived by users, and does not mean that the model itself generates content faster.

02 What Is the Difference Between Streaming and Non-Streaming Output?

Comparison dimension

Non-streaming output

Streaming output

Return method

Returns the complete result at once

Continuously returns incremental content

User waiting time

Wait for all content to be generated

Can display content as soon as the first chunk is received

API connection

Ordinary request and response

Persistent connection

Client processing

Relatively simple

Requires handling incremental events

Exception handling

Mainly handles request failures

Also needs to handle generation interruptions

Use cases

Classification, data extraction, batch processing

AI chat, customer service, code assistants

Token billing

Billed according to platform rules

Billed according to platform rules

For applications that need to display the model generation process directly, streaming output usually provides a better interaction experience.

For backend data processing, structured information extraction, and other tasks that do not require real-time display, non-streaming calls may be simpler.

03 What Is SSE? Why Do LLM APIs Often Use SSE?

SSE (Server-Sent Events) is a one-way real-time data transfer mechanism based on HTTP.

The server can send events to the client through a persistent connection without requiring the client to repeatedly issue requests.

A common SSE response type is:

Content-Type: text/event-stream

In OpenAI-compatible Chat Completions APIs that use SSE, the server may return data similar to the following:

data: {"choices":[{"delta":{"content":"Hello"}}]}

data: {"choices":[{"delta":{"content":" World"}}]}

data: [DONE]

After receiving events, the client parses the incremental content and concatenates it into complete text:

Hello World

The above is a simplified example; actual responses may also include fields such as model identifier, role information, finish reason, tool calls, and Token usage.

Event formats may differ across model services; refer to the actual API documentation.

What Are the Differences Between SSE and WebSocket?

Technology

SSE

WebSocket

Communication direction

Unidirectional server-to-client delivery

Bidirectional communication

Underlying protocol

HTTP

WebSocket

Implementation complexity

Relatively low

Relatively high

Typical scenarios

Text streaming generation, event notifications

Real-time voice, bidirectional interaction

For common large language model text generation scenarios, after the client submits a request, it mainly needs to continuously receive content returned by the server, so SSE is a common choice.

For scenarios requiring continuous bidirectional communication, such as real-time voice interaction, WebSocket or other solutions can be evaluated based on the service interface.

04 Python Streaming Call Environment Preparation

First, install the OpenAI Python SDK and an environment variable management tool.

pip install -U openai python-dotenv

Create a file in the project root directory:.env file:

LLM_API_KEY=your_api_key
LLM_BASE_URL=https://your-provider.example/v1
LLM_MODEL=your_model_id

The above are configuration placeholders and need to be replaced with the actual information provided by the model service platform.

If you use the OpenAI-compatible model interface provided by AGTCloud, obtain the corresponding API Key, Base URL, and Model ID from the current development documentation.

Also, add .env to .gitignore, to avoid committing the API Key to public code repositories.

05 Implement Your First Streaming API Request with Python

Create a file:streaming.py file:

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(
    api_key=os.environ["LLM_API_KEY"],
    base_url=os.environ["LLM_BASE_URL"],
    timeout=60.0
)

with client.chat.completions.create(
    model=os.environ["LLM_MODEL"],
    messages=[
        {
            "role": "user",
            "content": "请介绍大模型 API 的三个应用场景。"
        }
    ],
    stream=True
) as stream:

    for chunk in stream:
        if not chunk.choices:
            continue

        content = chunk.choices[0].delta.content

        if content:
            print(content, end="", flush=True)

print()

Run the program:

python streaming.py

If the service platform and model support the corresponding streaming interface, the terminal will gradually display content as the model generates it.

The core parameter of this code is:

stream=True

Unlike regular API calls, the streaming interface returns an iterable response stream.

Developers need to continuously read response events and extract incremental text from delta.content to extract incremental text.

06 How to Save the Complete Streaming Response?

In real business scenarios, developers may not only need to display model output in real time, but may also need to save the complete answer for conversation history, business records, or subsequent processing.

You can collect the text fragments returned each time in a list.

def stream_chat(prompt):
    parts = []

    with client.chat.completions.create(
        model=os.environ["LLM_MODEL"],
        messages=[
            {
                "role": "user",
                "content": prompt
            }
        ],
        stream=True
    ) as stream:

        for chunk in stream:
            if not chunk.choices:
                continue

            content = chunk.choices[0].delta.content

            if content:
                parts.append(content)
                print(content, end="", flush=True)

    print()

    return "".join(parts)

Call the function:

result = stream_chat("什么是 RAG 检索增强生成?")

with open("response.txt", "w", encoding="utf-8") as file:
    file.write(result)

This enables real-time content display and also obtains the complete response after generation finishes normally.

For multi-turn dialogue applications in production environments, user messages, model answers, and generation status should also be saved according to session management logic.

07 How to Count Token Usage for Streaming Output?

Token usage statistics are an important basis for enterprises to manage model costs.

In Chat Completions interfaces that support the corresponding parameter, you can use stream_options to request streaming usage statistics.

with client.chat.completions.create(
    model=os.environ["LLM_MODEL"],
    messages=[
        {
            "role": "user",
            "content": "解释什么是 AI Agent。"
        }
    ],
    stream=True,
    stream_options={
        "include_usage": True
    }
) as stream:

    for chunk in stream:
        if chunk.usage:
            print("\n输入 Token:", chunk.usage.prompt_tokens)
            print("输出 Token:", chunk.usage.completion_tokens)
            print("总 Token:", chunk.usage.total_tokens)

        if chunk.choices:
            content = chunk.choices[0].delta.content

            if content:
                print(content, end="", flush=True)

Note:

  • Not all OpenAI-compatible interfaces support stream_options.

  • Usage statistics may be returned at the end of the streaming response.

  • If the connection is interrupted early, the client may not receive the final usage information.

  • Some models may provide additional statistics fields such as cached Tokens and reasoning Tokens.

Therefore, enterprises should manage costs by combining API responses, platform call logs, and actual billing.

Total Token count cannot be directly equated to call cost, because input, output, and cached Tokens may be priced differently.

08 How to Measure the Response Speed of a Streaming API?

When evaluating streaming API performance, it is not enough to only measure the total request completion time.

The following metrics are recommended for focus.

Performance metric

English name

Meaning

Time to First Token

TTFT

Time from request sent to first Token returned

Time to First Content

Time to First Content

Time from request sent to first displayable content returned

Inter-Token Latency

ITL

Time interval between consecutive output Tokens

Output throughput

Tokens per Second

Number of Tokens generated per unit time

Total response time

End-to-End Latency

Time from request start to response end

Stream completion rate

Stream Completion Rate

Proportion of requests that complete generation normally

For chatbots, Time to First Content directly affects the response speed perceived by users.

For long-form text generation and code generation tasks, Output throughput and Total response time are also very important.

Measure Time to First Content with Python

import time

start = time.perf_counter()
first_content_time = None

with client.chat.completions.create(
    model=os.environ["LLM_MODEL"],
    messages=[
        {
            "role": "user",
            "content": "介绍大模型 API 的工作原理。"
        }
    ],
    stream=True
) as stream:

    for chunk in stream:
        if not chunk.choices:
            continue

        content = chunk.choices[0].delta.content

        if content:
            if first_content_time is None:
                first_content_time = time.perf_counter()

            print(content, end="", flush=True)

end = time.perf_counter()

if first_content_time is not None:
    print(
        "\n首段内容延迟:",
        round(first_content_time - start, 3),
        "秒"
    )

print("总响应时间:", round(end - start, 3), "秒")

This code measures the time when the client receives the first non-empty text content, not the strict first Token generation time on the model server side.

When enterprises compare model performance, they should standardize test environment, input content, output requirements, and statistical methodology, and obtain latency metrics such as P50 and P95 through multiple tests.

09 How to Handle Streaming API Interruptions and Exceptions?

Streaming requests need to maintain a persistent connection, so in addition to ordinary API errors, they may encounter issues such as generation interruption, network connection exceptions, and incomplete responses.

Below is a basic exception handling example.

from openai import (
    APIConnectionError,
    APITimeoutError,
    RateLimitError,
    APIStatusError
)

parts = []
finish_reason = None

try:
    with client.chat.completions.create(
        model=os.environ["LLM_MODEL"],
        messages=[
            {
                "role": "user",
                "content": "介绍 MaaS 平台的主要价值。"
            }
        ],
        stream=True
    ) as stream:

        for chunk in stream:
            if not chunk.choices:
                continue

            choice = chunk.choices[0]

            if choice.delta.content:
                parts.append(choice.delta.content)
                print(
                    choice.delta.content,
                    end="",
                    flush=True
                )

            if choice.finish_reason:
                finish_reason = choice.finish_reason

except RateLimitError:
    print("\n请求受限,请检查额度与限流规则。")

except APITimeoutError:
    print("\n请求超时,生成可能未完成。")

except APIConnectionError:
    print("\n网络连接异常,生成可能中断。")

except APIStatusError as e:
    print("\nAPI 请求失败:", e.status_code)

finally:
    partial_result = "".join(parts)

    print("\n结束原因:", finish_reason)
    print("已接收字符数:", len(partial_result))

For requests that have already returned partial content, unconditional automatic retry is not recommended.

Re-requesting the model may produce a different answer, and may also lead to duplicated content and additional call costs.

Enterprises should design handling mechanisms according to business scenarios:

  • Preserve the partial content already received.

  • Mark whether generation completed normally.

  • Distinguish termination cases such as network exceptions, output length limits, and content filtering.

  • Decide whether to allow retries based on the error type.

  • Prevent AI Agents from repeatedly performing external operations due to duplicate requests.

10 Why does the frontend still display content all at once when Streaming is enabled?

This is a relatively common issue when developing streaming AI applications.

Even if the model API has streaming output enabled, users may still see the result only after generation is complete if intermediate services or the frontend do not correctly handle incremental data.

Common causes include:

Problem

Troubleshooting direction

Backend waits for the complete response

Check whether each incremental chunk is forwarded in real time

Reverse proxy buffering

Check the buffering configuration of Nginx or other proxies

Frontend reads the response all at once

Use a streaming read mechanism instead of waiting for the complete JSON

Output is not flushed in time

Check server-side output and buffers

Connection closes prematurely

Check timeout configuration and connection status

CDN or gateway buffering

Confirm that intermediate services support streaming transmission

A complete streaming application must ensure that model services, application backends, proxy services, and frontend display all correctly handle incremental responses.

Setting only stream=True does not mean the entire application has implemented end-to-end streaming output.

11 Does streaming output increase API call costs?

For text generation interfaces using the same model and the same billing rules, streaming output usually does not increase the Token unit price merely because the response transmission method is different.

However, actual costs may still be affected by the following factors:

  • The number of Tokens actually generated by the model.

  • How the server handles requests after a user cancels.

  • Duplicate requests caused by network interruptions.

  • Failed retries and additional model calls.

  • Application server resource consumption caused by persistent connections.

Therefore, Streaming is primarily a response transmission and interaction method, not a technology that directly reduces model call costs.

Enterprises need to pay attention to user experience, model costs, and application infrastructure costs at the same time.

12 Which AI applications are suitable for streaming output?

Application scenario

Recommended approach

Reason

AI chatbot

Streaming

Improves real-time interaction experience

Intelligent customer service

Streaming

Reduces the time users wait for the first response segment

AI code assistant

Streaming

Displays generated content in real time

Long article generation

Streaming

Users can read part of the content in advance

Batch text classification

Non-streaming

Easier to process results uniformly

Structured information extraction

Usually uses non-streaming

Easier to perform complete JSON validation

AI Agent

Choose based on the task

Needs to balance tool calls and execution status

Image and video generation

Choose based on the model interface

May use an asynchronous task mechanism

Not all AI applications require Streaming.

For backend tasks that do not directly show the generation process to users, non-streaming interfaces often have lower development complexity.

13 How to use streaming APIs through AGTCloud?

AGTCloud provides multi-model API services for developers and enterprises, covering model capabilities such as text, image, video, speech, and 3D.

For text models that support OpenAI-compatible streaming interfaces, developers can complete integration through the following steps:

  1. Obtain the API Key provided by the platform.

  2. Review the model catalog and the corresponding interface documentation.

  3. Configure the Base URL and Model ID.

  4. Use the Python SDK to send a basic request.

  5. Enable streaming output and handle incremental responses.

  6. Test first-segment content latency, complete responses, and exception handling.

Streaming capabilities, parameter support, and response fields may differ across models; during formal integration, follow the platform's current interface documentation.

Visit AGTCloud:https://agtcloud.cn/

Summary

Streaming output is an important technical capability for building real-time AI applications.

With technologies such as the Python SDK and SSE, developers can receive and display results in real time while the model generates content, improving the user interaction experience.

However, streaming applications in production environments not only need to implement basic API calls, but also need to pay attention to response concatenation, first-segment content latency, Token usage statistics, exception handling, and end-to-end data transmission.

For enterprises, streaming or non-streaming calling methods should be chosen according to specific business scenarios, balancing user experience, development complexity, service stability, and usage costs.

Docs ↗

Frequently asked questions

Streaming output means the model returns incremental results to the client as it generates content, rather than waiting until the full response is generated and returning it all at once.

X

Xu Cheng'an

Enterprise AI Solutions

AGTCloud column author on enterprise AI applications, focusing on practical adoption of large models in enterprise business systems, intelligent knowledge bases, AI Agent, and automated workflows. Key research includes model serving architecture, RAG applications, cost control, and enterprise deployment solutions, helping enterprises assess the practical value of AI technologies.