Streaming delle risposte LLM agli utenti
Consegni i token agli utenti in tempo reale. Impari come funziona lo streaming, perché migliori la latenza percepita e come consumare in codice una completion trasmessa in streaming.
Streaming delle risposte LLM agli utenti è una lezione Prompt Engineering & LLM Optimization for Developers 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 Prompt Engineering & LLM Optimization for Developers, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Prompt Engineering & LLM Optimization for Developers include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Domande Frequenti
La lezione «Streaming delle risposte LLM agli utenti» è gratuita?
Sì — il testo completo di «Streaming delle risposte LLM agli utenti» è 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 Prompt Engineering & LLM Optimization for Developers, passa a CoddyKit PRO. Il corso Prompt Engineering & LLM Optimization for Developers include 4 lezioni in totale.
Cosa imparerò in «Streaming delle risposte LLM agli utenti»?
Consegni i token agli utenti in tempo reale. Impari come funziona lo streaming, perché migliori la latenza percepita e come consumare in codice una completion trasmessa in streaming. Eserciti Prompt Engineering & LLM Optimization for Developers 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 Prompt Engineering & LLM Optimization for Developers?
Non è richiesta alcuna esperienza precedente. Prompt Engineering & LLM Optimization for Developers 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 LLM agli utenti»?
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 Prompt Engineering & LLM Optimization for Developers?
Sì. Ogni lezione Prompt Engineering & LLM Optimization for Developers 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
- Generazione aumentata dal recupero (RAG)
- Chiamate di funzione e uso degli strumenti
- Creazione di semplici agenti LLM
- Streaming delle risposte LLM agli utenti