Errors
Lykia's error body, what each status code it returns means, and which errors to retry versus which mean the request needs fixing.
MarkdownOn this page
When a request fails, Lykia returns a non-2xx HTTP status and a JSON body that always has the same shape. Branch on the status code, the string code or the error class in metadata.reason; the message is written for humans and may change.
Error body
{
"error": {
"message": "Insufficient credits. Add credits to your balance, or add your own provider key (BYOK) to this project.",
"type": "invalid_request_error",
"code": "insufficient_credits",
"status": 402,
"metadata": {
"reason": "insufficient_credits"
}
}
}errorobjectPresent in every error response, and in the error event of a stream.
messagestringAn English description of what went wrong. Log it or show it to a developer, but do not branch on its text.
typestringThe OpenAI-style type: authentication_error (401), permission_error (403), rate_limit_error (429), provider_error (502, 504), server_error (other 5xx) or invalid_request_error (other 4xx).
codestringA stable machine code, always a string: for example invalid_api_key, project_archived, insufficient_credits, key_limit_exceeded, budget_exceeded, model_not_found, model_not_allowed, preset_not_found, invalid_tags, unsupported_input, unsupported_sort or no_provider. When no specific code applies, it is derived from the status (bad_request, rate_limited, provider_error…).
statusintegerThe HTTP status as a number.
metadataobjectAlways has reason (below). When a provider caused the error it also has provider (the provider's id) and its own message in raw, with any secrets removed; when waiting helps, retry_after in seconds.
metadata.reason is a small, stable set of error classes, so one mapping in your code covers every provider:
reason | Meaning |
|---|---|
invalid_request | The request is malformed or the provider rejected it as such. |
unauthorized | The API key is missing, invalid, disabled, archived or expired, or the company is suspended (401). |
forbidden | The key or the project does not allow this, or the project is archived (403). |
context_length_exceeded | The prompt is longer than the model's context window. |
content_policy | The provider refused the content. |
rate_limited | A rate limit was hit; wait and retry. |
overloaded | The provider is overloaded; retry later. |
timeout | Every provider that was tried timed out. |
provider_auth | A provider rejected the credentials it was given. |
provider_error | Providers failed without producing a response. |
no_provider | No provider can serve the request with the current settings. |
insufficient_credits | The balance (or plan) cannot pay for the request. |
limit_exceeded | A key limit, project budget or the free-model daily limit is used up. |
unsupported_input | The model cannot read part of the input (a file type, an image, audio on credits). |
Messages are in English whatever your interface language, for OpenAI compatibility. The OpenAI SDKs turn this body into their own error types; they read code, type and the message from it, and you read the status code from the SDK's error object.
Status codes
| Code | Meaning | What to do |
|---|---|---|
400 | Invalid request: a missing or malformed field, broken JSON, no model and no project default model, an undefined preset (preset_not_found) or one whose model does not fit the endpoint (preset_modality_mismatch), tags over their limits (invalid_tags), a file the model cannot read (unsupported_input) or more than eight files (too_many_files), a provider.sort other than price (unsupported_sort), or audio input to a model with an audio price on credits (it works with your own provider key). A provider rejecting the request itself (an unsupported parameter, a prompt longer than the context window) also returns 400, with the provider's message. | Fix the request. Retrying gives the same result. |
401 | The API key is missing, invalid, disabled, archived or expired, or the company is suspended. | Check the Authorization header and that the key is active in the dashboard. |
402 | The company is out of credits or still on the Free plan, the key's spending limit or the project's budget has been reached, or what is left of the balance, limit or budget cannot cover the request's prompt and a minimal completion. | Top up, raise the key limit or project budget, wait for the limit to reset, or send a shorter prompt or a lower max_tokens. |
403 | The key's project has been archived (project_archived), the model is not on the project's allowed list, or the project only allows its own provider keys and none of them can serve the model. | Use a key from an active project, check the project's routing settings, or pick another model. |
404 | Model not found: the id is misspelled, or the model has been removed or turned off. Also returned for an unknown request id in GET /generation and for an unknown path. | Check the id with GET /models. |
408 | Every provider that was tried timed out. | Retry after a short wait; if it keeps happening, send a smaller request or use streaming. |
413 | The request body is larger than Lykia's size limit, or a provider said the request is too large. | Send a smaller body; send images by URL rather than inline. |
429 | The key's per-minute rate limit was hit (with Retry-After), the daily limit for free models was reached, the company has too many paid requests in flight at once, or every provider that could serve the request was rate limited. | Wait and retry, and slow down your request rate or run fewer requests at once. For the free-model limit, wait until 00:00 UTC or use a paid model. |
502 | The providers that were tried failed and none produced a response. | Retry. If it persists, add a fallback model or allow more providers. |
503 | No provider is available for the request with the current routing settings, or no provider Lykia connects to offers the model with a price and the project has no key of its own for a provider that offers it. | Widen your routing preferences or the project's settings, pick another model from GET /models, or add your own key for the model's provider; retrying alone rarely helps. |
Two rarer codes: 415 when the body uses a content encoding Lykia does not accept, and 500 for an unexpected error inside Lykia (retry it like a 502).
For transient provider failures (connection errors, timeouts, 429, 5xx, a provider rejecting the credentials it was given, a model that is no longer offered), Lykia already tries the next provider, and the next model if you defined fallbacks, before anything reaches you. A 408, 429 or 502 from the gateway means those candidates ran out. See Provider routing and Model fallbacks.
Image, video and audio errors
The media endpoints use the same error body. These codes are specific to them:
| Code | Status | Meaning | What to do |
|---|---|---|---|
unsupported_input | 400 | The model does not accept a value (metadata.param names the field: a size, duration, format or provider_options entry), or the option combination is not priced yet (the message says "not priced yet"; it works with your own provider key). Nothing was sent to the provider. | Pick a value from the model's media.capabilities in GET /models. |
unsupported_model | 400 | The model is of another kind than the endpoint, for example a speech model in an image request. | Use a model of the right kind. |
storage_not_configured | 400 | An image url was requested while Lykia's storage is not available. | Ask for response_format: "b64_json". |
consent_required | 400 | A voice clone without consent=true. | Clone only with the speaker's permission, and say so with consent=true. |
platform_sales_disabled | 403 | The model's provider is not offered on Lykia credits yet. | Add your own key for that provider to the project (BYOK). |
byok_only_no_key | 403 | The project only allows its own provider keys and has none for this model. | Add a key for the model's provider or pick another model. |
voice_not_found | 404 | The voice id is unknown or belongs to another project. | List voices with GET /audio/voices. |
timeout | 408 | An image provider did not finish within the wait (provider_code: image_wait_exceeded). Not charged. | Retry, or pick a faster model. |
video_not_ready | 409 | The video's file was requested before the job completed. | Read the job until status is completed. |
job_not_cancellable | 409 | The job has finished, or the provider cannot cancel it at this stage. | Nothing to do; a finished job keeps its result. |
video_expired | 410 | The video's file was deleted after its expires_at. | Generate it again; download files you want to keep. |
provider_busy | 429 | Lykia's connection to the provider is at its limit of requests at once. | Retry after Retry-After. |
media_queue_full | 429 | The project already has the most video jobs Lykia lets it keep waiting. | Wait for jobs to finish, then retry. |
A provider that charges for a rejected request (for example on content grounds) is reported with metadata.billed_by_provider: true, and that cost is charged; a failed video job carries the same flag in its error. Otherwise failed, cancelled and timed-out media requests are free.
More on 402
A 402 has these possible causes: the company's balance has run out, the company is on the Free plan and the model is paid, the spending limit of the key that sent the request has been reached, or the project's budget is used up. It also comes before any of those reaches zero when what is left, after the reservations of requests in flight, cannot cover the request's prompt and a minimal completion; Lykia reserves each request's maximum cost first, so that usage never takes them past zero (Reservations). Requests with your own provider keys get 402 when the balance is at or below zero and the month's BYOK allowance is used up. The message and code say which: insufficient_credits for the balance or plan, key_limit_exceeded and budget_exceeded for the key limit and the project budget. An empty balance reads "Insufficient credits. Add credits to your balance, or add your own provider key (BYOK) to this project." You can also check the company balance, the key's usage and the project's budget in the dashboard. From the API, GET /key returns the key's limit and what is left, and GET /credits returns the company balance, what is reserved and what is available. Limits explains how each limit works.
Retrying
Retry only transient errors:
- Retry:
408,429,502, and network errors (dropped connections, timeouts).503only after you have changed the routing settings, or after a longer wait. - Do not retry:
400,401,403,404,413. Nothing changes until the request or the settings do. 402: only after topping up or raising the limit, or once the limit has reset.
Wait between attempts with exponential backoff plus random jitter, so that many clients do not retry in lockstep. If the response includes a Retry-After header (or error.metadata.retry_after), wait that many seconds. Cap the number of attempts. By error class: rate_limited, overloaded, timeout and provider_error are worth retrying; the others are not until something changes.
import os
import random
import time
import requests
RETRYABLE = {408, 429, 502, 503}
def chat(payload: dict, max_attempts: int = 5) -> dict:
for attempt in range(1, max_attempts + 1):
try:
response = requests.post(
"https://api.getlykia.com/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
json=payload,
timeout=120,
)
except (requests.ConnectionError, requests.Timeout):
if attempt == max_attempts:
raise
else:
if response.ok:
return response.json()
error = response.json().get("error", {})
if response.status_code not in RETRYABLE or attempt == max_attempts:
reason = error.get("metadata", {}).get("reason")
raise RuntimeError(f"{error.get('status')} {error.get('code')} ({reason}): {error.get('message')}")
retry_after = response.headers.get("Retry-After")
if retry_after and retry_after.isdigit():
time.sleep(int(retry_after))
continue
# Exponential backoff with full jitter: up to 1s, 2s, 4s, 8s ...
time.sleep(random.uniform(0, 2 ** (attempt - 1)))
raise RuntimeError("unreachable")
result = chat({"model": "openai/gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}]})
print(result["choices"][0]["message"]["content"])const RETRYABLE = new Set([408, 429, 502, 503]);
type LykiaError = {
error: { message: string; type: string; code: string; status: number; metadata: { reason: string; provider?: string; retry_after?: number } };
};
async function chat(payload: object, maxAttempts = 5): Promise<any> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
let response: Response;
try {
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(payload),
});
} catch (networkError) {
if (attempt === maxAttempts) throw networkError;
await sleep(Math.random() * 2 ** (attempt - 1) * 1000);
continue;
}
if (response.ok) return response.json();
const { error } = (await response.json()) as LykiaError;
if (!RETRYABLE.has(response.status) || attempt === maxAttempts) {
throw new Error(`${error.status} ${error.code} (${error.metadata.reason}): ${error.message}`);
}
const retryAfter = Number(response.headers.get("Retry-After"));
// Exponential backoff with full jitter unless the server asked for a specific wait.
await sleep(retryAfter > 0 ? retryAfter * 1000 : Math.random() * 2 ** (attempt - 1) * 1000);
}
throw new Error("unreachable");
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const result = await chat({ model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }] });
console.log(result.choices[0].message.content);package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"time"
)
type lykiaError struct {
Error struct {
Message string `json:"message"`
Code string `json:"code"`
Status int `json:"status"`
Metadata struct {
Reason string `json:"reason"`
} `json:"metadata"`
} `json:"error"`
}
func retryable(status int) bool {
return status == 408 || status == 429 || status == 502 || status == 503
}
func chat(payload []byte, maxAttempts int) ([]byte, error) {
for attempt := 1; attempt <= maxAttempts; attempt++ {
req, err := http.NewRequest(http.MethodPost, "https://api.getlykia.com/v1/chat/completions", bytes.NewReader(payload))
if err != nil {
return nil, 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 {
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
return nil, readErr
}
if resp.StatusCode == http.StatusOK {
return body, nil
}
var e lykiaError
_ = json.Unmarshal(body, &e)
if !retryable(resp.StatusCode) || attempt == maxAttempts {
return nil, fmt.Errorf("%d %s (%s): %s", e.Error.Status, e.Error.Code, e.Error.Metadata.Reason, e.Error.Message)
}
} else if attempt == maxAttempts {
return nil, err
}
// Exponential backoff with full jitter: up to 1s, 2s, 4s, 8s ...
limit := time.Duration(1<<(attempt-1)) * time.Second
time.Sleep(time.Duration(rand.Int63n(int64(limit))))
}
return nil, fmt.Errorf("unreachable")
}
func main() {
payload, _ := json.Marshal(map[string]any{
"model": "openai/gpt-4o-mini",
"messages": []map[string]string{{"role": "user", "content": "Hello!"}},
})
body, err := chat(payload, 5)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(string(body))
}The OpenAI SDKs retry some transient errors on their own, and you set the number of attempts in the client options. Branch on the status code from the SDK's error object:
import os
import openai
from openai import OpenAI
# The SDK already retries some failures; max_retries sets how many times.
client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"], max_retries=3)
try:
completion = client.chat.completions.create(
model="openai/gpt-4o-mini",
messages=[{"role": "user", "content": "Hello!"}],
)
print(completion.choices[0].message.content)
except openai.APIStatusError as exc:
# exc.code is Lykia's string code; exc.body is the error object, its class is in metadata.reason
reason = (exc.body or {}).get("metadata", {}).get("reason") if isinstance(exc.body, dict) else None
if reason in ("insufficient_credits", "limit_exceeded"):
print("Out of credits or over a limit:", exc.code, exc.message)
elif reason in ("unauthorized", "forbidden"):
print("Check the API key and the project settings:", exc.code, exc.message)
else:
raiseimport OpenAI from "openai";
// The SDK already retries some failures; maxRetries sets how many times.
const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY, maxRetries: 3 });
try {
const completion = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [{ role: "user", content: "Hello!" }],
});
console.log(completion.choices[0].message.content);
} catch (err) {
if (!(err instanceof OpenAI.APIError)) throw err;
// err.code is Lykia's string code; the error class is in metadata.reason
const reason = (err.error as { metadata?: { reason?: string } } | undefined)?.metadata?.reason;
if (reason === "insufficient_credits" || reason === "limit_exceeded") console.error("Out of credits or over a limit:", err.code, err.message);
else if (reason === "unauthorized" || reason === "forbidden") console.error("Check the API key and the project settings:", err.code, err.message);
else throw err;
}Every response from the API, including errors, carries an X-Generation-Id header. Log it next to the status code so you can point to the exact request later; for requests that reached a provider it is also the id of the request record.
Errors while streaming
With stream: true, an error that happens before the first chunk means the stream never starts: you get an ordinary error response with the body above. Check the status code before you start reading. If the provider fails after the stream has started, the status stays 200 and Lykia sends a separate error event: an object with id, object, created, model, provider and the same error object as above, but no choices, followed by data: [DONE]. If the connection closes before the final usage chunk, treat the response as incomplete. See Streaming.
Next steps
- Limits: key limits, project budgets and rate limits.
- Authentication and API keys: the usual causes of
401. - API reference: every endpoint uses the same error body.