Prompt Engineering & LLM Optimization for Developers · 课时

向用户流式传输 LLM 响应

实时向用户传递令牌。学习流式传输的工作原理、它为何能改善感知延迟,以及如何在代码中使用流式完成结果。

第 4 / 4 课13 个步骤

向用户流式传输 LLM 响应 是 CoddyKit 上的免费 Prompt Engineering & LLM Optimization for Developers 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Prompt Engineering & LLM Optimization for Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Prompt Engineering & LLM Optimization for Developers 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Stream?

By default an LLM call returns the entire response only after generation finishes. For long answers this feels slow.

Streaming sends tokens as they are produced, so the user sees text appear word-by-word — drastically improving perceived responsiveness.

Time to First Token

Two latency numbers matter:

  • TTFT (time to first token): how long until the first word appears
  • Total time: until the full answer is ready

Streaming barely changes total time but makes TTFT the number your users actually feel.

Server-Sent Events

Most LLM APIs stream over Server-Sent Events (SSE): a long-lived HTTP response where each chunk is a small JSON event prefixed with data:.

The stream ends with a special [DONE] marker.

Enabling Streaming

You opt in by setting a flag on the request. The API then returns an iterable stream instead of a single object.

const stream = await client.chat.completions.create({
  model: "gpt-4o-mini",
  messages: messages,
  stream: true
});

Reading Chunks

Each chunk carries a delta — the new piece of text. You concatenate deltas to rebuild the full message.

let full = "";
for await (const chunk of stream) {
  const piece = chunk.choices[0].delta.content || "";
  full += piece;
  process.stdout.write(piece);
}

Updating the UI

On the frontend you append each delta to the visible message. A simple approach: keep state and re-render on every token.

function onToken(token, setText) {
  setText(prev => prev + token);
}

Handling the Done Signal

When the stream closes, finalize: stop the typing indicator, persist the full message, and re-enable the input box.

stream.on("end", () => {
  saveMessage(full);
  hideTypingIndicator();
});

Errors Mid-Stream

A stream can fail halfway. Always wrap consumption in try/catch and show whatever partial text you already received rather than discarding it.

try {
  for await (const c of stream) { /* ... */ }
} catch (e) {
  showPartial(full);
  reportError(e);
}

Cancellation

Users may want to stop a long answer. Pass an AbortController signal so you can cancel the request and free server resources.

const controller = new AbortController();
client.chat.completions.create({ ...opts, signal: controller.signal });
// later
controller.abort();

Streaming with Tools

When the model is calling a function, tool-call arguments also arrive as deltas. Buffer them until the call is complete before executing the tool.

Cost & Token Counting

Streaming does not change cost — you still pay per token. To count usage, sum the tokens you received, or request a final usage event if the API supports it.

Quick Check

Test your streaming knowledge.

Recap

You learned to stream LLM responses: opt in with a stream flag, read incremental delta chunks over SSE, update the UI per token, handle the done signal, manage errors and cancellation, and remember streaming improves perceived latency without changing cost.

免费开始

用 AI 导师学习 Prompt Engineering & LLM Optimization for Developers — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「向用户流式传输 LLM 响应」课时是免费的吗?

是的 — 「向用户流式传输 LLM 响应」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Prompt Engineering & LLM Optimization for Developers 课程的其余内容,请升级到 CoddyKit PRO。 Prompt Engineering & LLM Optimization for Developers 课程共包含 4 节课。

「向用户流式传输 LLM 响应」这节课中我会学到什么?

实时向用户传递令牌。学习流式传输的工作原理、它为何能改善感知延迟,以及如何在代码中使用流式完成结果。 你通过在浏览器中直接运行的动手代码来练习 Prompt Engineering & LLM Optimization for Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Prompt Engineering & LLM Optimization for Developers 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Prompt Engineering & LLM Optimization for Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「向用户流式传输 LLM 响应」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Prompt Engineering & LLM Optimization for Developers 课中编写并运行代码吗?

能。每节 Prompt Engineering & LLM Optimization for Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 检索增强生成(RAG)
  2. 函数调用与工具使用
  3. 构建简单的 LLM 智能体
  4. 向用户流式传输 LLM 响应
← 返回 Prompt Engineering & LLM Optimization for Developers