# Streaming

> Set stream to true to receive the response as Server-Sent Events while it is generated, and learn the chunk format, where usage arrives, how errors show up mid-stream and how to cancel.

Without streaming, your users wait for the model to finish the whole answer before they see anything. With streaming, text starts appearing as soon as the model produces its first token. Lykia streams in the same format as OpenAI, as Server-Sent Events (SSE), so the OpenAI SDKs and any SSE-capable client handle it as they are.

## Turn streaming on

Add `"stream": true` to the [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions) body. With an SDK you iterate over the chunks; usage arrives in the last one:

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

stream = client.chat.completions.create(
    model="google/gemini-2.5-flash",
    messages=[{"role": "user", "content": "Name three uses of a message queue."}],
    stream=True,
)

usage = None
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        usage = chunk.usage

print()
if usage is None:
    raise RuntimeError("stream ended without a usage chunk; treat the response as incomplete")
# cost is a Lykia field, so it is not a typed attribute of the SDK object.
print("tokens:", usage.total_tokens, "cost (USD):", getattr(usage, "cost", None))
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const stream = await client.chat.completions.create({
  model: "google/gemini-2.5-flash",
  messages: [{ role: "user", content: "Name three uses of a message queue." }],
  stream: true,
});

let usage: (OpenAI.CompletionUsage & { cost?: number }) | undefined;
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
  if (chunk.usage) usage = chunk.usage;
}

process.stdout.write("\n");
if (!usage) throw new Error("stream ended without a usage chunk; treat the response as incomplete");
// cost is a Lykia field, so it is not part of the SDK's CompletionUsage type.
console.log("tokens:", usage.total_tokens, "cost (USD):", usage.cost);
```

Streamed requests follow the same routing, fallback and billing rules as non-streamed ones. Lykia sends the response headers once the first chunk has arrived from a provider, so until then a failing provider can still be swapped for the next candidate. The headers include `X-Generation-Id` and, when Lykia set or lowered the output limit for the request, `X-Max-Tokens-Applied` ([Reservations](https://www.getlykia.com/en/docs/guides/credits-and-billing#reservations)).

## Stream format

The response has `Content-Type: text/event-stream`. Each event is a line starting with `data: ` followed by a blank line. The data is a `chat.completion.chunk` object, and the stream ends with a `data: [DONE]` line.

```text
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"role":"assistant","content":"1. "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"Decoupling "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"services\n"},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"2. "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"Smoothing "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"traffic "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"spikes\n"},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"3. "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"Running "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"background "},"finish_reason":null}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"jobs"},"finish_reason":"stop"}]}

data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":12,"total_tokens":26,"cost":0.000034,"is_byok":false,"cost_details":{"upstream_cost":0.000034,"platform_fee":0,"is_byok":false},"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":0},"completion_tokens_details":{"reasoning_tokens":0}}}

data: [DONE]
```

A chunk contains:

- `id` (string) — Lykia's id for the request, the same in every chunk and in the `X-Generation-Id` response header. Once the stream has finished you can look it up with [`GET /generation`](https://www.getlykia.com/en/docs/api-reference/generation).
- `object` (string) — Always `"chat.completion.chunk"`.
- `created` (integer) — Unix timestamp in seconds.
- `model` (string) — The model serving the request.
- `provider` (string) — The id of the provider that served the request (for example `openai`).
- `choices` (array) — What changed in this chunk. Empty in the final usage chunk.
  - `index` (integer) — Position of the choice.
  - `delta` (object) — The part to append: `role` in the first chunk, then pieces of `content`; for tool calls, pieces of `tool_calls`; for models that report their reasoning, pieces of `reasoning`.
  - `finish_reason` (string | null) — `null` until generation ends, then a value such as `"stop"`, `"length"` or `"tool_calls"`.
- `usage` (object) — Only in the last data chunk: the same object as in a non-streamed response, with `prompt_tokens`, `completion_tokens`, `total_tokens`, `cost` in USD, `is_byok`, `cost_details`, `prompt_tokens_details` and `completion_tokens_details`.

Some providers add fields of their own to a chunk, such as `system_fingerprint` or `logprobs`; Lykia passes them through. Concatenate the `content` pieces in order to get the full answer. For tool calls, `tool_calls[].function.arguments` arrives in pieces too, so parse the arguments as JSON only after you have joined all of them.

## Usage and cost

Token counts and cost are only known once the answer is complete, which is why `usage` comes in the last data chunk, right before `data: [DONE]`. Lykia asks the provider for usage itself; you do not need to add anything to the request. If you already send OpenAI's `stream_options: { "include_usage": true }`, you can leave it in.

> **Warning:** If the stream ends without a chunk that carries `usage`, treat the response as incomplete. The connection may have dropped or the provider may have failed halfway; do not present the text as finished, and retry if you need the full answer.

## Read the stream without an SDK

You do not need a special library to read SSE. Read line by line, skip lines that do not start with `data: `, and stop at `[DONE]`. Lykia does not send SSE comment lines (lines starting with `:`), but the SSE specification allows them, so a robust client ignores them.

**cURL**

```bash
# -N turns off curl's output buffering so chunks print as they arrive.
curl -N https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "model": "google/gemini-2.5-flash",
    "stream": true,
    "messages": [{ "role": "user", "content": "Name three uses of a message queue." }]
  }'
