Tutorial · Menengah · ±10 mnt
Respons Streaming Real-Time (SSE)
Kirim jawaban kata-per-kata seperti ChatGPT dengan stream:true.
1. Aktifkan stream
Tambahkan "stream": true. Respons memakai Server-Sent Events: baris data: {...} berisi chunk chat.completion.chunk, diakhiri data: [DONE].
curl -N https://sahabatmobile.com/api/v1/chat/completions \
-H "Authorization: Bearer sk-ISI_KEY_ANDA" \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemini-2.5-flash",
"messages": [{"role": "user", "content": "Ceritakan legenda Malin Kundang."}],
"stream": true
}',
2. Contoh chunk
Setiap chunk membawa potongan teks di choices[0].delta.content. Chunk terakhir membawa finish_reason: "stop".
data: {"id":"chatcmpl-x","object":"chat.completion.chunk","model":"google/gemini-2.5-flash","choices":[{"index":0,"delta":{"content":"Dahulu"},"finish_reason":null}]}
data: {"id":"chatcmpl-x","object":"chat.completion.chunk","model":"google/gemini-2.5-flash","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
3. Contoh Python
Gabungkan potongan delta.content sambil menampilkannya langsung.
import requests
with requests.post(
"https://sahabatmobile.com/api/v1/chat/completions",
headers={"Authorization": "Bearer sk-ISI_KEY_ANDA"},
json={"model": "google/gemini-2.5-flash",
"messages": [{"role": "user", "content": "Halo!"}],
"stream": True},
stream=True, timeout=120,
) as r:
for line in r.iter_lines():
if not line or not line.startswith(b"data: "):
continue
payload = line[6:].decode()
if payload == "[DONE]":
break
import json
delta = json.loads(payload)["choices"][0]["delta"]
print(delta.get("content", ""), end="", flush=True)