LLM-Antworten an Nutzer streamen
Liefern Sie Tokens in Echtzeit an Ihre Nutzer. Lernen Sie, wie Streaming funktioniert, warum es die wahrgenommene Latenz verbessert und wie Sie eine gestreamte Completion im Code verarbeiten
LLM-Antworten an Nutzer streamen ist eine kostenlose Prompt Engineering & LLM Optimization for Developers-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Prompt Engineering & LLM Optimization for Developers-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Prompt Engineering & LLM Optimization for Developers-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „LLM-Antworten an Nutzer streamen“ kostenlos?
Ja — der vollständige Text von „LLM-Antworten an Nutzer streamen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Prompt Engineering & LLM Optimization for Developers-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Prompt Engineering & LLM Optimization for Developers-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „LLM-Antworten an Nutzer streamen“?
Liefern Sie Tokens in Echtzeit an Ihre Nutzer. Lernen Sie, wie Streaming funktioniert, warum es die wahrgenommene Latenz verbessert und wie Sie eine gestreamte Completion im Code verarbeiten Du übst Prompt Engineering & LLM Optimization for Developers mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Prompt Engineering & LLM Optimization for Developers zu starten?
Keine Vorkenntnisse erforderlich. Prompt Engineering & LLM Optimization for Developers auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „LLM-Antworten an Nutzer streamen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Prompt Engineering & LLM Optimization for Developers-Lektion Code schreiben und ausführen?
Ja. Jede Prompt Engineering & LLM Optimization for Developers-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Retrieval Augmented Generation (RAG)
- Function Calling und Tool-Nutzung
- Einfache LLM-Agenten erstellen
- LLM-Antworten an Nutzer streamen