Skip to content

OpenAI-compatible API

lean serve exposes an HTTP API shaped like OpenAI’s, so most clients and SDKs work by changing the base URL.

Terminal window
lean serve lean-agent-light --port 8080
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="dummy")
resp = client.chat.completions.create(
model="lean-agent-light",
messages=[{"role": "user", "content": "Explain expert offloading in two sentences."}],
)
print(resp.choices[0].message.content)

The server holds one model and serves one request at a time. Concurrent requests queue rather than interleave.

Without --api-key (or LEAN_API_KEY) the API is open, which is why the default bind address is loopback-only. With a key set, every /v1 route requires it:

Authorization: Bearer <key>

/health is always reachable, key or not, so process supervisors do not need credentials.

Field Type Default Notes
messages array required {"role": "...", "content": "..."}. Roles: system, user, assistant.
model string server’s model Accepted and echoed back; the server serves whatever it was launched with.
max_tokens integer model limit Rejected with 400 if larger than the model’s context length. Otherwise capped at the room the prompt leaves; a prompt that does not fit the context at all is a 400.
temperature number 0.7 0 is greedy.
top_p number unset Nucleus sampling.
seed integer random Fixes sampling for reproducible output.
repetition_penalty number 1.0 (off) Extension, as in vLLM (repeat_penalty is accepted too). Penalises tokens seen in the last 64. Off by default: a penalty corrupts output that has to repeat itself exactly, such as code, JSON, tool calls and arithmetic.
stream boolean false Server-sent events instead of one JSON body.
thinking boolean model default Extension. false skips the <think> phase, true asks for it. Ignored by models without one. The default is on, except lean-agent-cruiser, whose context is capped at 2,048 tokens for now.
chat_template_kwargs object unset Variables for the model’s chat template, as vLLM and llama.cpp accept them. enable_thinking here takes precedence over thinking, so clients that toggle thinking this way work unchanged.
{
"id": "chatcmpl-...",
"object": "chat.completion",
"created": 1769472000,
"model": "lean-agent-light",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"reasoning_content": "The user wants a short explanation...",
"content": "Expert offloading keeps only the experts a token actually routes to in VRAM..."
},
"finish_reason": "stop"
}
],
"usage": { "prompt_tokens": 24, "completion_tokens": 96, "total_tokens": 120 }
}

finish_reason is stop when the model emits an end-of-sequence token, or length when it hits max_tokens.

On thinking models, the <think> block is split out into reasoning_content rather than left inline in content. The field is omitted entirely when there is no reasoning to report, so clients that ignore it still see clean prose.

With "stream": true the response is text/event-stream. The first chunk carries the role, subsequent chunks carry content (or reasoning_content) deltas, the last chunk carries finish_reason and usage, and the stream ends with the literal data: [DONE].

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Expert"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":24,"completion_tokens":96,"total_tokens":120}}
data: [DONE]

A chat client sends the whole conversation on every turn, and an agent sends it on every step. lean serve keeps what it computed for the last chat request, so a request that starts with the same messages only processes what is new. On a 6,000-token conversation that takes the wait for the first token from about 1.4 s to 0.1 s on lean-agent-light, and from about 7 s to 0.5 s on lean-coder-welter on one 24 GB card.

  • It works across turns with thinking on, and across the steps of a tool loop. Nothing needs to be enabled or sent.
  • usage.prompt_tokens_details.cached_tokens says how many prompt tokens were reused (usage.input_tokens_details.cached_tokens on /v1/responses). prompt_tokens still counts the whole prompt.
  • A new conversation that starts with the same system prompt and tools reuses that part, from the third such conversation on.
  • The server holds one conversation at a time. A request from a different conversation is processed in full apart from a shared system prompt.
  • Changing anything early in the prompt, such as a timestamp in the system message, means everything after it is processed again.
  • lean-agent-cruiser does not reuse prompts yet, and neither does /v1/completions.

The legacy raw-text endpoint. It exists mainly so evaluation harnesses that score prompts (lm-eval-harness and friends) can drive the runtime.

