0Pricing
Prompt Engineering & LLM Optimization for Developers · レッスン

LLMレスポンスをユーザーにストリーミングする

トークンをリアルタイムでユーザーに届けます。ストリーミングの仕組み、体感レイテンシが改善する理由、ストリーミングされた補完をコードで利用する方法を学びます。

「LLMレスポンスをユーザーにストリーミングする」はCoddyKit上の無料Prompt Engineering & LLM Optimization for Developersレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.

よくある質問

「LLMレスポンスをユーザーにストリーミングする」レッスンは無料ですか?

はい。「LLMレスポンスをユーザーにストリーミングする」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Prompt Engineering & LLM Optimization for Developersコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Prompt Engineering & LLM Optimization for Developersコースには全4レッスンが含まれています。

「LLMレスポンスをユーザーにストリーミングする」で何を学びますか?

トークンをリアルタイムでユーザーに届けます。ストリーミングの仕組み、体感レイテンシが改善する理由、ストリーミングされた補完をコードで利用する方法を学びます。 ブラウザで直接実行するハンズオンコードでPrompt Engineering & LLM Optimization for Developersを演習し、24時間対応の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. Retrieval Augmented Generation(RAG)
  2. Function Callingとツール利用
  3. シンプルなLLMエージェントの構築
  4. LLMレスポンスをユーザーにストリーミングする
← Prompt Engineering & LLM Optimization for Developersに戻る