Panduan
Streaming
Terima respons token demi token sebagai Server-Sent Events, dengan pemakaian token di chunk terakhir.
Atur "stream": true untuk menerima jawaban selagi dihasilkan. Respons berupa aliran Server-Sent Events (text/event-stream) dalam format OpenAI: setiap event adalah chat.completion.chunk, dan aliran diakhiri dengan data: [DONE].
Stream sebuah respons
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.larasrouter.com/v1",
api_key=os.environ["LARAS_API_KEY"],
)
stream = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "Tulis haiku tentang hujan di Jakarta."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print(f"\n\n{chunk.usage.total_tokens} token")
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.larasrouter.com/v1",
apiKey: process.env.LARAS_API_KEY,
});
const stream = await client.chat.completions.create({
model: "deepseek-flash",
messages: [{ role: "user", content: "Tulis haiku tentang hujan di Jakarta." }],
stream: true,
stream_options: { include_usage: true },
});
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content;
if (text) process.stdout.write(text);
if (chunk.usage) console.log(`\n\n${chunk.usage.total_tokens} token`);
}
curl https://api.larasrouter.com/v1/chat/completions \
-H "Authorization: Bearer $LARAS_API_KEY" \
-H "Content-Type: application/json" \
--no-buffer \
-d '{
"model": "deepseek-flash",
"messages": [{"role": "user", "content": "Tulis haiku tentang hujan di Jakarta."}],
"stream": true,
"stream_options": {"include_usage": true}
}'
Bentuk aliran
data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}
data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Langit kelabu"}}]}
data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"chatcmpl-…","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":16,"completion_tokens":42,"total_tokens":58,"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":16}}
data: [DONE]
- Reasoning datang lebih dulu, di
delta.reasoning_content, sebelumdelta.contentberisi jawaban. Lihat Konten reasoning. - Tool call datang sebagai potongan
delta.tool_callsyang Anda gabungkan berdasarkanindex. Lihat Tool calling.
Pemakaian token
Jika stream_options.include_usage bernilai true, chunk terakhir sebelum [DONE] membawa objek usage dan array choices yang kosong. Tanpa opsi itu, Anda tidak menerima chunk pemakaian — request Anda tetap diukur dan ditagih dengan cara yang sama, dan bisa Anda lihat di konsol pada menu Usage.
Cara aliran berakhir
- Normal: chunk dengan
finish_reason, lalu (jika diminta) chunk pemakaian, laludata: [DONE]. Kami baru mengirim[DONE]setelah pemakaian request tercatat, jadi aliran yang Anda lihat selesai adalah aliran yang kami tagih dengan tepat. - Error di tengah aliran: jika provider gagal setelah aliran dimulai, aliran diakhiri dengan event error dalam format yang biasa, misalnya
data: {"error":{"message":"…","type":"api_error","code":"provider_unavailable","param":null}}. Anggap aliran yang berakhir tanpa[DONE]belum lengkap. - Error sebelum aliran dimulai — kunci tidak valid, wallet kosong, rate limit — dikembalikan sebagai respons error JSON biasa dengan status HTTP yang sesuai, bukan sebagai aliran. Lihat Error & retry.