```

**Python**

```python
import json
import os

import requests

response = requests.post(
    "https://api.getlykia.com/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
    json={
        "model": "google/gemini-2.5-flash",
        "stream": True,
        "messages": [{"role": "user", "content": "Name three uses of a message queue."}],
    },
    stream=True,
    timeout=120,
)
response.raise_for_status()

usage = None
for raw in response.iter_lines(decode_unicode=True):
    # Skip blank separators and SSE comment lines (they start with ":").
    if not raw or raw.startswith(":") or not raw.startswith("data: "):
        continue
    data = raw[len("data: "):]
    if data == "[DONE]":
        break
    chunk = json.loads(data)
    # A provider failure after the stream started arrives as an event with "error" and no "choices"
    if "error" in chunk:
        error = chunk["error"]
        raise RuntimeError(f"{error['status']} {error['code']}: {error['message']}")
    for choice in chunk.get("choices", []):
        print(choice.get("delta", {}).get("content") or "", end="", flush=True)
    if chunk.get("usage"):
        usage = chunk["usage"]

print()
if usage is None:
    raise RuntimeError("stream ended without a usage chunk; treat the response as incomplete")
print("cost (USD):", usage["cost"])
```

**TypeScript**

```typescript
const response = await fetch("https://api.getlykia.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.LYKIA_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "google/gemini-2.5-flash",
    stream: true,
    messages: [{ role: "user", content: "Name three uses of a message queue." }],
  }),
});
if (!response.ok || !response.body) {
  throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
}

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
let usage: { cost: number } | undefined;

for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  const lines = buffer.split("\n");
  buffer = lines.pop() ?? "";
  for (const line of lines) {
    // Skip blank separators and SSE comment lines (they start with ":").
    if (!line.startsWith("data: ")) continue;
    const data = line.slice("data: ".length);
    if (data === "[DONE]") continue;
    const chunk = JSON.parse(data);
    // A provider failure after the stream started arrives as an event with `error` and no `choices`
    if (chunk.error) throw new Error(`${chunk.error.status} ${chunk.error.code}: ${chunk.error.message}`);
    process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
    if (chunk.usage) usage = chunk.usage;
  }
}

process.stdout.write("\n");
if (!usage) throw new Error("stream ended without a usage chunk; treat the response as incomplete");
console.log("cost (USD):", usage.cost);
```

**Go**

```go
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

