# Streaming

> Read Chat Completions chunks and Responses events over Server-Sent Events.

Source: https://i14.ai/docs/api-usage/streaming/

Streaming lets you display output while the model generates it. Both Chat Completions and Responses use Server-Sent Events (SSE), but their event formats differ.

| Endpoint                                                                | Text to append                                           | End of a successful stream                                  |
| ----------------------------------------------------------------------- | -------------------------------------------------------- | ----------------------------------------------------------- |
| [Chat Completions](https://i14.ai/docs/api-reference/chat-completions/) | `choices[].delta.content` in JSON chunks                 | A finishing choice and `data: [DONE]`, with no error event. |
| [Responses](https://i14.ai/docs/api-reference/responses/)               | The `delta` field in `response.output_text.delta` events | A `response.completed` event.                               |

## Stream Chat Completions

Add `"stream": true` to your request body to enable streaming. The API will keep the connection open and push chunks of data as the model produces them.

Use `--no-buffer` with curl to disable output buffering and see each chunk as it arrives:

macOS and Linux (bash or zsh)

```bash
curl https://api.i14.ai/v1/chat/completions \
  --no-buffer \
  -H "Authorization: Bearer $I14_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "i14-sugarglider-nemotron3-super-120b-v1",
    "messages": [
      { "role": "system", "content": "You are a helpful assistant." },
      { "role": "user", "content": "Write a short poem about the ocean." }
    ],
    "stream": true,
    "stream_options": {"include_usage": true},
    "max_tokens": 8192
  }'
```

## SSE Response Format

Each SSE record can carry a JSON chunk in one or more `data:` lines. A choice has a `delta` rather than a full `message`. Append text from `delta.content` by choice index. A delta can instead carry an assistant role, separate reasoning, or a tool call fragment. Do not assume each event has visible text.

The final choice reports its `finish_reason`. A normally closed Chat Completions stream ends with a sentinel. An error can also be followed by that sentinel, so check for an error as well:

```plaintext
data: [DONE]
```

Example SSE (selected fields; each event is followed by a blank line):

```text
data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}

data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"The ocean"},"finish_reason":null}]}

data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":8,"total_tokens":22}}

data: [DONE]
```

> **Caution**
>
> Request `stream_options.include_usage: true` to receive the usage-only chunk shown above. Check that `choices` is non-empty before indexing it. If you do not request usage, or the connection ends early, a usage chunk may not arrive.

## Streaming with the OpenAI SDK

The OpenAI SDK handles SSE parsing for you. Set `stream=True` (Python) or `stream: true` (Node.js) in your request and iterate over the returned stream object to access each content delta.

* Python

  ```python
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["I14_API_KEY"],
      base_url="https://api.i14.ai/v1",
  )

  with client.chat.completions.create(
      model="i14-sugarglider-nemotron3-super-120b-v1",
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Write a short poem about the ocean."},
      ],
      stream=True,
      stream_options={"include_usage": True},
      max_tokens=8192,
  ) as stream:
      for chunk in stream:
          if not chunk.choices:
              continue  # final chunk carries usage only
          content = chunk.choices[0].delta.content
          if content:
              print(content, end="", flush=True)

  print()  # newline after stream ends
  ```

* Node.js

  ```javascript
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: process.env.I14_API_KEY,
    baseURL: "https://api.i14.ai/v1",
  });

  const stream = await client.chat.completions.create({
    model: "i14-sugarglider-nemotron3-super-120b-v1",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Write a short poem about the ocean." },
    ],
    stream: true,
    stream_options: { include_usage: true },
    max_tokens: 8192,
  });

  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content ?? "";
    process.stdout.write(content);
  }

  process.stdout.write("\n");
  ```

## Stream Responses

Responses uses named SSE events. Dispatch on the JSON `type`; it is not a Chat Completions chunk. Append text deltas, then inspect the final response and its usage when present. Treat `response.failed`, `response.incomplete` and `error` as outcomes other than a successful completion. Do not wait for `data: [DONE]`.

Example SSE (selected events and fields):

```text
event: response.output_text.delta
data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"The answer"}

event: response.completed
data: {"type":"response.completed","response":{"id":"resp_example","status":"completed","usage":{"input_tokens":15,"output_tokens":10,"total_tokens":25}}}
```

The Python SDK parses the stream for you. Set `I14_MODEL` to a model that supports Responses and `I14_API_KEY` to your key.

```python
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.i14.ai/v1", api_key=os.environ["I14_API_KEY"])
stream = client.responses.create(
    model=os.environ["I14_MODEL"],
    input="Explain embeddings in one sentence.",
    store=False,
    stream=True,
    max_output_tokens=256,
)
terminal = None
with stream:
    for event in stream:
        if event.type == "response.output_text.delta":
            print(event.delta, end="", flush=True)
        elif event.type in {"response.completed", "response.incomplete", "response.failed", "error"}:
            terminal = event.type
if terminal != "response.completed":
    raise RuntimeError(f"Response did not complete: {terminal or 'connection closed'}")
print()
```

Use the same event types in the Node.js SDK’s async iterator. If you need tools, handle [function call events](https://i14.ai/docs/api-usage/function-calling/#responses) separately from text.

## Handle keepalives and interruptions

* Ignore SSE comment lines starting with `:`. They keep a connection open and are not model output.
* If you parse raw SSE, assemble complete events across network reads. Use a blank line as the event boundary, not a network chunk.
* An HTTP `200` is not a completion signal. A gateway can begin the stream with keepalives, then report an error in a Chat Completions JSON `error` record or a Responses `error` event. Treat an error or a missing success terminal as partial output.
* Set client, CDN, and proxy timeouts for your intended context size and output length. Set connection and read timeouts deliberately rather than disabling them. For an interactive client, let users cancel a request when they no longer need the result.
* Retry transient errors with bounded backoff, but do not append a retried stream to the same partial answer or run the same side-effecting tool twice.
