Skip to content

Streaming Responses: SSE Pattern

ChatGPT yanıtı tek seferde değil, akarak gelir — kullanıcı bekleme süresi azalır. SSE ile implementasyon.

Şükrü Yusuf KAYA
9 min read
Advanced
Streaming Responses: SSE Pattern

"Tek seferde 5 saniye bekleme yerine, kelime kelime yazılma"#

ChatGPT.com'da deneyimliyorsun: yanıt soldan sağa akıyor. Bu streaming — Server-Sent Events (SSE) protokolü ile.
Avantaj:
  • Kullanıcı algılanan beklemenin %50'si kadar bekler
  • İlk token 200ms'de, son token 5sn'de — kullanıcı 200ms'de okumaya başlar
  • Uzun yanıtlar için zorunlu UX standardı
javascript
import OpenAI from "openai";
const openai = new OpenAI();
 
const stream = await openai.chat.completions.create({
model: "gpt-5",
messages: [{ role: "user", content: "10 farklı pasta tarifi yaz." }],
stream: true, // ← anahtar
});
 
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || "";
process.stdout.write(content);
}
// Yanıt akarak ekrana yazılır
Node.js streaming — for-await-of ile.
python
from openai import OpenAI
client = OpenAI()
 
stream = client.chat.completions.create(
model="gpt-5",
messages=[{"role": "user", "content": "10 farklı pasta tarifi yaz."}],
stream=True,
)
 
for chunk in stream:
content = chunk.choices[0].delta.content or ""
print(content, end="", flush=True)
Python streaming — for döngüsü ile.
typescript
// app/api/chat/route.ts (Next.js App Router)
import { OpenAI } from "openai";
import { OpenAIStream, StreamingTextResponse } from "ai";
 
const openai = new OpenAI();
 
export async function POST(req: Request) {
const { messages } = await req.json();
 
const response = await openai.chat.completions.create({
model: "gpt-5",
messages,
stream: true,
});
 
const stream = OpenAIStream(response);
return new StreamingTextResponse(stream);
}
 
// Frontend (React + Vercel ai sdk)
import { useChat } from "ai/react";
 
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
 
return (
<div>
{messages.map((m) => (
<div key={m.id}>
{m.role === "user" ? "Sen: " : "AI: "}
{m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
</form>
</div>
);
}
Next.js + Vercel ai SDK ile uçtan uca streaming.

Özet#

✓ Streaming = SSE ile chunk-by-chunk yanıt ✓ Kullanıcı bekleme süresini %50+ azaltır ✓ Vercel ai SDK Next.js için en kolay yol
Sıradaki ders: Function Calling — yapılandırılmış tool kullanımı.

Yorumlar & Soru-Cevap

(0)
Yorum yazmak için giriş yap.
Yorumlar yükleniyor...

Related Content