Skip to content

Errors

Lykia's error body, what each status code it returns means, and which errors to retry versus which mean the request needs fixing.

Markdown
On 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

402 Payment Required
{
  "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"
    }
  }
}
errorobject

Present in every error response, and in the error event of a stream.

messagestring

An English description of what went wrong. Log it or show it to a developer, but do not branch on its text.

typestring

The 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).

codestring

A 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…).

statusinteger

The HTTP status as a number.

metadataobject

Always 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:

reasonMeaning
invalid_requestThe request is malformed or the provider rejected it as such.
unauthorizedThe API key is missing, invalid, disabled, archived or expired, or the company is suspended (401).
forbiddenThe key or the project does not allow this, or the project is archived (403).
context_length_exceededThe prompt is longer than the model's context window.
content_policyThe provider refused the content.
rate_limitedA rate limit was hit; wait and retry.
overloadedThe provider is overloaded; retry later.
timeoutEvery provider that was tried timed out.
provider_authA provider rejected the credentials it was given.
provider_errorProviders failed without producing a response.
no_providerNo provider can serve the request with the current settings.
insufficient_creditsThe balance (or plan) cannot pay for the request.
limit_exceededA key limit, project budget or the free-model daily limit is used up.
unsupported_inputThe 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

CodeMeaningWhat to do
400Invalid 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.
401The 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.
402The 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.
403The 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.
404Model 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.
408Every provider that was tried timed out.Retry after a short wait; if it keeps happening, send a smaller request or use streaming.
413The 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.
429The 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.
502The providers that were tried failed and none produced a response.Retry. If it persists, add a fallback model or allow more providers.
503No 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:

CodeStatusMeaningWhat to do
unsupported_input400The 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_model400The 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_configured400An image url was requested while Lykia's storage is not available.Ask for response_format: "b64_json".
consent_required400A voice clone without consent=true.Clone only with the speaker's permission, and say so with consent=true.
platform_sales_disabled403The model's provider is not offered on Lykia credits yet.Add your own key for that provider to the project (BYOK).
byok_only_no_key403The 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_found404The voice id is unknown or belongs to another project.List voices with GET /audio/voices.
timeout408An image provider did not finish within the wait (provider_code: image_wait_exceeded). Not charged.Retry, or pick a faster model.
video_not_ready409The video's file was requested before the job completed.Read the job until status is completed.
job_not_cancellable409The job has finished, or the provider cannot cancel it at this stage.Nothing to do; a finished job keeps its result.
video_expired410The video's file was deleted after its expires_at.Generate it again; download files you want to keep.
provider_busy429Lykia's connection to the provider is at its limit of requests at once.Retry after Retry-After.
media_queue_full429The 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). 503 only 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"])

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:
        raise

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