type chunk struct {
	Choices []struct {
		Delta struct {
			Content string `json:"content"`
		} `json:"delta"`
	} `json:"choices"`
	Usage *struct {
		Cost float64 `json:"cost"`
	} `json:"usage"`
	// A provider failure after the stream started arrives as an event with "error" and no "choices"
	Error *struct {
		Code    string `json:"code"`
		Status  int    `json:"status"`
		Message string `json:"message"`
	} `json:"error"`
}

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":    "google/gemini-2.5-flash",
		"stream":   true,
		"messages": []map[string]string{{"role": "user", "content": "Name three uses of a message queue."}},
	})
	req, err := http.NewRequest(http.MethodPost, "https://api.getlykia.com/v1/chat/completions", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("Lykia returned %d", resp.StatusCode))
	}

	var cost *float64
	scanner := bufio.NewScanner(resp.Body)
	scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
	for scanner.Scan() {
		line := scanner.Text()
		// Skip blank separators and SSE comment lines (they start with ":").
		if !strings.HasPrefix(line, "data: ") {
			continue
		}
		data := strings.TrimPrefix(line, "data: ")
		if data == "[DONE]" {
			break
		}
		var c chunk
		if err := json.Unmarshal([]byte(data), &c); err != nil {
			panic(err)
		}
		if c.Error != nil {
			panic(fmt.Sprintf("%d %s: %s", c.Error.Status, c.Error.Code, c.Error.Message))
		}
		if len(c.Choices) > 0 {
			fmt.Print(c.Choices[0].Delta.Content)
		}
		if c.Usage != nil {
			cost = &c.Usage.Cost
		}
	}
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	fmt.Println()
	if cost == nil {
		panic("stream ended without a usage chunk; treat the response as incomplete")
	}
	fmt.Println("cost (USD):", *cost)
}
```

## Errors

When an error happens before the first chunk (an invalid key, an empty balance, an unknown model, or every provider failing), the stream never starts: you get an ordinary HTTP error response with the usual [error body](https://www.getlykia.com/en/docs/guides/errors). Check the status code before you start reading the stream.

Once the stream has started, the status stays `200`. If the provider fails after that point, or stops sending for too long, Lykia sends one separate error event and then `data: [DONE]`. The event carries `id`, `object`, `created`, `model`, `provider` and an `error` object with the same fields as an [error body](https://www.getlykia.com/en/docs/guides/errors#error-body) (`message`, `type`, `code`, `status`, `metadata.reason`), and it has **no `choices`**. Check every event for `error` before you read `choices`. That stream has no usage chunk. The tokens generated before the failure are billed, and the record's status is `error`.

```text
data: {"id":"gen-…","object":"chat.completion.chunk","created":1795373697,"model":"anthropic/claude-sonnet-4.5","provider":"anthropic","error":{"message":"The provider reported an error","type":"provider_error","code":"provider_error","status":502,"metadata":{"reason":"provider_error","provider":"anthropic"}}}

data: [DONE]
```

Because the event has no `choices`, the OpenAI SDKs raise it as an API error while you iterate, and the Vercel AI SDK reports it as an `error` part instead of a normal finish.

## Cancel a stream

When the user stops a response, close the connection. Lykia notices that your connection has closed and cancels the request to the provider, so you do not keep paying for tokens nobody will read.

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

stream = client.chat.completions.create(
    model="google/gemini-2.5-flash",
    messages=[{"role": "user", "content": "Write a long story about a lighthouse keeper."}],
    stream=True,
)

received = ""
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        received += chunk.choices[0].delta.content
    if len(received) > 500:
        # Closing the stream closes the connection; Lykia cancels the request to the provider.
        stream.close()
        break

print(received)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const stream = await client.chat.completions.create({
  model: "google/gemini-2.5-flash",
  messages: [{ role: "user", content: "Write a long story about a lighthouse keeper." }],
  stream: true,
});

let received = "";
for await (const chunk of stream) {
  received += chunk.choices[0]?.delta?.content ?? "";
  if (received.length > 500) {
    // Aborting closes the connection; Lykia cancels the request to the provider.
    stream.controller.abort();
    break;
  }
}

console.log(received);
```

> **Note:** What the provider generated up to the moment you cancel is billed, including reasoning tokens and text that had not reached you yet. Providers usually report usage only at the end of a stream, so for a cancelled stream Lykia estimates the token counts from all the text it received from the provider (about four characters per token), and never bills less than the usage the provider last reported. The request shows up in your logs with the status `cancelled`.

## Next steps

- [Tool calling](https://www.getlykia.com/en/docs/guides/tool-calling): assemble `tool_calls` pieces from a stream.
- [Errors](https://www.getlykia.com/en/docs/guides/errors): handle errors returned before a stream starts.
- [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions): reference for the chunk object.