Field Type Default Notes
prompt string or array required
max_tokens integer 16 OpenAI’s legacy default, not the chat default.
temperature number 0.7
top_p number unset
stop string or array unset Stop strings, trimmed from the output.
seed integer random
logprobs integer unset Return per-token logprobs. Only the top-1 alternative is reported.
echo boolean false Include the prompt in the response, with its logprobs when scoring.

Setting max_tokens: 0 with echo and logprobs selects pure scoring mode: the server runs a single chunked all-position prefill and returns per-token prompt logprobs without generating anything.

Unlike the chat endpoint, this one applies no chat template and no repeat penalty. What you send is what the model sees.

Lists the one model this server is hosting, in OpenAI’s list shape.

{
"object": "list",
"data": [
{ "id": "lean-agent-light", "object": "model", "created": 1769472000, "owned_by": "leanmodels" }
]
}

Returns ok with status 200. Unauthenticated.

Errors use OpenAI’s envelope:

{ "error": { "message": "max_tokens (999999) exceeds the model's maximum context length (262144)", "type": "invalid_request_error", "code": null } }
Status When
400 Malformed body, or max_tokens beyond the model’s context length.
401 Missing or wrong bearer key when one is configured.
408 Generation exceeded --request-timeout-secs.
500 Generation failed. The server recovers; the next request is served normally.

tools on the request and tool_calls on the response are supported on every model that lean serves, for streaming and non-streaming requests. A turn that calls a tool returns finish_reason: "tool_calls", and content: null when the model said nothing else, matching the OpenAI schema.

Tool syntax is not implemented by lean - it comes from the chat template the model authors shipped, which is stored in the model pack. That is why the format is always the one the model was trained on rather than an approximation.

What to know before you wire up a client:

  • A streamed tool call arrives whole. With "stream": true, text streams as usual and each tool call arrives in a single delta carrying its index, id, function.name and the complete function.arguments string, once the model has finished writing it. Clients that accumulate argument fragments work unchanged; there is just one fragment. No tool markup reaches content.
  • tool_choice is accepted but not enforced. "none" hides the tools from the model for that turn. lean does not constrain decoding, so "required" or a named function cannot guarantee the model emits that call.
  • Message content may be a string or a list of text parts. Image parts are ignored. The developer role is treated as system, and max_completion_tokens is accepted for max_tokens.
  • The Responses API works too. POST /v1/responses accepts instructions, input items, function tools, max_output_tokens and stream, and returns reasoning, message and function_call output items. The server keeps no conversation state, so previous_response_id is rejected: send the whole conversation in input each turn, as Codex does. Built-in tools such as web_search are ignored.

If the model emits a malformed tool call, the block is returned as ordinary message content, delimiters and all, rather than erroring. You see exactly what the model produced instead of the request failing.

These are reasoning models. They spend tokens inside a <think> block before producing anything you see, and max_tokens covers both. Set it too low and the budget is gone before the visible answer starts, so you get an empty content with finish_reason: "length":

// max_tokens: 32
{ "content": "", "finish_reason": "length" }
// max_tokens: 512
{ "content": "hello", "finish_reason": "stop" }

Nothing failed in the first case, the model simply never got to the answer. The same applies to tool calls, which are also emitted after thinking: too small a budget yields no tool_calls rather than a wrong one.

Give tool-calling requests room. A few hundred tokens is enough for a short call, and reasoning on a hard prompt can use far more. If you do not want thinking at all, send "thinking": false (or "chat_template_kwargs": {"enable_thinking": false}) and the whole budget goes to the answer.

  • Multiple completions. No n parameter; one choice per request.
  • Concurrency. Requests are serialised behind a single model instance.
  • Multiple models per server. One process serves one model. Run several processes on different ports if you need more.
  • Multimodal content. content is a plain string; no image or audio parts.
  • logit_bias, presence_penalty, frequency_penalty, and response_format are ignored if sent.