# How Lykia works

> How companies, projects, API keys, credits and BYOK fit together on every request, what happens to a request inside Lykia, and how provider fallback works.

Every request you send to Lykia takes the same path. The key is recognised, the project's settings are applied, Lykia checks how the request will be paid for (credits, your own provider key or a model Lykia has marked free), forwards it to a suitable provider and, at the end, works out the cost and records it. This page walks through that path and the ideas behind it.

## Companies and projects

Your account is a **company**. Team members, roles, the credit balance and payments all sit at company level. A company has one or more **projects**: a project is one of your products or environments, such as `mobile-app`, `internal-tools` or `staging`.

These belong to a project:

- API keys
- Provider keys (BYOK)
- Budget and routing settings (default model, allowed models, ignored providers)
- Request logs and usage statistics

That way, different products in the same company keep their spending, limits and logs apart. A project called "Default" is created together with the company. More in [Projects](https://www.getlykia.com/en/docs/guides/projects).

## API keys

Every request to the gateway carries an API key. Keys start with `lyk-v1-` and belong to exactly one project. From the key, Lykia knows which project a request is for, who pays for it and which limits apply. Each key can have its own spending limit, expiry date and status. More in [Authentication and API keys](https://www.getlykia.com/en/docs/guides/authentication).

## Who pays for a request

A request is paid for in one of three ways:

- **Credits**: the prepaid USD balance of the company. The cost is calculated from the model's list price and deducted from the balance. See [Credits and billing](https://www.getlykia.com/en/docs/guides/credits-and-billing).
- **Your own key (BYOK)**: requests sent with a provider key you added to the project are billed to you by that provider. Lykia does not take an inference charge from your credits for them. See [Bring your own key (BYOK)](https://www.getlykia.com/en/docs/guides/byok).
- **Free models**: models Lykia has marked as free. Lykia covers their cost, and they are usable up to a daily request limit that depends on your plan and is shared by all companies with the same owner. There are no free models by default; Lykia decides which models are free, and the [model catalog](https://www.getlykia.com/en/models) on the site marks them.

The request log tells you which one applied: each record has a usage type of `credits`, `byok` or `free`.

## The life of a request

When a `POST /chat/completions` request reaches Lykia, this happens in order:

1. **The key is checked.** Lykia computes the key's hash and looks it up. A missing, unknown, disabled, archived or expired key, or a key whose company is suspended, gets `401`; a key whose project has been archived gets `403`. Lykia keeps the result in memory for a short time, so a change you make to a key (disabling it, for example) can take a few seconds to reach the gateway.
2. **The key's rate limit is applied.** Each key may send a limited number of requests per minute; above that you get `429` with a `Retry-After` header. The limit is set by Lykia; see [Limits](https://www.getlykia.com/en/docs/guides/limits#rate-limits-429).
3. **The body is read and the model is resolved.** A body larger than the size limit gets `413`. The id in `model` is looked up in the catalog; when you leave `model` out, the project's default model is used, and if the project has none you get `400`. A model that is not in the catalog, has been removed or has been turned off returns `404`; a model outside the project's allowed list returns `403`.
4. **Candidates are lined up.** For each model, Lykia lists the places that can serve it in two tiers: the project's own provider keys first, then Lykia's direct connection to the provider (only connections that have a price in the catalog). Lykia does not send requests on to another place through an intermediary. The project's routing settings and the request's `provider` preferences are applied to this list. If the project only allows its own provider keys and none of them can serve the model, you get `403`; if nothing else is left, `503`.
5. **Pre-flight checks run.** If the key's spending limit or the project's budget has been reached, you get `402`. Then each candidate must be payable: a candidate that uses your own provider key is, unless the balance is at or below zero and the company's BYOK allowance for the month is used up; a free model is, until the daily free-model limit is used up (`429` once it is); a paid model needs a plan that allows paid models and a credit balance above zero (`402` otherwise).
6. **Candidates are tried in turn.** Right before each attempt, Lykia reserves the most the attempt can cost against the balance, and against the key's spending limit and the project's budget when they are set, and sends the provider an output limit that reservation covers (reported in the `X-Max-Tokens-Applied` header). A free model takes its place in the daily count at this point. A candidate that cannot be covered is skipped; if none can, you get `402` (or `429`, for example when the free-model limit is reached). See [Reservations](https://www.getlykia.com/en/docs/guides/credits-and-billing#reservations). A connection error, a timeout, a rate limit, a server error, a provider that rejects the credentials it was given, or a provider that no longer offers the model moves the request on to the next candidate. An error caused by the request itself, such as an invalid parameter, would fail the same way everywhere, so it comes straight back to you.
7. **The response is passed back to you.** If you asked for streaming, chunks are forwarded as they arrive.
8. **Cost is calculated and recorded.** Once the response is complete, Lykia computes the cost from the token counts the provider reports, takes it from the balance in place of the reservation, updates the key's usage and the daily totals, and writes the request record.

> **Note:** Only the attempt that produced the response is billed. Attempts that failed, or that Lykia moved on from, cost nothing. Requests rejected in steps 1 to 5, or in step 6 before any provider was tried, are not billed and are not written to the request log.

## Provider fallback

A model can often be served by more than one candidate: your project's own key and Lykia's direct connection, or several providers that offer the model. Because of the ordered attempts in step 6, a provider that is briefly failing or rate-limiting you usually does not fail your request: the next candidate answers, and the only visible difference is the `provider` field in the response. You can change which providers are tried, and in what order, with the request's `provider` object: see [Provider routing](https://www.getlykia.com/en/docs/guides/provider-routing).

Falling back to a different *model* when the model itself cannot answer is a separate feature, configured with the `models` array: see [Model fallbacks](https://www.getlykia.com/en/docs/guides/model-fallbacks).

## What you see in the response

Responses use the OpenAI Chat Completions format. Three fields are worth knowing:

```json
{
  "id": "gen-1795373724-GNtDgXTt5L42PjqQ",
  "object": "chat.completion",
  "created": 1795373724,
  "model": "openai/gpt-4o-mini",
  "provider": "openai",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "An AI gateway sits between your application and model providers, giving you one API to call while it routes, bills and logs each request."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 17,
    "completion_tokens": 27,
    "total_tokens": 44,
    "cost": 0.000019,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.000019,
      "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"
}
```

- `model`: the model that served the request.
- `provider`: the id of the provider that served the request (for example `openai`).
- `usage.cost`: the cost of the request in USD.

Pass the `id` to [`GET /generation`](https://www.getlykia.com/en/docs/api-reference/generation) to get the full record of the request: attempts, timings and usage type.

## Next steps

- [Quickstart](https://www.getlykia.com/en/docs/quickstart): Send your first request.
- [Models](https://www.getlykia.com/en/docs/models): Model ids and how prices are expressed.
- [Limits](https://www.getlykia.com/en/docs/guides/limits): Key limits, project budgets and rate limits.
- [Errors](https://www.getlykia.com/en/docs/guides/errors): Status codes and retries.
