0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · Aula

Respostas de IA em streaming

Aprenda a transmitir tokens de um modelo de IA em tempo real, para que os usuários vejam as respostas aparecerem progressivamente em vez de aguardarem a resposta completa.

Respostas de IA em streaming é uma aula grátis de AI Powered SaaS: Stripe + Auth + Billing + Deploy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Powered SaaS: Stripe + Auth + Billing + Deploy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “Respostas de IA em streaming” é grátis?

Sim — o texto completo de “Respostas de IA em streaming” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy, atualize para CoddyKit PRO. O curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy inclui 4 aulas no total.

O que vou aprender em “Respostas de IA em streaming”?

Aprenda a transmitir tokens de um modelo de IA em tempo real, para que os usuários vejam as respostas aparecerem progressivamente em vez de aguardarem a resposta completa. Você pratica AI Powered SaaS: Stripe + Auth + Billing + Deploy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Nenhuma experiência prévia é necessária. AI Powered SaaS: Stripe + Auth + Billing + Deploy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Respostas de IA em streaming”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Sim. Cada aula de AI Powered SaaS: Stripe + Auth + Billing + Deploy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Integração de APIs de serviços de IA
  2. Fundamentos da engenharia de prompts
  3. Incorporando IA à interface do usuário
  4. Respostas de IA em streaming
← Voltar para AI Powered SaaS: Stripe + Auth + Billing + Deploy