Streaming
API Reference
Server-Sent Events (SSE) Streaming
Set "stream": true in your request to receive tokens as they are generated. This is ideal for chat interfaces where users expect real-time responses.
cURL
curl https://api.barqapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $BARQ_API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Tell me a short story"}],
"stream": true
}'
Python
from openai import OpenAI
client = OpenAI(
base_url="https://api.barqapi.com/v1",
api_key="your-barq-api-key"
)
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a short story"}],
stream=True
)
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
JavaScript
const stream = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Tell me a short story" }],
stream: true
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
Stream Chunk Format
// Each SSE event:
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":"Hello"},"index":0}]}
// Final chunk:
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]