Skip to content

Chat completions

Generates a model response for a conversation. Accepts the OpenAI Chat Completions body plus Lykia's models and provider fields; set stream to receive the response as it is generated.

Markdown
On this page
POST/v1/chat/completions

This endpoint takes an OpenAI Chat Completions request and answers in the same format. Lykia sends the request to a provider that serves the model in model. If that provider cannot answer, Lykia moves on to the next suitable provider, or to the next model in models. Only the attempt that produces the response is billed.

Request body

Lykia checks the fields it relies on (model, messages, stream, models, provider, user, metadata, reasoning, cache, cache_control markers, file parts, and that tools is an array) and returns 400 when they are malformed. Lykia does not validate the other fields; which of them reach the provider depends on the route the request takes (see What is sent to the provider). A parameter a model does not support does not get the request rejected by Lykia. The supported_parameters field in GET /models lists what each model supports.

modelstring

The model id, in author/model form (for example openai/gpt-4o-mini), or a preset as @name (for example @text), which brings its own fallbacks and defaults. See Models and Model presets. Required unless the project has a default model; without either you get 400.

messagesarrayrequired

The conversation so far, oldest first.

rolestringrequired

system, developer, user, assistant or tool.

contentstring | array

The message text. To mix text with images or files, pass an array of parts: { "type": "text", "text": "…" }, { "type": "image_url", "image_url": { "url": "…" } } and { "type": "file", "file": { "filename", "file_data": "data:<mime>;base64,…" } } (PDF or image, at most eight per request; see File inputs). Only models with image or file in their input_modalities read those parts. A part, and a system message, may carry a cache_control marker (see Reasoning and prompt caching). Required except on assistant messages that only carry tool_calls.

tool_callsarray

assistant messages only: the tool calls the model asked for in an earlier turn, sent back unchanged.

reasoning_detailsarray

assistant messages only: the thinking blocks the model returned in an earlier turn, sent back unchanged so that it can continue its thinking in a tool loop.

tool_call_idstring

tool messages only, and required there: the id of the tool call whose result you are returning.

streamboolean

When true, the response arrives in pieces as Server-Sent Events. Defaults to false. See Streaming chunk.

stream_optionsobject

Accepted for OpenAI compatibility. You don't need include_usage: Lykia asks the provider for usage itself and returns it in the last chunk.

max_tokensinteger

The most tokens the response may contain. Lykia may lower it, or set it when you leave it out, so that the request's cost fits what is available; the value it sends is returned in the X-Max-Tokens-Applied header (see Output limit). For Anthropic models, which require a maximum, Lykia uses the model's maximum output from the catalog when no limit applies otherwise.

max_completion_tokensinteger

Same purpose as max_tokens, under OpenAI's newer name. Use whichever the model lists in supported_parameters. Lykia writes its limit into the field you used; when you used neither, into max_completion_tokens for OpenAI and max_tokens for other providers.

temperaturenumber

Sampling temperature. Lower values give steadier output, higher values more variety.

top_pnumber

Nucleus sampling threshold.

frequency_penaltynumber

Penalises tokens that already appear often, reducing repetition.

presence_penaltynumber

Penalises tokens that have appeared at all, nudging the model towards new topics.

stopstring | string[]

One or more strings at which generation stops.

seedinteger

A fixed seed that, on models that support it, makes repeated requests more likely to return the same output.

toolsarray

Functions the model may call, each { "type": "function", "function": { "name", "description", "parameters" } } where parameters is a JSON Schema. See Tool calling.

tool_choicestring | object

none, auto, required, or { "type": "function", "function": { "name": "…" } } to force one function.

parallel_tool_callsboolean

Whether the model may request several tool calls in one response.

response_formatobject

Output format: { "type": "text" }, { "type": "json_object" }, or { "type": "json_schema", "json_schema": { "name", "strict", "schema" } } for JSON that follows a schema. See Structured outputs.

logprobsboolean

Return the log probabilities of the generated tokens.

top_logprobsinteger

