Streaming delle risposte dell’IA
Impari a trasmettere in streaming i token di un modello di IA in tempo reale, così gli utenti vedono comparire progressivamente le risposte invece di attendere il risultato completo.
Streaming delle risposte dell’IA è una lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Powered SaaS: Stripe + Auth + Billing + Deploy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Powered SaaS: Stripe + Auth + Billing + Deploy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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: trueon 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.
Impara AI Powered SaaS: Stripe + Auth + Billing + Deploy con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Streaming delle risposte dell’IA» è gratuita?
Sì — il testo completo di «Streaming delle risposte dell’IA» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Powered SaaS: Stripe + Auth + Billing + Deploy, passa a CoddyKit PRO. Il corso AI Powered SaaS: Stripe + Auth + Billing + Deploy include 4 lezioni in totale.
Cosa imparerò in «Streaming delle risposte dell’IA»?
Impari a trasmettere in streaming i token di un modello di IA in tempo reale, così gli utenti vedono comparire progressivamente le risposte invece di attendere il risultato completo. Eserciti AI Powered SaaS: Stripe + Auth + Billing + Deploy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare AI Powered SaaS: Stripe + Auth + Billing + Deploy?
Non è richiesta alcuna esperienza precedente. AI Powered SaaS: Stripe + Auth + Billing + Deploy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Streaming delle risposte dell’IA»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy?
Sì. Ogni lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Integrazione delle API dei servizi IA
- Fondamenti di prompt engineering
- Integrazione dell'IA nell'interfaccia utente
- Streaming delle risposte dell’IA