# Leiolai Developer API

> Status: Experimental. The 11-million-token context window and continuous generation are experimental.

Build with Leiolai through OpenAI-compatible Chat Completions, Responses, or text Completions, or through Anthropic-compatible Messages. Leiolai also offers continuous generation, adjustable reasoning effort, and up to 11 million tokens of context.

Machine-readable spec: https://leiolai.com/docs/openapi.yaml

## Quick start

The API accepts Chat Completions, Responses, Anthropic Messages, and text Completions requests. Create a key with Unrestricted, Private only, or Research only access. Unrestricted keys require `mode` on every request. Restricted keys can omit it; requests cannot override a key restriction.

| Your client calls | Use | Endpoint |
| --- | --- | --- |
| `chat.completions.create` | Chat Completions | `POST /v1/chat/completions` |
| `responses.create` | Responses | `POST /v1/responses` |
| `messages.create` | Anthropic Messages | `POST /v1/messages` |
| Legacy text prompt | Text Completions | `POST /v1/completions` |

First, [open Account in the Leiolai web app](https://leiolai.com/app/#account). Sign in, choose **Top up** beside your balance, then open **More**, **Leiolai API**, and **Manage keys**. Choose the key's mode access. A new key is shown once. Store it on a backend you control.

- Base URL: `https://api.leiolai.com/v1`
- `POST /v1/chat/completions`: send a conversation, get one assistant response.
- `POST /v1/responses`: send text or typed input items, get one Responses object or typed event stream.
- `POST /v1/messages`: send an Anthropic Messages request, get one message or typed event stream.
- `POST /v1/completions`: send one text prompt, get one legacy text completion.
- `POST /v1/infinite/chat/completions`: open a continuous response that can accept new context while it runs.
- `POST /v1/infinite/inject`: send context, buffer state, or a stop command to a continuous session.
- `GET /v1/models`: returns `leiolai-1`, the currently available model.
- Authorization: send your `sb_` key on every request. OpenAI clients use `Authorization: Bearer sb_...`; Anthropic clients use `x-api-key: sb_...`.
- Account, billing, and keys: `https://leiolai.com/app/#account`

Never put an API key in frontend JavaScript. Anyone can extract it and spend your balance. Keep the key on a backend you control, then have your frontend call that backend.

```bash
curl https://api.leiolai.com/v1/chat/completions \
  -H "Authorization: Bearer sb_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "leiolai-1",
    "messages": [{"role": "user", "content": "Say hi in five words."}],
    "stream": true,
    "mode": "private"
  }'
```

With the OpenAI Python SDK:

```python
from openai import OpenAI

client = OpenAI(
    api_key="sb_your_key",
    base_url="https://api.leiolai.com/v1",
)

response = client.chat.completions.create(
    model="leiolai-1",
    messages=[{"role": "user", "content": "Say hi in five words."}],
    reasoning_effort="low",
    extra_body={"mode": "private"},
)
print(response.choices[0].message.content)
```

With the Vercel AI SDK 6 or 7:

```bash
npm install ai @leiolai/ai-sdk-provider @ai-sdk/openai-compatible zod
```

```typescript
import { generateText } from "ai";
import { leiolai } from "@leiolai/ai-sdk-provider";

const result = await generateText({
  model: leiolai("leiolai-1"),
  prompt: "Say hi in five words.",
});
console.log(result.text);
```

The provider reads `LEIOLAI_API_KEY`. A Private-only or Research-only key needs no provider mode setting. With an unrestricted key, call `createLeiolai({mode: "private"})` or use `non-private` for Research.

Audio input, embeddings, fine-tuning, and batch endpoints are not part of this compatibility surface.

## API formats

All four finite formats use `leiolai-1`, the same key restrictions, billing, and output checks. OpenAI SDKs use `https://api.leiolai.com/v1` as their base URL; Anthropic SDKs use `https://api.leiolai.com`. If your SDK cannot add `mode`, create a Private-only or Research-only key.

| Format | Input | Response depth | Output cap | Function tools | Schema-valid JSON | Stream text |
| --- | --- | --- | --- | --- | --- | --- |
| Chat Completions | `messages` | `reasoning_effort` | `max_completion_tokens` | `tools[].function` | `response_format` | `choices[0].delta.content` |
| Responses | `input` | `reasoning.effort` | `max_output_tokens` | `tools[]` with top-level `name` and `parameters` | `text.format` | `response.output_text.delta` |
| Anthropic Messages | `messages` | `output_config.effort` | required `max_tokens` | `tools[]` with `input_schema` | Unsupported | `content_block_delta` with `text_delta` |
| Text Completions | `prompt` | `reasoning_effort` | `max_tokens` | Unsupported | Unsupported | `choices[0].text` |

Continuous generation uses the separate Leiolai endpoint `POST /v1/infinite/chat/completions`. It is not a mode of these four finite formats.

### Responses

`POST /v1/responses` accepts `model`, `input` as a string or an array of message and function-call items, `instructions`, `stream`, `max_output_tokens`, `reasoning.effort`, `text.format`, function `tools`, `tool_choice`, and `parallel_tool_calls`. It accepts text, base64 image URLs, and supported inline text files as input. It returns a Responses `output` array with `message` or `function_call` items. With `stream: true`, it sends typed events such as `response.created`, `response.output_text.delta`, `response.output_item.done`, and `response.completed`. A final answer may arrive in one text delta.

```python
from openai import OpenAI

client = OpenAI(api_key="sb_your_private_only_key", base_url="https://api.leiolai.com/v1")
response = client.responses.create(model="leiolai-1", input="Say hi in five words.")
print(response.output_text)
```

This endpoint is stateless. Send prior `output` items back in `input` for a multi-turn conversation or a function result. `store: false` is accepted; `store: true` and `previous_response_id` return HTTP 400. Only caller-defined function tools are supported. Hosted tools, background jobs, and other unlisted Responses fields return HTTP 400. The `store` field controls this Responses API's retrievable state, not Leiolai's chat handling or retention policy.

### Anthropic Messages

`POST /v1/messages` accepts `model`, a positive `max_tokens`, and a nonempty `messages` array. Send an `sb_` key as `x-api-key` with `anthropic-version: 2023-06-01`. Text, base64 image blocks, top-level `system` text, client-defined tools and results, `tool_choice`, `output_config.effort`, and `stream` are supported. The response has Anthropic `content` blocks and `stop_reason`. With `stream: true`, read named `message_start`, content-block, `message_delta`, and `message_stop` events. A final answer may arrive in one text delta.

```python
from anthropic import Anthropic

client = Anthropic(api_key="sb_your_private_only_key", base_url="https://api.leiolai.com")
message = client.messages.create(
    model="leiolai-1",
    max_tokens=256,
    messages=[{"role": "user", "content": "Say hi in five words."}],
)
print(message.content[0].text)
```

This endpoint is stateless: resend earlier messages and tool results on the next turn. Prompt caching, extended thinking blocks, hosted tools, custom stop sequences, and other unlisted Messages fields return HTTP 400. The `mode` field is a Leiolai extension for unrestricted keys.

### Text Completions

`POST /v1/completions` accepts one string `prompt`, `model`, `stream`, `max_tokens`, and `n: 1`. It returns `text_completion` with `choices[0].text`. A completed stream ends in `data: [DONE]`. This adapter uses Leiolai's conversational model, so it does not promise byte-for-byte continuation of an unfinished prefix. Prompt arrays, multiple choices, `echo: true`, log probabilities, stop sequences, and other unlisted Completions fields return HTTP 400.

## Model

Leiolai 1 is currently available. Use `leiolai-1` for every request. The response-depth field depends on the API format; see the table above.

- Model ID: `leiolai-1`. Use it in every request. Compatibility layers may qualify the same ID as `openai/leiolai-1` or `leiolai/leiolai-1`; the suffix still resolves to `leiolai-1` and does not select a different model. Unknown model IDs return 404 `model_not_found`.
- Context window: Experimental. The context window can hold up to 11 million tokens (11,000,000).
- Modality: Chat Completions and Responses accept text, base64 images, and supported inline text files. Anthropic Messages accepts text and base64 images. Text Completions accepts text.

## Request format

`POST /v1/chat/completions` with a JSON body:

```json
{
  "model": "leiolai-1",
  "messages": [
    {"role": "user", "content": "Explain why the sky changes color at sunset."}
  ],
  "stream": true,
  "stream_options": {"include_usage": true},
  "reasoning_effort": "medium",
  "mode": "private"
}
```

Creates a completion for the supplied conversation. The body follows the OpenAI chat completions schema; the supported fields are below.

- `model`: required. Use `leiolai-1`.
- `messages`: role and content pairs. Role is system, user, assistant, or tool. Content is a plain string or an array of typed parts. An assistant message may include `tool_calls`; a tool result uses `role: "tool"` and the matching `tool_call_id`.
- Text part: `{"type":"text","text":"..."}`.
- Image part: `{"type":"image_url","image_url":{"url":"..."}}` with a base64 `data:` image URL. Images work in both modes. Remote image URLs are not accepted.
- File part: `{"type":"file","file":{"filename":"notes.md","file_data":"data:text/markdown;base64,..."}}`. Inline files may contain up to 2 MiB of UTF-8 text, code, CSV, JSON, HTML, XML, YAML, SQL, or Markdown. `file_id` references and binary files such as PDFs are not accepted by this endpoint.
- `stream`: when true, content is returned as server-sent event deltas. When omitted, the response is a single JSON object.
- `stream_options.include_usage`: when true with `stream: true`, the stream includes OpenAI's final usage-only chunk before `data: [DONE]`.
- `reasoning_effort`: optional response depth: low, medium, high, or xhigh. Defaults to low.
- `max_completion_tokens`: optional output cap, in tokens. If omitted, Leiolai derives a ceiling from the available balance and API budget. `max_tokens` is a compatibility alias.
- `mode`: required for unrestricted API keys. A Private-only or Research-only key may omit it because the server infers the key's only permitted mode. Send `private` or `non-private`; a value that conflicts with the key restriction returns HTTP 403. Images and supported inline files work in both modes.
This is a Chat Completions-compatible subset, not a promise that every OpenAI field or SDK feature is implemented. Only the fields listed here are part of the contract. You always receive one choice.

## Function tools

Chat Completions, Responses, and Anthropic Messages support caller-defined functions. Text Completions does not accept `tools`. Leiolai validates returned calls but never executes your functions.

### Chat Completions tools

Send OpenAI function definitions in `tools`. Leiolai returns tool calls for your application to execute. It never executes your functions.

```json
{
  "model": "leiolai-1",
  "mode": "private",
  "messages": [{"role": "user", "content": "What is the weather in Chicago?"}],
  "tools": [{
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get the weather for a city",
      "strict": true,
      "parameters": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
        "additionalProperties": false
      }
    }
  }],
  "tool_choice": "auto"
}
```

- `tool_choice`: `auto`, `none`, `required`, or `{"type":"function","function":{"name":"get_weather"}}`.
- `parallel_tool_calls`: set true to allow one assistant turn to return multiple independent calls. All calls belong to that same turn. Dependent work remains sequential.
- `strict`: accepted on each function. Every returned function name and argument object is validated against the supplied definition before delivery.
- A non-streaming tool response sets `message.content` to null, fills `message.tool_calls`, and uses `finish_reason: "tool_calls"`.
- Execute the calls in your application, then send the assistant message back unchanged followed by one `role: "tool"` message per result. Match each result with `tool_call_id`.
- Tool call IDs are stable within a response and unique across calls. Do not construct or rewrite them.

Example continuation:

```json
{
  "model": "leiolai-1",
  "mode": "private",
  "messages": [
    {"role": "user", "content": "What is the weather in Chicago?"},
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [{
        "id": "call_0123456789abcdef",
        "type": "function",
        "function": {"name": "get_weather", "arguments": "{\"city\":\"Chicago\"}"}
      }]
    },
    {"role": "tool", "tool_call_id": "call_0123456789abcdef", "content": "72 F and clear"}
  ],
  "tools": [{
    "type": "function",
    "function": {
      "name": "get_weather",
      "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
    }
  }]
}
```

### Responses tools

Responses puts function fields directly in each `tools[]` item:

```json
{
  "model": "leiolai-1",
  "input": "What is the weather in Chicago?",
  "tools": [{"type": "function", "name": "get_weather",
    "description": "Get the weather for a city",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
      "required": ["city"], "additionalProperties": false}, "strict": true}],
  "tool_choice": "auto",
  "mode": "private"
}
```

Run each returned `function_call` in your application. Resend the call item, then add a `function_call_output` item with the same `call_id`. This endpoint does not accept `previous_response_id`:

```json
{
  "model": "leiolai-1",
  "input": [
    {"role": "user", "content": "What is the weather in Chicago?"},
    {"id": "fc_123", "type": "function_call", "status": "completed", "call_id": "call_123",
      "name": "get_weather", "arguments": "{\"city\":\"Chicago\"}"},
    {"type": "function_call_output", "call_id": "call_123", "output": "72 F and clear"}
  ],
  "mode": "private"
}
```

`tool_choice` accepts `auto`, `none`, `required`, or `{"type":"function","name":"get_weather"}`. `parallel_tool_calls` allows multiple independent calls in one response.

### Anthropic Messages tools

Messages names the function schema `input_schema` and returns `tool_use` content blocks:

```json
{
  "model": "leiolai-1",
  "max_tokens": 256,
  "messages": [{"role": "user", "content": "What is the weather in Chicago?"}],
  "tools": [{"name": "get_weather", "description": "Get the weather for a city",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}},
      "required": ["city"], "additionalProperties": false}}],
  "tool_choice": {"type": "auto"},
  "mode": "private"
}
```

Run each call in your application. Resend the assistant's `tool_use` block and follow it with a user `tool_result` block using the matching `tool_use_id`:

```json
{
  "model": "leiolai-1",
  "max_tokens": 256,
  "messages": [
    {"role": "user", "content": "What is the weather in Chicago?"},
    {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_123",
      "name": "get_weather", "input": {"city": "Chicago"}}]},
    {"role": "user", "content": [{"type": "tool_result",
      "tool_use_id": "toolu_123", "content": "72 F and clear"}]}
  ],
  "mode": "private"
}
```

`tool_choice` accepts `{"type":"auto"}`, `{"type":"none"}`, `{"type":"any"}`, or `{"type":"tool","name":"get_weather"}`.

## Structured outputs

Chat Completions uses `response_format`; Responses uses `text.format`. Anthropic Messages and text Completions do not accept a structured-output field.

### Chat Completions JSON

Use `response_format` when the assistant response itself must be JSON. Do not combine `response_format` with function tools in the same request.

```json
{
  "model": "leiolai-1",
  "mode": "private",
  "messages": [{"role": "user", "content": "Classify the sentiment as positive or negative."}],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "sentiment",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {"sentiment": {"type": "string", "enum": ["positive", "negative"]}},
        "required": ["sentiment"],
        "additionalProperties": false
      }
    }
  }
}
```

`{"type":"json_object"}` requires one valid JSON object. `json_schema` accepts `name`, optional `description`, optional `strict`, and `schema`. Successful content is one schema-valid JSON value with no Markdown fence or trailing prose.

### Responses JSON

```json
{
  "model": "leiolai-1",
  "input": "Classify the sentiment.",
  "text": {"format": {
    "type": "json_schema",
    "name": "sentiment",
    "strict": true,
    "schema": {"type": "object",
      "properties": {"sentiment": {"type": "string", "enum": ["positive", "negative"]}},
      "required": ["sentiment"], "additionalProperties": false}
  }},
  "mode": "private"
}
```

`text.format` also accepts `{"type":"json_object"}`. Read the generated JSON from the response's `output` message.

## Streaming

Every format accepts `stream: true`, but the event names and text fields differ. A short answer may arrive in one text chunk. Continuous generation has its own event stream, described below.

### Chat Completions streaming

Chat Completions sends `data:` events and ends with `data: [DONE]`. Leiolai returns one choice, so append `choices[0].delta.content` from each text chunk. Without streaming, read `choices[0].message.content` from one `chat.completion` object.

This example includes `"stream_options":{"include_usage":true}` in the request:

```text
data: {"id":"chatcmpl-8f1c2d3a4b5e6f7a8b9c0d1e","object":"chat.completion.chunk","created":1787000000,"model":"leiolai-1","choices":[{"delta":{"role":"assistant","content":"Hi there"},"index":0,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-8f1c2d3a4b5e6f7a8b9c0d1e","object":"chat.completion.chunk","created":1787000000,"model":"leiolai-1","choices":[{"delta":{},"index":0,"finish_reason":"stop"}],"usage":null}

data: {"id":"chatcmpl-8f1c2d3a4b5e6f7a8b9c0d1e","object":"chat.completion.chunk","created":1787000000,"model":"leiolai-1","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":2,"total_tokens":16}}

data: [DONE]
```

Read it:

- `id`: the response ID. It stays the same across every chunk. Include it when reporting a bad answer.
- `choices[0].delta.role`: `assistant`, on the first chunk only.
- `choices[0].delta.content`: append each value to build the reply. A short answer may arrive in one content chunk.
- `choices[0].delta.tool_calls`: collect calls by `index`. Keep the first `id`, append each `function.arguments` fragment in order, and use the completed JSON string only after the terminal `finish_reason: "tool_calls"` chunk.
- `data: [DONE]`: marks the end of the stream.
- `usage`: token counts for the request: `prompt_tokens`, `completion_tokens`, and `total_tokens`. A non-streaming response includes them when counts are available. A stream includes them only when you send `stream_options.include_usage: true`; OpenAI's usage-only chunk has an empty `choices` array and arrives immediately before `[DONE]`. Earlier chunks carry `usage: null`. When present, these report the token counts used for billing.
- `choices[0].finish_reason`: `stop` when Leiolai completed the answer, `tool_calls` when your application should execute returned functions, `length` when it reached your `max_completion_tokens` cap, and `content_filter` when the content policy stopped the response. Null before the terminal chunk.

### Responses streaming

Responses sends named events. Append `delta` from `response.output_text.delta`; assemble function arguments from `response.function_call_arguments.delta`. `response.output_item.done` contains each completed `message` or `function_call` item. The terminal event is `response.completed`, `response.incomplete`, or `response.failed`. There is no `[DONE]` sentinel. The current adapter may deliver the final text in one delta.

### Anthropic Messages streaming

Messages sends named `message_start`, content-block, `message_delta`, and `message_stop` events. Append `delta.text` from `content_block_delta` when its delta type is `text_delta`; a `tool_use` block's arguments arrive as `input_json_delta`. `message_delta` reports the stop reason and output usage. `message_stop` ends the stream. There is no `[DONE]` sentinel.

### Text Completions streaming

Text Completions sends `data:` chunks. Append `choices[0].text`. The terminal chunk has an empty `text` and a `finish_reason`, followed by `data: [DONE]`. Without streaming, read `choices[0].text` from one `text_completion` object.

## Continuous generation

Experimental. Continuous generation keeps a response open and lets you add context while it runs. There is no output-token ceiling. The session will end when you stop it or if your available balance or API budget is exhausted. The opening endpoint always returns server-sent events. It is a Leiolai extension, not a standard Chat Completions stream, so use an SSE client that preserves every event.

Open a session with `POST /v1/infinite/chat/completions`:

```bash
curl -N https://api.leiolai.com/v1/infinite/chat/completions \
  -H "Authorization: Bearer sb_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "leiolai-1",
    "messages": [{"role": "user", "content": "Teach me astronomy until I stop you."}],
    "reasoning_effort": "medium",
    "mode": "private",
    "lookahead": true,
    "consumer_lease": true,
    "realtime_audio": true
  }'
```

Opening fields:

- `model`, `messages`, `reasoning_effort`, and `mode` have the same meaning as on the finite endpoint. Text, image, and supported inline file parts work in both modes. You pay the input rate for the opening messages once. Inject updates do not add another input charge.
- `lookahead`: optional. When true, the stream includes a replaceable preview separate from delivered text.
- `consumer_lease`: optional. When true, send `consumer_heartbeat` while the stream is live. This lets Leiolai close the session if the downstream consumer disconnects but a proxy keeps the HTTP connection open.
- `realtime_audio`: optional. Set this when the client speaks delivered text as it arrives. Leiolai will not rewrite words the user may already have heard. Send buffer reports to pace delivery.

The stream begins with the session event:

```text
data: {"session_id":"inf-0123456789abcdef"}
```

Keep that opaque `session_id`. Send it as the `session` query parameter on every inject request. Send the same API key on the opening request and every inject. A session belongs to the API key that opened it.

The continuous stream has four data event shapes:

The `choices` field is the OpenAI-compatible response array. Leiolai returns one item, so read `choices[0]`. In a text event, `delta.content` is new text; append each value.

- `{"choices":[{"delta":{"content":"..."}}]}` is delivered answer text. Append every `content` value. Delivered bytes never change.
- `{"lookahead":"..."}` is the full current preview. Replace the previous preview with this value. An empty string clears it. Never append lookahead to delivered text.
- `{"inject_ack":{"id":"...","seq":1,"anchor":20,"text":"..."}}` confirms a completed user message. `anchor` tells you how much assistant text belongs before it and is measured in UTF-8 bytes from the start of the delivered answer.
- `data: [DONE]` ends the session. A pause in output does not end the session.

SSE comment lines are keepalives and can be ignored. One possible sequence is:

```text
data: {"session_id":"inf-0123456789abcdef"}

data: {"choices":[{"delta":{"content":"The first sentence. "}}]}

data: {"lookahead":"This preview may still change."}

data: {"lookahead":""}

data: {"inject_ack":{"id":"opaque-receipt-id","seq":1,"anchor":20,"text":"Wait, explain that more simply."}}

data: {"choices":[{"delta":{"content":"Here is the simpler version. "}}]}

: keepalive

data: [DONE]
```

### Inject context

Send live context to `POST /v1/infinite/inject?session=<session_id>`. The endpoint accepts these fields:

- `text`: the user's completed message.
- `text_partial`: the user's complete message so far. Each update replaces the previous value.
- `image`: the latest image as a base64 data URI. It replaces the prior live image after screening.
- `buffer`: the client's queued-output state. See Buffer control below.
- `consumer_heartbeat`: send only this field with `true` to confirm the downstream consumer is still connected. Use it only when the opening request set `consumer_lease: true`.
- `stop`: send `true` by itself to end the session.

Send inject requests one at a time, in order, within each session. Do not send `text` and `text_partial` together. Send `stop` by itself. Unknown fields return HTTP 400.

As the user interrupts, send the complete transcript so far through `text_partial`. Leiolai clears the old lookahead and pauses delivery. When the user finishes, send the completed message through `text`. Leiolai adds it to the conversation, sends `inject_ack` with the exact insertion point, and resumes from the updated context.

The final-injection POST also returns the receipt for correlation:

```json
{
  "ok": true,
  "inject_ack": {
    "id": "opaque-receipt-id",
    "seq": 1,
    "anchor": 20,
    "text": "Wait, explain that more simply."
  }
}
```

`inject_ack.anchor` tells you how much assistant text belongs before the user’s message. It is a UTF-8 byte count from the start of the delivered answer. Once you have received that many bytes, show the user’s message. Show any later answer text beneath it.

Opening messages accept the same image and inline file parts as finite chat. During a live session, `image` updates the current visual context. A live image must be a base64 data URI with up to 8 MiB of decoded image data; the complete inject body may be up to 12 MiB. Files cannot be added through the inject endpoint after the session opens.

### Buffer control

Buffer reports are optional. They tell Leiolai how much consumable output remains queued and how quickly it is draining. Use them for latency-sensitive playback or another consumer that can measure queued work in seconds. Text-only clients can ignore them.

Send:

```json
{
  "buffer": {
    "remaining_seconds": 1.2,
    "drain_rate": 1.0
  }
}
```

- `remaining_seconds` is the non-negative number of seconds currently queued by the client.
- `drain_rate` is the queue's consumption speed relative to real time, from `0` through `4`. Send `0` while paused or unable to consume, `1` at normal speed, and `2` at twice normal speed.

Report whenever queued output or its `drain_rate` changes. For latency-sensitive playback, periodic updates around every 500 ms can help correct timing drift. The server estimates the remaining buffer between reports. Less frequent updates are accepted. Send one request at a time so reports arrive in order.

At the current defaults, Leiolai pauses delivery when the client reports more than 2.5 seconds of queued output. Generation continues while delivery is paused, so lookahead may keep changing. Leiolai resumes delivery when the queue reaches 2.5 seconds or less. If the queue drops below 0.8 seconds and more output is ready, Leiolai may add enough to target about 1.5 seconds. These thresholds are controlled by the server. Clients should report their actual state instead of reproducing this logic.

## Errors

OpenAI-format endpoints use the JSON envelope and error codes below:

```json
{
  "error": {
    "message": "mode is required for unrestricted API keys. Send \"private\" or \"non-private\".",
    "type": "invalid_request_error",
    "param": "mode",
    "code": "invalid_value"
  }
}
```

`error.type` is the broad error class. `error.code` is the stable programmatic code, and `error.param` names the request field when one caused the failure. After an SSE stream begins, its HTTP status remains 200, so read the stream for failures. Responses sends `response.failed`; text Completions can send a named `error` event. If the content policy stops a finite Chat Completions stream, its final choice has `finish_reason: "content_filter"`. Messages reports `stop_reason: "refusal"`.

Anthropic Messages uses `{"type":"error","error":{"type":"authentication_error","message":"..."}}` for JSON errors and a named `error` event after streaming begins. HTTP statuses and request IDs still apply. The OpenAI error-code table below applies to the OpenAI-format endpoints.

Every API-generated response includes `X-Request-Id`. Log it when you contact support. You may send your own trace value in `X-Client-Request-Id`; valid values are echoed in the response.

| Status | Code | What it means |
| --- | --- | --- |
| 401 | invalid_api_key | No valid API key was provided. Check the bearer token. |
| 402 | insufficient_credits | Your available balance cannot cover this request. Top up or request less output. |
| 402 | api_budget_exhausted | The key or the account reached its API budget for the period. Raise or clear the budget in your account. |
| 402 | api_budget_required | Auto reload is on for the account, so API use needs a budget. Set one, or turn auto reload off. |
| 400 | invalid_value | A field is invalid, two fields conflict, or an unrestricted API key omits mode. |
| 400 | invalid_tool_schema | A function definition or its JSON Schema is invalid. |
| 400 | invalid_tool_result | Assistant tool-call history or a caller-supplied tool result is invalid. |
| 400 | context_length_exceeded | The request exceeds the available model context. Shorten the messages or tool history. |
| 400 | invalid_json | The request body is not valid JSON. |
| 403 | api_key_mode_restricted | The request conflicts with the API key's Private-only or Research-only restriction. |
| 403 | content_policy_violation | The content policy blocked the input before streaming began. |
| 403 | content_filter | The content policy stopped the response. An active finite stream reports `finish_reason: "content_filter"`. |
| 404 | model_not_found | The requested model is not available. |
| 404 | session_not_found | The continuous session ended, does not exist, or belongs to another API key. |
| 405 | method_not_allowed | This route does not accept that HTTP method. |
| 413 | request_too_large | The request body exceeds the accepted size. |
| 429 | rate_limit_exceeded | You exceeded the request rate limit. Wait for the number of seconds in `Retry-After`, then try again. |
| 500 | streaming_unavailable | Streaming is unavailable. Try again. |
| 503 | billing_unavailable | API billing is temporarily unavailable. Retry shortly. |
| 503 | api_budget_unverifiable | Spending records are temporarily unavailable. Retry shortly. |
| 503 | context_length_unavailable | The service could not verify the request's context length. Retry shortly. |
| 503 | vision_unavailable | Image understanding is temporarily unavailable. Retry shortly. |
| 503 | service_busy | The service is at capacity. Retry after the number of seconds in `Retry-After` when that header is present. |
| 503 | service_unavailable | The request could not be completed. Retry shortly. |
| 502 | invalid_tool_call | A generated tool call failed deterministic validation after repair. Retry the request. |

## Token pricing

Low, medium, and high Research rates use launch pricing. `xhigh` and Private use standard pricing.

| Reasoning effort | Research input, USD / 1M tokens | Research output, USD / 1M tokens | Private input, USD / 1M tokens | Private output, USD / 1M tokens |
| --- | --- | --- | --- | --- |
| low | ~~$20~~ $0.01 | ~~$90~~ $0.02 | $20 | $90 |
| medium | ~~$40~~ $0.25 | ~~$175~~ $0.65 | $40 | $175 |
| high | ~~$80~~ $6.40 | ~~$350~~ $21 | $80 | $350 |
| xhigh | $160 | $700 | $160 | $700 |
