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.
MarkdownOn this page
/v1/chat/completionsThis 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.
modelstringThe 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.
messagesarrayrequiredThe conversation so far, oldest first.
rolestringrequiredsystem, developer, user, assistant or tool.
contentstring | arrayThe 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_callsarrayassistant messages only: the tool calls the model asked for in an earlier turn, sent back unchanged.
reasoning_detailsarrayassistant 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_idstringtool messages only, and required there: the id of the tool call whose result you are returning.
streambooleanWhen true, the response arrives in pieces as Server-Sent Events. Defaults to false. See Streaming chunk.
stream_optionsobjectAccepted for OpenAI compatibility. You don't need include_usage: Lykia asks the provider for usage itself and returns it in the last chunk.
max_tokensintegerThe 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_tokensintegerSame 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.
temperaturenumberSampling temperature. Lower values give steadier output, higher values more variety.
top_pnumberNucleus sampling threshold.
frequency_penaltynumberPenalises tokens that already appear often, reducing repetition.
presence_penaltynumberPenalises tokens that have appeared at all, nudging the model towards new topics.
stopstring | string[]One or more strings at which generation stops.
seedintegerA fixed seed that, on models that support it, makes repeated requests more likely to return the same output.
toolsarrayFunctions the model may call, each { "type": "function", "function": { "name", "description", "parameters" } } where parameters is a JSON Schema. See Tool calling.
tool_choicestring | objectnone, auto, required, or { "type": "function", "function": { "name": "…" } } to force one function.
parallel_tool_callsbooleanWhether the model may request several tool calls in one response.
response_formatobjectOutput format: { "type": "text" }, { "type": "json_object" }, or { "type": "json_schema", "json_schema": { "name", "strict", "schema" } } for JSON that follows a schema. See Structured outputs.
logprobsbooleanReturn the log probabilities of the generated tokens.
top_logprobsintegerWith logprobs on, how many of the most likely tokens to return for each position.
userstringLykia-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.
metadataobjectLykia-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.
reasoningobjectHow 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.
cachestringauto 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.
providerobjectLykia-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.
sortstringOnly 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_fallbacksbooleanDefaults 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,usageand, to OpenAI only,prompt_cache_key. Every other field is dropped without an error. Among them aren(you get a single choice),service_tier,store,metadata,prediction,modalities,audioandimage_config(no audio or image output), andpluginsandweb_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
userandmetadata, and Lykia's ownmodels,providerandcachefields, never reach the provider, and Lykia never turns on storage at the provider (OpenAI always receivesstore: 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/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Generation-Id: gen-1795379366-omQUb1mhiPl4498Y
X-Max-Tokens-Applied: 4983This 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
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
}'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": "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,
},
timeout=60,
)
response.raise_for_status()
completion = response.json()
print(completion["choices"][0]["message"]["content"])
print(completion["provider"], completion["usage"]["cost"])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: "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,
}),
});
if (!response.ok) {
throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
}
const completion = await response.json();
console.log(completion.choices[0].message.content);
console.log(completion.provider, completion.usage.cost);package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
payload, _ := json.Marshal(map[string]any{
"model": "openai/gpt-4o-mini",
"messages": []map[string]string{
{"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,
})
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()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
panic(fmt.Sprintf("Lykia returned %d: %s", resp.StatusCode, body))
}
var completion struct {
Provider string `json:"provider"`
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
Usage struct {
Cost float64 `json:"cost"`
} `json:"usage"`
}
if err := json.Unmarshal(body, &completion); err != nil {
panic(err)
}
fmt.Println(completion.Choices[0].Message.Content)
fmt.Println(completion.Provider, completion.Usage.Cost)
}{
"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
idstringLykia'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.
objectstringAlways chat.completion.
createdintegerCreation time as a Unix timestamp in seconds.
modelstringThe model that actually served the request. After a fallback this differs from the model you asked for.
providerstringThe id of the provider that served the request (for example openai, anthropic); the values are the slug values listed by GET /providers.
choicesarrayThe generated answer, as the provider returned it.
indexintegerPosition of the choice.
messageobjectrole (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_reasonstringWhy generation stopped, such as stop, length, tool_calls or content_filter.
usageobjectToken counts and cost.
prompt_tokensintegerInput tokens, including those read from or written to the cache.
completion_tokensintegerGenerated tokens, including reasoning tokens.
total_tokensintegerThe sum of the two.
costnumberWhat 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_byokbooleantrue when the request went out with one of your project's provider keys.
cost_detailsobjectupstream_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_detailsobjectcached_tokens (input read from the cache) and cache_write_tokens (input written to the cache).
completion_tokens_detailsobjectreasoning_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.
objectstringAlways chat.completion.chunk.
choicesarrayWhat changed in this chunk.
indexintegerPosition of the choice.
deltaobjectThe new part: role in the first chunk, then content, tool_calls, reasoning or reasoning_details arriving piece by piece.
finish_reasonstring | nullnull until the choice is finished.
usageobjectOnly 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." }]
}'import json
import os
import requests
with requests.post(
"https://api.getlykia.com/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
json={
"model": "openai/gpt-4o-mini",
"stream": True,
"messages": [{"role": "user", "content": "Say hello in Turkish."}],
},
stream=True,
timeout=120,
) as response:
response.raise_for_status()
for line in response.iter_lines(decode_unicode=True):
if not line or not line.startswith("data: "):
continue # blank separators and SSE comment lines
data = line[len("data: "):]
if data == "[DONE]":
break
chunk = json.loads(data)
for choice in chunk.get("choices", []):
print(choice["delta"].get("content") or "", end="", flush=True)
if chunk.get("usage"):
print("\ncost (USD):", chunk["usage"]["cost"])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: "openai/gpt-4o-mini",
stream: true,
messages: [{ role: "user", content: "Say hello in Turkish." }],
}),
});
if (!response.ok || !response.body) {
throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
}
const decoder = new TextDecoder();
let buffer = "";
for await (const bytes of response.body) {
buffer += decoder.decode(bytes, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue; // blank separators and SSE comment lines
const data = line.slice("data: ".length);
if (data === "[DONE]") continue;
const chunk = JSON.parse(data);
process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
if (chunk.usage) console.log(`\ncost (USD): ${chunk.usage.cost}`);
}
}What the raw stream looks like:
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." }]
}'import os
from openai import OpenAI
client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])
# Lykia-specific fields are not part of the OpenAI SDK signature; send them with extra_body.
completion = client.chat.completions.create(
model="anthropic/claude-sonnet-4.5",
messages=[{"role": "user", "content": "Summarise the plot of Hamlet in two sentences."}],
extra_body={
"models": ["openai/gpt-4o", "google/gemini-2.5-flash"],
"provider": {"order": ["anthropic"], "ignore": ["deepinfra"], "allow_fallbacks": True},
},
)
print(completion.model, completion.choices[0].message.content)import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });
// Lykia-specific fields are not in the SDK's types, so the request object is widened.
const request = {
model: "anthropic/claude-sonnet-4.5",
messages: [{ role: "user" as const, content: "Summarise the plot of Hamlet in two sentences." }],
models: ["openai/gpt-4o", "google/gemini-2.5-flash"],
provider: { order: ["anthropic"], ignore: ["deepinfra"], allow_fallbacks: true },
};
const completion = await client.chat.completions.create(request as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);
console.log(completion.model, completion.choices[0].message.content);The model and provider fields of the response tell you which model and provider ended up answering.
Errors
| Code | When |
|---|---|
400 | The 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 |
401 | The key is missing, invalid, disabled, archived or expired, or the company is suspended |
402 | Not 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 |
403 | The 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 |
404 | The model does not exist, has been removed or is turned off |
408 | Every provider that was tried timed out |
413 | The body is larger than the size limit |
429 | The 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 |
502 | The providers that were tried returned errors |
503 | No 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.