With logprobs on, how many of the most likely tokens to return for each position.

userstring

Lykia-specific tag: an id for your own end user or tenant, at most 128 characters. Lykia stores it with the request record so you can filter logs and break usage down per user; it is never sent to the provider. Send a pseudonymous id rather than personal data. See Tags and usage breakdown.

metadataobject

Lykia-specific tags: up to 16 string key-value pairs (keys 1–64 characters, without . and not starting with $; values at most 512 characters), stored with the record and never sent to the provider. Over the limits: 400 with the code invalid_tags.

reasoningobject

How much the model should think: { "effort": "low" | "medium" | "high" }, { "max_tokens": n } or { "enabled": false }, plus exclude: true to leave the thinking text out of the response. Lykia translates it to each provider's own setting. See Reasoning and prompt caching.

cachestring

auto or off (default). With auto, Lykia places the prompt-cache breakpoint itself for providers that need an explicit one, when the request has no cache_control markers of its own.

modelsstring[]

Lykia-specific. Fallback order: Lykia tries model first and, if it gets no response, each model in this list in turn. Repeated ids are ignored, as are entries past the maximum number of backups. See Model fallbacks.

providerobject

Lykia-specific. Which providers may serve the request, and in what order. Your project's routing settings always apply; this field narrows the choice within them. See Provider routing.

orderstring[]

Providers to try first, in this order (for example ["anthropic", "openai"]).

onlystring[]

Use these providers and no others.

ignorestring[]

Never use these providers.

sortstring

Only price: every candidate, including your own provider keys at their list-price equivalent, is ordered cheapest first before order is applied. Any other value returns 400 with the code unsupported_sort.

allow_fallbacksboolean

Defaults to true. When false, only the providers in order are tried (only the first provider when order is empty), and the request fails if none of them succeeds.

What is sent to the provider

  • With your own provider key (BYOK): an OpenAI-compatible provider receives the body as you sent it, including fields Lykia does not know.
  • With Lykia's keys: only these fields are passed on: model, messages, stream, stream_options, max_tokens, max_completion_tokens, temperature, top_p, top_k, min_p, top_a, frequency_penalty, presence_penalty, repetition_penalty, seed, stop, tools, tool_choice, parallel_tool_calls, response_format, structured_outputs, logprobs, top_logprobs, logit_bias, reasoning, reasoning_effort, include_reasoning, verbosity, transforms, usage and, to OpenAI only, prompt_cache_key. Every other field is dropped without an error. Among them are n (you get a single choice), service_tier, store, metadata, prediction, modalities, audio and image_config (no audio or image output), and plugins and web_search_options (web search, file parsing): add-ons whose cost cannot be measured with the catalog's token prices.
  • Anthropic and Google AI Studio: Lykia translates the fields that have an equivalent in their API and drops the rest.
  • On every route: the tags user and metadata, and Lykia's own models, provider and cache fields, never reach the provider, and Lykia never turns on storage at the provider (OpenAI always receives store: false). Which features each provider family supports is in the compatibility matrix.

Audio input (input_audio parts) to a model that has an audio price cannot be measured either: with Lykia's keys it returns 400; with your own key it is passed on.

Output limit

Before each attempt, Lykia reserves the most the request can cost (its prompt and its output limit at the model's prices) against the company balance, and against the key's spending limit and the project's budget when they are set (see Reservations). The output limit sent to the provider is one that reservation covers: the value you asked for, lowered if what is available does not cover it, or, when you sent none, the model's maximum output or less if that is all the available amount covers. When Lykia set or lowered the limit, the response carries the value in the X-Max-Tokens-Applied header:

http
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Generation-Id: gen-1795379366-omQUb1mhiPl4498Y
X-Max-Tokens-Applied: 4983

This request to openai/gpt-4o had no max_tokens, and the company's available balance covered fewer output tokens than the model's maximum. An answer that reaches the limit ends with finish_reason: "length". If the available amount cannot cover the prompt plus a minimal completion (16 tokens, or fewer if you asked for fewer), the request returns 402 without reaching a provider. Requests to free models, and requests with your own provider key when neither the key limit nor the project budget counts BYOK spending, reserve nothing: the limit you sent goes out unchanged and the header is absent.

For Anthropic models with extended thinking, when Lykia lowers the output limit it also lowers the thinking budget to fit below it, and turns thinking off when the budget would fall under Anthropic's minimum.

Example

Request
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [
      { "role": "system", "content": "You are a concise assistant." },
      { "role": "user", "content": "What is a token in a language model?" }
    ],
    "max_tokens": 200,
    "temperature": 0.3
  }'
