Skip to content
Docs

Using the API

Streaming

Send "stream": true and tokens arrive as the model writes them, as Server-Sent Events (text/event-stream) in the format of the endpoint you called. It works the same in the three APIs and on every model. If a stream gets cut, you pay for the input and only the output that reached you.

Chat completions

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="deepseek-v4.1-flash-1017",
    messages=[{"role": "user", "content": "Write a haiku about open models"}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage.total_tokens, "tokens")

Each event is a data: line with a chat.completion.chunk, and the stream ends with data: [DONE]. Models that reason send their thinking in delta.reasoning_content before the answer.

text/event-stream
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"deepseek-v4.1-flash-1017","choices":[{"index":0,"delta":{"content":"Open"}}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"deepseek-v4.1-flash-1017","choices":[{"index":0,"delta":{"content":" weights,"}}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"deepseek-v4.1-flash-1017","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":17,"total_tokens":31}}

data: [DONE]

Usage at the end of the stream

Ask for "stream_options": {"include_usage": true} and the last chunk before [DONE] carries usage, with an empty choices array. Without it, the stream has no token count. Either way, you are billed for the tokens actually used.

Messages

import os
from anthropic import Anthropic

client = Anthropic(base_url="https://api.libremodel.ai", api_key=os.environ["LIBREMODEL_API_KEY"])

with client.messages.stream(
    model="deepseek-v4.1-flash-1017",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a haiku about open models"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    print("\n", stream.get_final_message().usage)

The usual Messages events: message_start, content_block_start, content_block_delta, content_block_stop, message_delta and message_stop. Usage always comes in message_start and message_delta, and the final count is the one in message_delta; there is nothing to ask for.

Responses

The usual Responses events, from response.created to response.completed (or response.incomplete if the response was cut short, for example by max_output_tokens), each with its sequence_number. Usage always comes in that last event; there is nothing to ask for.

Keepalive comments

A stream can include lines that start with :, even before the first event. They are SSE comments that keep the connection open. SDKs and SSE clients skip them; if you parse the stream yourself, ignore them.

Errors during a stream

If the request fails before the first event, nothing is charged. Usually you get a regular HTTP error (Limits and errors); if the model takes long to start, the stream may already be open with status 200 and keepalive comments, and the failure arrives as an error event. Once the first event is sent, a failure arrives as one last error event, in the format of the endpoint, and the stream closes.

data: {"error":{"message":"The response was interrupted. You were only charged for what was delivered.","type":"server_error","code":"upstream_interrupted"}}
Error codes inside a stream
CodeWhat happenedWhat to do
upstream_interruptedThe model stopped sending in the middle of the response, or the service restarted.Retry the request. You were charged only for what was delivered.
upstream_timeoutThe model went silent for too long, or the response took too long overall.Retry the request.
insufficient_balanceThe response used up what your balance covers.Top up, or set a lower max_tokens.
key_limit_exceededThe response used up what remains of the key's spending limit.Raise the key's limit, or set a lower max_tokens.

With the Messages format the event carries no code: use error.message and error.type. In Responses it is an error event with code and message at the top level.

Without streaming

Without "stream": true the response is a single JSON object, as usual. While the model writes, the body can start with blank lines (\n) before the JSON: they keep the connection open on long responses. JSON parsers and the SDKs skip them; if you check the body yourself, trim the leading whitespace before parsing it.

Once those lines are sent, the status is already 200. If the model fails after that, the body is the error in the format of the endpoint (in the OpenAI formats, a JSON object with only error), with the codes in the table above, and you pay as for a stream cut in the middle: the input plus the output the model generated, estimated.

What a cut stream costs

How each ending is charged
How the stream endsWhat you pay
It completesThe usage the model reports.
It is cut in the middle, with an error eventThe input, plus the output delivered to you, estimated from the text you received.
You close the connectionGeneration stops right away. You pay for the input and the output delivered.
It fails before the first eventNothing.

To stop a response early, close the connection (in the SDKs, break out of the loop or abort the request). The model stops generating, and you stop paying for output.