Streaming responses
Receive content, tool calls, and token usage as server-sent events from Chat Completions.
Request usage explicitly.
Set stream: true and stream_options.include_usage: true to request final usage. Without that option, a usage event may not arrive.
Terminal
curl -N https://beta.blaschkelabs.com/v1/chat/completions \
-H "Authorization: Bearer $BLASCHKE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"<model-id>","messages":[{"role":"user","content":"Explain a Blaschke product."}],"stream":true,"stream_options":{"include_usage":true}}'Text
data: {"choices":[{"delta":{"role":"assistant","content":""}}]}
data: {"choices":[{"delta":{"content":"A Blaschke "}}]}
data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":8,"total_tokens":20}}
data: [DONE]Read events, not tokens.
Events may split tokens or contain several tokens. An empty choices array can carry usage and does not end the stream; [DONE] does.
JavaScript
const response = await fetch("https://beta.blaschkelabs.com/v1/chat/completions", {
method: "POST",
headers: { authorization: "Bearer " + process.env.BLASCHKE_API_KEY, "content-type": "application/json" },
body: JSON.stringify({ model: process.env.BLASCHKE_MODEL, messages: [{ role: "user", content: "Hello" }], stream: true, stream_options: { include_usage: true } }),
});
if (!response.ok) throw new Error(await response.text());
if (!response.body) throw new Error("Response body is unavailable.");
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of response.body) {
buffer += decoder.decode(chunk, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line.startsWith("data:")) continue;
const payload = line.slice(5).trim();
if (!payload) continue;
if (payload === "[DONE]") break;
const data = JSON.parse(payload);
process.stdout.write(data.choices?.[0]?.delta?.content || "");
if (data.usage) console.log("\nUsage:", data.usage);
}
}Assemble complete calls before execution.
Accumulate tool_calls by index. Validate and execute a function only after its complete arguments arrive. Never treat a partial call as a completed tool call.