Response200
{
  "id": "gen-1795373724-YQhkPKb4HcCr0wWN",
  "object": "chat.completion",
  "created": 1795373724,
  "model": "openai/gpt-4o-mini",
  "provider": "openai",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "A token is a small piece of text, often a word or part of a word, that the model reads and writes. Prices and context limits are counted in tokens."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 27,
    "completion_tokens": 34,
    "total_tokens": 61,
    "cost": 0.000024,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.000024,
      "platform_fee": 0,
      "is_byok": false
    },
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0
    }
  },
  "system_fingerprint": "fp_560af6e559"
}

The response also carries the request's id in the X-Generation-Id header. When model was a preset, the X-Lykia-Preset header names it; when Lykia had to turn thinking off for the request, X-Lykia-Reasoning: dropped is set.

Response object

idstring

Lykia's id for the request, in the form gen-<time>-<random>. Keep it if you want to look the request up later with GET /generation.

objectstring

Always chat.completion.

createdinteger

Creation time as a Unix timestamp in seconds.

modelstring

The model that actually served the request. After a fallback this differs from the model you asked for.

providerstring

The id of the provider that served the request (for example openai, anthropic); the values are the slug values listed by GET /providers.

choicesarray

The generated answer, as the provider returned it.

indexinteger

Position of the choice.

messageobject

role (assistant), content (the text; can be null when the model only calls tools), tool_calls for any tool calls the model requested, reasoning with the model's readable thinking text when the provider returns it, and reasoning_details, the opaque thinking blocks to send back unchanged in a tool loop.

finish_reasonstring

Why generation stopped, such as stop, length, tool_calls or content_filter.

usageobject

Token counts and cost.

prompt_tokensinteger

Input tokens, including those read from or written to the cache.

completion_tokensinteger

Generated tokens, including reasoning tokens.

total_tokensinteger

The sum of the two.

costnumber

What the request cost, as a USD decimal. If you pay with credits, this is the amount taken from your balance; for requests sent with your own provider key it is 0. How it is calculated: Credits and billing.

is_byokboolean

true when the request went out with one of your project's provider keys.

cost_detailsobject

upstream_cost (the request at list price; for BYOK, what the provider bills you), platform_fee (the BYOK fee for this request once the month's allowance is used up, otherwise 0) and is_byok.

prompt_tokens_detailsobject

cached_tokens (input read from the cache) and cache_write_tokens (input written to the cache).

completion_tokens_detailsobject

reasoning_tokens: the model's thinking tokens.

Other top-level fields an OpenAI-compatible provider returns, such as system_fingerprint, are passed through unchanged.

Streaming chunk

With "stream": true the response is sent as text/event-stream. Each event is a JSON object on a line starting with data: , and the stream ends with data: [DONE]. The id, created, model and provider fields mean the same as in the response object and repeat in every chunk.

objectstring

Always chat.completion.chunk.

choicesarray

What changed in this chunk.

indexinteger

Position of the choice.

deltaobject

The new part: role in the first chunk, then content, tool_calls, reasoning or reasoning_details arriving piece by piece.

finish_reasonstring | null

null until the choice is finished.

usageobject

Only in the final data chunk, with the same fields as in the response object, cost_details included. That chunk's choices is empty.

When the provider fails after the stream has started, Lykia sends a separate event with id, object, created, model, provider and an error object (the same fields as the error body), without choices, then data: [DONE]. No usage chunk follows. See Streaming.

curl -N https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "stream": true,
    "messages": [{ "role": "user", "content": "Say hello in Turkish." }]
  }'

