Streaming de respuestas de LLM para los usuarios
Entregue tokens a sus usuarios en tiempo real. Aprenda cómo funciona el streaming, por qué mejora la latencia percibida y cómo consumir una completion transmitida en el código.
Streaming de respuestas de LLM para los usuarios es una lección gratuita de Prompt Engineering & LLM Optimization for Developers en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Prompt Engineering & LLM Optimization for Developers, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Prompt Engineering & LLM Optimization for Developers incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Preguntas frecuentes
¿La lección «Streaming de respuestas de LLM para los usuarios» es gratis?
Sí — el texto completo de «Streaming de respuestas de LLM para los usuarios» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Prompt Engineering & LLM Optimization for Developers, actualiza a CoddyKit PRO. El curso de Prompt Engineering & LLM Optimization for Developers incluye 4 lecciones en total.
¿Qué aprenderé en «Streaming de respuestas de LLM para los usuarios»?
Entregue tokens a sus usuarios en tiempo real. Aprenda cómo funciona el streaming, por qué mejora la latencia percibida y cómo consumir una completion transmitida en el código. Practicas Prompt Engineering & LLM Optimization for Developers con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Prompt Engineering & LLM Optimization for Developers?
No se requiere experiencia previa. Prompt Engineering & LLM Optimization for Developers en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Streaming de respuestas de LLM para los usuarios»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Prompt Engineering & LLM Optimization for Developers?
Sí. Cada lección de Prompt Engineering & LLM Optimization for Developers incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Generación aumentada mediante recuperación (RAG)
- Llamadas a funciones y uso de herramientas
- Creación de agentes LLM sencillos
- Streaming de respuestas de LLM para los usuarios