0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · レッスン

AIレスポンスのストリーミング

AIモデルからトークンをリアルタイムにストリーミングし、完全なレスポンスを待たずに回答が段階的に表示されるようにする方法を学びます。

「AIレスポンスのストリーミング」はCoddyKit上の無料AI Powered SaaS: Stripe + Auth + Billing + Deployレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Powered SaaS: Stripe + Auth + Billing + Deploy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Powered SaaS: Stripe + Auth + Billing + Deployコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Why Stream Responses?

Large language models can take several seconds to produce a full answer. Streaming sends tokens to the client as they are generated, so the user sees text appear word by word.

  • Lower perceived latency
  • Users can start reading immediately
  • Feels conversational, like a chat

How Streaming Works

Streaming relies on a long-lived HTTP connection. The server keeps the response open and pushes chunks as they arrive from the model provider.

Two common transports are Server-Sent Events and chunked HTTP responses. Most AI SDKs default to SSE.

Enabling Stream Mode

Most AI APIs accept a stream: true flag. Instead of a single JSON object you receive a sequence of small JSON events, each containing a piece of the answer.

const response = await client.chat.completions.create({
  model: "gpt-4o-mini",
  stream: true,
  messages: [{ role: "user", content: "Explain streaming." }],
});

Reading the Stream on the Server

The SDK returns an async iterable. You loop over it and forward each delta to your client.

for await (const chunk of response) {
  const token = chunk.choices[0].delta.content || "";
  process.stdout.write(token);
}

Forwarding to the Browser with SSE

Wrap each token in an SSE data: frame. Set the right headers so the browser keeps the connection open.

res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
for await (const chunk of aiStream) {
  const t = chunk.choices[0].delta.content || "";
  res.write("data: " + JSON.stringify({ t }) + "\n\n");
}
res.end();

Consuming the Stream in the UI

On the client, use the EventSource API or fetch with a reader. Append each token to your displayed message state.

const es = new EventSource("/api/chat");
es.onmessage = (e) => {
  const { t } = JSON.parse(e.data);
  setMessage((prev) => prev + t);
};

Showing a Typing Indicator

While tokens stream in, show a blinking cursor or animated dots. Remove it once the stream closes. This reinforces the feeling that the AI is actively responding.

Handling Stream Errors

Connections can drop mid-stream. Always handle the error event and close the source. Offer a retry button and keep whatever partial text was already received.

es.onerror = () => {
  es.close();
  showRetry();
};

Cancelling a Stream

Let users stop a long answer. With fetch you abort via an AbortController; with EventSource you call close(). Cancelling also saves token cost.

const controller = new AbortController();
fetch("/api/chat", { signal: controller.signal });
// later:
controller.abort();

Cost and Token Accounting

Streaming does not change billing: you still pay for total tokens generated. Count tokens as they arrive, or read the final usage event some providers send when the stream ends.

Backpressure and Buffering

If the client reads slower than the model produces, tokens queue up. Most runtimes handle this automatically, but for very high throughput consider buffering small batches of tokens before flushing to reduce write overhead.

Quick Check

Test your understanding of streaming AI responses.

Recap

You learned to stream AI responses end to end:

  • Enable stream: true on the API call
  • Iterate over chunks server-side and forward via SSE
  • Append tokens in the UI with a typing indicator
  • Handle errors, cancellation, and token accounting

Streaming makes AI features feel fast and conversational.

よくある質問

「AIレスポンスのストリーミング」レッスンは無料ですか?

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

「AIレスポンスのストリーミング」で何を学びますか?

AIモデルからトークンをリアルタイムにストリーミングし、完全なレスポンスを待たずに回答が段階的に表示されるようにする方法を学びます。 ブラウザで直接実行するハンズオンコードでAI Powered SaaS: Stripe + Auth + Billing + Deployを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Powered SaaS: Stripe + Auth + Billing + Deployを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Powered SaaS: Stripe + Auth + Billing + Deployは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「AIレスポンスのストリーミング」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Powered SaaS: Stripe + Auth + Billing + Deployレッスンでコードを書いて実行できますか?

はい。すべてのAI Powered SaaS: Stripe + Auth + Billing + Deployレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. AIサービスAPIの統合
  2. プロンプトエンジニアリングの基礎
  3. UIへのAI組み込み
  4. AIレスポンスのストリーミング
← AI Powered SaaS: Stripe + Auth + Billing + Deployに戻る