Create

Sign in to ReadmeX

or

How we handle your data: Privacy Policy

ReadmeX

Your AI reading companion

What would you like to catch up on?

Pick a briefing, or ask your own question.

Your community and people briefings stay personal to you.

Story

Robust LLM API streaming with Server-Sent Events

AI summary

An engineering guide explains how to consume large-language-model streaming APIs over Server-Sent Events. It describes a provider-style text/event-stream format in which frames are separated by blank lines and may be split across network reads. A runnable httpx example demonstrates buffered frame parsing, incremental UTF-8 decoding, retries only before any output is emitted, explicit connection closure on cancellation, and separate measurement of time to first token and total generation time. The guide warns that retrying after output has begun can duplicate visible content, while stopping reads without closing the connection may leave upstream generation and billing active. Its schema and behaviors are implementation guidance and are not verified as compatible with every LLM API provider.

In-depth insight

The report connects common streaming failures—garbled text, duplicated output, and continued token generation after interruption—to concrete safeguards involving buffering, incremental decoding, retry boundaries, and explicit connection closure.

接大模型接口时,把 stream=True 加上去只是第一步。

真正耗时间的是后面这些事:输出偶尔出现乱码、网络抖一下重试后内容重复了、用户点了停止但后台还在计费。

这些问题的根源都在同一个地方——流式响应返回的不再是一个完整的 JSON,而是一串被网络任意切分的事件。客户端要自己把它拼回去。

下面按「报文结构 → 三个坑 → 可运行的实现」来讲。

一、流式响应到底返回了什么

流式接口用的是 SSE(Server-Sent Events)。响应的 Content-Type 是 text/event-stream,body 是一串以空行分隔的帧:

#HTTPX

Original · 8 min readRead the original
Group chat

No comments yet. Start the conversation.