Skip to content

Streaming

Enabling Streaming

Set stream: true in your chat completion request:

Terminal window
curl https://ghostmind.optdmsa.com/v1/chat/completions \
-H "Authorization: Bearer sk-gm-..." \
-H "Content-Type: application/json" \
-d '{
"model": "auto",
"stream": true,
"messages": [{"role": "user", "content": "Hello!"}]
}'

SSE Format

The response is a stream of Server-Sent Events:

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]

Event Flow

  1. First chunk — Contains delta.role: "assistant"
  2. Content chunks — Contain delta.content with text fragments
  3. Final chunk — Contains finish_reason: "stop"
  4. [DONE] — Stream terminator

Error During Stream

If an error occurs mid-stream, an error event is sent:

data: {"error":{"message":"Upstream error","type":"upstream_error"}}

Client Example (JavaScript)

const response = await fetch("https://ghostmind.optdmsa.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": "Bearer sk-gm-...",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "auto",
stream: true,
messages: [{ role: "user", content: "Hello!" }],
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") return;
const chunk = JSON.parse(data);
const content = chunk.choices?.[0]?.delta?.content;
if (content) process.stdout.write(content);
}
}
}

Next Steps