Streaming
Real-time token streaming with Server-Sent Events
Responses are delivered token by token as they are generated, rather than waiting for the full completion. Streaming uses Server-Sent Events (SSE) and gives you:
- Lower perceived latency - the first token reaches the caller at time-to-first-token instead of after the whole completion
- Reliability on long generations - the response starts flowing at time-to-first-token, so it clears the response timeout that ends requests which send nothing
- Progress indication - render output while the model is still generating
Enable Streaming
Set stream: true in your request:
import os
import openai
client = openai.OpenAI(
base_url="https://api.blackfuel.ai/v1",
api_key=os.environ["BLACKFUEL_API_KEY"],
)
stream = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[
{"role": "user", "content": "Write a haiku about programming."}
],
stream=True
)
for chunk in stream:
# The stream ends with a usage chunk whose choices array is empty
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print() # Newline at endimport OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.blackfuel.ai/v1',
apiKey: process.env.BLACKFUEL_API_KEY
});
const stream = await client.chat.completions.create({
model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
messages: [
{ role: 'user', content: 'Write a haiku about programming.' }
],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
}
console.log(); // Newline at endcurl -X POST https://api.blackfuel.ai/v1/chat/completions \
-H "Authorization: Bearer $BLACKFUEL_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"messages": [
{"role": "user", "content": "Write a haiku about programming."}
],
"stream": true
}'Stream Response Format
The response is text/event-stream. On POST /v1/chat/completions, each event is a line prefixed with data: , separated from the next by a blank line, and the stream closes with the literal sentinel data: [DONE]:
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1703123456,"model":"deepseek-ai/DeepSeek-V4-Flash-0731","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],"usage":{"prompt_tokens":18,"total_tokens":18,"completion_tokens":0}}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1703123456,"model":"deepseek-ai/DeepSeek-V4-Flash-0731","choices":[{"index":0,"delta":{"content":"Code"},"logprobs":null,"finish_reason":null}],"usage":{"prompt_tokens":18,"total_tokens":19,"completion_tokens":1}}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1703123456,"model":"deepseek-ai/DeepSeek-V4-Flash-0731","choices":[{"index":0,"delta":{"content":" flows"},"logprobs":null,"finish_reason":null}],"usage":{"prompt_tokens":18,"total_tokens":20,"completion_tokens":2}}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1703123456,"model":"deepseek-ai/DeepSeek-V4-Flash-0731","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":18,"total_tokens":20,"completion_tokens":2}}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1703123456,"model":"deepseek-ai/DeepSeek-V4-Flash-0731","choices":[],"usage":{"prompt_tokens":18,"total_tokens":20,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":0}}}
data: [DONE][DONE] is a sentinel string, not JSON — match it before you hand the payload to a JSON decoder.
The last chunk before data: [DONE] is the usage chunk. See Token Usage.
Each entry in choices carries the same index / logprobs / finish_reason fields as the Choice object, with delta in place of message. usage.prompt_tokens_details appears on the usage chunk.
Chunk Object
| Field | Type | Description |
|---|---|---|
id | string | Completion identifier (same for all chunks) |
object | string | Always "chat.completion.chunk" |
created | integer | Unix timestamp |
model | string | Model used |
choices | array | Array with delta content. Empty on the final usage chunk |
usage | object | Token counts for the completion so far. Present on every chunk; final on the usage chunk |
Delta Object
| Field | Type | Description |
|---|---|---|
role | string | Present in first chunk only |
content | string | Token content (may be empty) |
reasoning | string | Reasoning content from reasoning-capable models. See Streaming reasoning |
tool_calls | array | Tool-call fragments, accumulated across chunks. See Handling Tool Calls in Streams |
Consuming the Stream
The OpenAI SDKs decode the event stream and yield chunk objects. Accumulate delta.content to build the complete response while it renders. These samples reuse the client from Enable Streaming:
stream = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[{"role": "user", "content": "Tell me a story."}],
stream=True
)
collected_content = []
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
collected_content.append(content)
print(content, end="", flush=True)
full_response = "".join(collected_content)
print(f"\n\nFull response length: {len(full_response)} chars")const stream = await client.chat.completions.create({
model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
messages: [{ role: 'user', content: 'Tell me a story.' }],
stream: true
});
const collectedContent = [];
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
collectedContent.push(content);
process.stdout.write(content);
}
}
const fullResponse = collectedContent.join('');
console.log(`\n\nFull response length: ${fullResponse.length} chars`);Async Streaming (Python)
For async applications:
import asyncio
import os
import openai
async def stream_response():
client = openai.AsyncOpenAI(
base_url="https://api.blackfuel.ai/v1",
api_key=os.environ["BLACKFUEL_API_KEY"],
)
stream = await client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[{"role": "user", "content": "Write a poem."}],
stream=True
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
asyncio.run(stream_response())Without an SDK
Any HTTP client that reads the body incrementally works. Take each data: line — reading line by line, or splitting the body on blank lines — strip the prefix, and stop at [DONE]. Without an SDK you also own retries, so these samples back off on 429; the timeout values come from Client timeouts.
import json
import os
import time
import httpx
REQUEST = {
"method": "POST",
"url": "https://api.blackfuel.ai/v1/chat/completions",
"headers": {"Authorization": f"Bearer {os.environ['BLACKFUEL_API_KEY']}"},
"json": {
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"messages": [{"role": "user", "content": "Write a haiku about programming."}],
"stream": True,
},
"timeout": httpx.Timeout(600.0, connect=5.0, read=60.0),
}
for attempt in range(4):
with httpx.stream(**REQUEST) as response:
if response.status_code == 429 and attempt < 3:
response.read()
time.sleep(2**attempt)
continue
response.raise_for_status()
for line in response.iter_lines():
if not line.startswith("data: "):
continue
payload = line[len("data: "):]
if payload == "[DONE]":
break
chunk = json.loads(payload)
if chunk["choices"] and chunk["choices"][0]["delta"].get("content"):
print(chunk["choices"][0]["delta"]["content"], end="", flush=True)
breakconst request = {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.BLACKFUEL_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
messages: [{ role: 'user', content: 'Write a haiku about programming.' }],
stream: true
})
};
async function openStream(attempt = 0) {
const response = await fetch('https://api.blackfuel.ai/v1/chat/completions', request);
if (response.status === 429 && attempt < 3) {
await response.text();
await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
return openStream(attempt + 1);
}
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`);
}
return response;
}
const response = await openStream();
let buffer = '';
let finished = false;
for await (const text of response.body.pipeThrough(new TextDecoderStream())) {
buffer += text;
const events = buffer.split('\n\n');
buffer = events.pop() ?? '';
for (const event of events) {
if (!event.startsWith('data: ')) continue;
const payload = event.slice('data: '.length);
if (payload === '[DONE]') {
finished = true;
break;
}
const chunk = JSON.parse(payload);
const content = chunk.choices[0]?.delta?.content;
if (content) process.stdout.write(content);
}
if (finished) break;
}Reading the body incrementally is what makes the response a stream. See Error Handling for the full failure surface.
Token Usage
Every chunk carries a usage object holding the running token counts for the completion so far, and the stream ends with a usage chunk: a final chunk whose choices array is empty and whose usage counts are the completed totals. It arrives immediately before data: [DONE], on every streaming request, whether or not you send stream_options.
Read the totals from the usage chunk — identify it by its empty choices.
Because choices is empty on a usage chunk, indexing chunk.choices[0] without a guard raises an IndexError at end of stream. Guard on chunk.choices — every Python sample on this page does.
stream = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[{"role": "user", "content": "Write a haiku about programming."}],
stream=True
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
# The usage chunk has no choices; its counts are final
if not chunk.choices and chunk.usage:
print(f"\n\nTokens: {chunk.usage.total_tokens}")const stream = await client.chat.completions.create({
model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
messages: [{ role: 'user', content: 'Write a haiku about programming.' }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
// The usage chunk has no choices; its counts are final
if (chunk.choices.length === 0 && chunk.usage) {
console.log(`\n\nTokens: ${chunk.usage.total_tokens}`);
}
}stream_options.include_usage is accepted for OpenAI compatibility. It changes nothing: the usage chunk is sent whether you set it to true, set it to false, or omit stream_options entirely.
Timeouts and Long-Running Requests
Two limits apply to every chat completion request:
| Limit | What happens when you exceed it |
|---|---|
| Response timeout — 125 seconds without a response | You get a 524 and the whole generation is thrown away — no content, no usage, no charge. In practice this only catches non-streaming requests, which send nothing until the last token. |
| Request ceiling — 600 seconds in total | The request ends. A streaming response keeps every chunk already delivered. |
A non-streaming request sends nothing until the last token is generated, so the entire generation has to finish inside the response timeout. A streaming request sends its first chunk at time-to-first-token — usually under a second — so it clears that timeout immediately and can run up to the request ceiling.
Stream any request that might exceed the response timeout. A high max_tokens, a large reasoning budget, or a long document to rewrite gets there easily.
The request ceiling is a ceiling, not an allowance: a stream can finish earlier, and one that ends without a finish_reason is incomplete rather than complete. See Error Handling.
A 524 does not carry the JSON error envelope that the API returns for other failures — Error Handling documents its plain-text body.
Client timeouts
Both limits are properties of the request, independent of your client's own timeout settings. Size your client timeouts to match them.
While streaming, httpx's read timeout applies per chunk rather than to the whole response, so you can add read=<seconds> to detect a stalled stream without capping total duration. Size it above the worst-case time to first token — a large prompt can take tens of seconds to produce its first chunk, and a read timeout below that fails the very requests streaming is meant to protect.
import os
import httpx
import openai
client = openai.OpenAI(
base_url="https://api.blackfuel.ai/v1",
api_key=os.environ["BLACKFUEL_API_KEY"],
timeout=httpx.Timeout(600.0, connect=5.0),
)import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.blackfuel.ai/v1',
apiKey: process.env.BLACKFUEL_API_KEY,
timeout: 600 * 1000
});Error Handling
A request that fails before the stream starts — authentication, an unknown model, a rate limit, or a validation error — returns a normal HTTP error response carrying the standard error body, and the SDK raises before the first chunk is yielded.
Once chunks are flowing, the response can still be cut short — a dropped connection, or the request ceiling ending a long generation mid-stream. In both cases you keep the chunks already delivered and no chunk carries finish_reason. Treat a stream that ends without finish_reason as incomplete rather than as a finished response.
try:
stream = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[{"role": "user", "content": "Hello"}],
stream=True
)
finish_reason = None
for chunk in stream:
if not chunk.choices:
continue
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.choices[0].finish_reason:
finish_reason = chunk.choices[0].finish_reason
if finish_reason is None:
print("\nStream ended early - response is incomplete")
except openai.APIConnectionError as e:
print(f"Connection error: {e}")
except openai.APIError as e:
print(f"API error: {e}")import OpenAI from 'openai';
try {
const stream = await client.chat.completions.create({
model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
messages: [{ role: 'user', content: 'Hello' }],
stream: true
});
let finishReason = null;
for await (const chunk of stream) {
if (chunk.choices.length === 0) continue;
if (chunk.choices[0].delta.content) {
process.stdout.write(chunk.choices[0].delta.content);
}
if (chunk.choices[0].finish_reason) {
finishReason = chunk.choices[0].finish_reason;
}
}
if (finishReason === null) {
console.log('\nStream ended early - response is incomplete');
}
} catch (error) {
if (error instanceof OpenAI.APIConnectionError) {
console.error(`Connection error: ${error}`);
} else if (error instanceof OpenAI.APIError) {
console.error(`API error: ${error}`);
} else {
throw error;
}
}APIConnectionError is a subclass of APIError, so catch it first.
Handling Tool Calls in Streams
When streaming with tools, tool calls are accumulated across chunks:
stream = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[{"role": "user", "content": "What's 25 * 17?"}],
tools=[{
"type": "function",
"function": {
"name": "calculate",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string"}
}
}
}
}],
stream=True
)
tool_calls = {}
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if delta.tool_calls:
for tc in delta.tool_calls:
idx = tc.index
if idx not in tool_calls:
tool_calls[idx] = {"name": "", "arguments": ""}
if tc.function.name:
tool_calls[idx]["name"] = tc.function.name
if tc.function.arguments:
tool_calls[idx]["arguments"] += tc.function.arguments
print("Tool calls:", tool_calls)const stream = await client.chat.completions.create({
model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
messages: [{ role: 'user', content: "What's 25 * 17?" }],
tools: [{
type: 'function',
function: {
name: 'calculate',
parameters: {
type: 'object',
properties: {
expression: { type: 'string' }
}
}
}
}],
stream: true
});
const toolCalls = {};
for await (const chunk of stream) {
if (chunk.choices.length === 0) continue;
const delta = chunk.choices[0].delta;
if (!delta.tool_calls) continue;
for (const tc of delta.tool_calls) {
toolCalls[tc.index] ??= { name: '', arguments: '' };
if (tc.function.name) toolCalls[tc.index].name = tc.function.name;
if (tc.function.arguments) toolCalls[tc.index].arguments += tc.function.arguments;
}
}
console.log('Tool calls:', toolCalls);function.arguments arrives as JSON fragments: concatenate every fragment for an index and decode once the stream ends, rather than parsing each fragment.
See Also
- Chat Completions: the full request and response contract.
- Reasoning: reading
delta.reasoningalongsidedelta.content. - Error Handling: status codes, retry logic, and the
524body. - Best Practices: concurrency and prompt structure.