What the raw stream looks like:

text/event-stream
data: {"id":"gen-1795373697-UdlzoYmB1uOtzcxN","object":"chat.completion.chunk","created":1795373697,"model":"openai/gpt-4o-mini","provider":"openai","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],"system_fingerprint":"fp_560af6e559"}

data: {"id":"gen-1795373697-UdlzoYmB1uOtzcxN","object":"chat.completion.chunk","created":1795373697,"model":"openai/gpt-4o-mini","provider":"openai","choices":[{"index":0,"delta":{"content":"Merhaba! "},"logprobs":null,"finish_reason":null}],"system_fingerprint":"fp_560af6e559"}

data: {"id":"gen-1795373697-UdlzoYmB1uOtzcxN","object":"chat.completion.chunk","created":1795373697,"model":"openai/gpt-4o-mini","provider":"openai","choices":[{"index":0,"delta":{"content":"Nasılsınız?"},"logprobs":null,"finish_reason":null}],"system_fingerprint":"fp_560af6e559"}

data: {"id":"gen-1795373697-UdlzoYmB1uOtzcxN","object":"chat.completion.chunk","created":1795373697,"model":"openai/gpt-4o-mini","provider":"openai","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"system_fingerprint":"fp_560af6e559"}

data: {"id":"gen-1795373697-UdlzoYmB1uOtzcxN","object":"chat.completion.chunk","created":1795373697,"model":"openai/gpt-4o-mini","provider":"openai","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":5,"total_tokens":17,"cost":0.000005,"is_byok":false,"cost_details":{"upstream_cost":0.000005,"platform_fee":0,"is_byok":false},"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":0},"completion_tokens_details":{"reasoning_tokens":0}}}

data: [DONE]

If the client disconnects, Lykia cancels the request to the provider as well; tokens generated up to that point are billed. More in Streaming.

Fallbacks and provider preferences

The request below tries anthropic/claude-sonnet-4.5 on Anthropic first and never uses the deepinfra provider. If the model cannot answer, openai/gpt-4o and then google/gemini-2.5-flash are tried. With the OpenAI SDK, Lykia-specific fields go in extra_body (Python) or in a widened request object (TypeScript).

curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "models": ["openai/gpt-4o", "google/gemini-2.5-flash"],
    "provider": {
      "order": ["anthropic"],
      "ignore": ["deepinfra"],
      "allow_fallbacks": true
    },
    "messages": [{ "role": "user", "content": "Summarise the plot of Hamlet in two sentences." }]
  }'

The model and provider fields of the response tell you which model and provider ended up answering.

Errors

CodeWhen
400The body is invalid (missing field, wrong type, broken JSON), no model was given and the project has no default, the preset is not defined (preset_not_found) or its model is not a chat model (preset_modality_mismatch), tags are over their limits (invalid_tags), a file part cannot be read by the model (unsupported_input) or there are more than eight (too_many_files), provider.sort is not price (unsupported_sort), audio input was sent to a model with an audio price without your own key, or the provider rejected the request itself
401The key is missing, invalid, disabled, archived or expired, or the company is suspended
402Not enough balance, a paid model on the Free plan, the key limit or project budget is used up, what is left of any of them cannot cover the prompt and a minimal completion, or (with your own key) the balance is at or below zero and the month's BYOK allowance is used up
403The key's project is archived, the model is not allowed for this project, or a BYOK-only project has no key that can serve it
404The model does not exist, has been removed or is turned off
408Every provider that was tried timed out
413The body is larger than the size limit
429The key's rate limit (with Retry-After), the daily limit on free models, too many paid requests in flight at once, or every provider rate limited the request
502The providers that were tried returned errors
503No suitable provider is available for the request (for example the routing settings ruled out every candidate, or no provider Lykia connects to offers the model with a price and the project has no key of its own for one that does)

The error body and retry advice are on the Errors page.