Guides
Streaming
Display a reply as it arrives and collect usage at the end of a chat stream.
Start a stream
cURL
curl -N "https://kavren.dev/v1/chat/completions" \
-H "Authorization: Bearer $KAVREN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-v4.1-flash-fast",
"messages": [
{
"role": "user",
"content": "Reply with the name of one planet."
}
],
"max_tokens": 64,
"stream": true,
"stream_options": {
"include_usage": true
}
}'Read the event stream
SSE · selected events
data: {"choices":[{"index":0,"delta":{"content":"Mars"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"choices":[],"usage":{"prompt_tokens":18,"completion_tokens":2,"total_tokens":20}}
data: [DONE]Append each nonempty delta.content. An event can carry a role, a tool fragment or usage without any text. Check for an empty choices array before indexing it. Buffer complete SSE events before parsing JSON.
Print text as it arrives
Python · openai
import os
from openai import OpenAI
client = OpenAI(base_url="https://kavren.dev/v1", api_key=os.environ["KAVREN_API_KEY"])
stream = client.chat.completions.create(
model="deepseek-v4.1-flash-fast",
messages=[{"role": "user", "content": "Reply with the name of one planet."}],
max_tokens=64,
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
for choice in chunk.choices:
if choice.delta.content:
print(choice.delta.content, end="", flush=True)
if chunk.usage:
print("\nTokens:", chunk.usage.total_tokens)Handle a disconnect
A socket closing before the terminal event can leave you with a partial answer. Preserve the partial text and request ID. If you supplied an Idempotency-Key, reuse it with the exact request body. A replay starts from the first event, so replace the partial buffer.