# Provider routing

> Use the provider object to choose which providers may serve a request and in what order, see how Lykia orders candidates, and how it all combines with your project's routing settings.

A model can be available from more than one provider: open-weight models are often hosted by several, and a model can be reached both with your project's own provider key and through Lykia's direct connection to that provider. For every request Lykia builds a list of candidates and tries them one after another. The default order suits most workloads. When you want to put a particular provider first, keep one out, or pin a request to one provider, add a `provider` object to the request.

## How Lykia orders candidates

Anywhere a request could be served is a candidate. For each model, Lykia orders candidates in two tiers:

1. **Your project's provider keys (BYOK).** If the project has its own key for a provider that serves the model, the request is tried with that key first. See [Bring your own key (BYOK)](https://www.getlykia.com/en/docs/guides/byok).
2. **Lykia's direct connection to the provider.** For providers where Lykia has its own key, the request goes out on Lykia's account and is billed to your credits. Only connections that have a price in the catalog are used in this tier.

There is no other tier: Lykia does not send requests on to another place through an intermediary. The `provider` field of a response is always the id of the provider that served it (for example `openai`, `anthropic`, `mistral`). Within each tier, candidates are ordered by price, cheapest first.

The preferences in `provider` narrow and reorder this list. Lykia then works through it, moving to the next candidate when the current one fails with:

- a connection error or a timeout,
- a rate limit (`429`) or a server error (`5xx`) from the provider,
- the provider rejecting the credentials Lykia sent (`401`, `402`, `403`),
- the provider not offering the model (`404`).

Other `4xx` errors are caused by the request itself, such as an invalid parameter or messages longer than the context window. Another provider would reject the same request, so Lykia does not move on: you get `400` (or `413` for a body that is too large) with the provider's message.

> **Note:** Only the attempt that produces the response is billed. Attempts that fail, or that Lykia moves past, cost nothing.

The `provider` field of the response tells you who served the request:

**Request**

cURL

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistralai/mistral-small-3.2-24b-instruct",
    "messages": [{ "role": "user", "content": "Summarise the CAP theorem in two sentences." }],
    "provider": {
      "order": ["mistral", "deepinfra"],
      "allow_fallbacks": true
    }
  }'
```

Python

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

completion = client.chat.completions.create(
    model="mistralai/mistral-small-3.2-24b-instruct",
    messages=[{"role": "user", "content": "Summarise the CAP theorem in two sentences."}],
    # Lykia-specific fields go in extra_body; the SDK sends them as part of the JSON body.
    extra_body={"provider": {"order": ["mistral", "deepinfra"], "allow_fallbacks": True}},
)
print(completion.model_extra.get("provider"), completion.choices[0].message.content)
```

TypeScript

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

// The SDK types do not know Lykia's extra fields, so the body is cast; the field is sent as-is.
const completion = await client.chat.completions.create({
  model: "mistralai/mistral-small-3.2-24b-instruct",
  messages: [{ role: "user", content: "Summarise the CAP theorem in two sentences." }],
  provider: { order: ["mistral", "deepinfra"], allow_fallbacks: true },
} as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);

console.log((completion as unknown as { provider: string }).provider, completion.choices[0].message.content);
```

**Response (200)**

```json
{
  "id": "gen-1795416169-zxkuvpWsY2pIumm9",
  "object": "chat.completion",
  "created": 1795416169,
  "model": "mistralai/mistral-small-3.2-24b-instruct",
  "provider": "mistral",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "A distributed system can guarantee at most two of consistency, availability and partition tolerance at the same time. Since network partitions will happen, the real choice is between consistency and availability while a partition lasts."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 41,
    "total_tokens": 65,
    "cost": 0.00001,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.00001,
      "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 `provider` object

`provider` is an optional object in the [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions) body. Providers are referred to by id (`openai`, `anthropic`, `google-ai-studio`, `mistral`, `groq`, `together` and so on); [`GET /providers`](https://www.getlykia.com/en/docs/api-reference/providers) lists the ids.

- `order` (string\[]) — Providers to try first, in the order given. Providers not in the list come after them, unless `allow_fallbacks` is turned off.
- `only` (string\[]) — Use these providers and nothing else. Every other candidate is dropped.
- `ignore` (string\[]) — Never use these providers.
- `sort` (string) — Only `"price"`. Without it, your own provider keys come first and each tier is ordered by price; with it, every candidate, including your own keys at their list-price equivalent, is ordered by price, cheapest first, and `order` is applied after that. Throughput and latency are not measured, so any other value gets `400` with the code `unsupported_sort`.
- `allow_fallbacks` (boolean, default true) — Set to `false` and Lykia tries only the providers listed in `order`; if `order` is empty, only the first provider in the list. If they fail, you get an error instead of a response from some other provider.

A `sort` other than `"price"` is rejected rather than ignored, so a client written for another gateway finds out at once:

```json
{
  "error": {
    "message": "`provider.sort` supports only \"price\" (throughput and latency are not measured)",
    "type": "invalid_request_error",
    "code": "unsupported_sort",
    "status": 400,
    "metadata": {
      "reason": "invalid_request"
    }
  }
}
```

### What is passed on to the provider

On requests that go out with Lykia's key, the provider receives only the body fields listed in [What is sent to the provider](https://www.getlykia.com/en/docs/api-reference/chat-completions#what-is-sent-to-the-provider); requests with your own provider keys are passed on in full. The `models` and `provider` fields belong to Lykia and are never sent to a provider.

### Set a provider order

The most common case is putting a preferred provider first. The example above sends the Mistral Small request to Mistral's own API first and to DeepInfra second, where they serve the model; candidates not in the list come after them and are still tried because `allow_fallbacks` is on.

**cURL**

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistralai/mistral-small-3.2-24b-instruct",
    "messages": [{ "role": "user", "content": "Summarise the CAP theorem in two sentences." }],
    "provider": {
      "order": ["mistral", "deepinfra"],
      "allow_fallbacks": true
    }
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

completion = client.chat.completions.create(
    model="mistralai/mistral-small-3.2-24b-instruct",
    messages=[{"role": "user", "content": "Summarise the CAP theorem in two sentences."}],
    # Lykia-specific fields go in extra_body; the SDK sends them as part of the JSON body.
    extra_body={"provider": {"order": ["mistral", "deepinfra"], "allow_fallbacks": True}},
)
print(completion.model_extra.get("provider"), completion.choices[0].message.content)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

// The SDK types do not know Lykia's extra fields, so the body is cast; the field is sent as-is.
const completion = await client.chat.completions.create({
  model: "mistralai/mistral-small-3.2-24b-instruct",
  messages: [{ role: "user", content: "Summarise the CAP theorem in two sentences." }],
  provider: { order: ["mistral", "deepinfra"], allow_fallbacks: true },
} as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);

console.log((completion as unknown as { provider: string }).provider, completion.choices[0].message.content);
```

### Exclude providers

`ignore` keeps specific providers out. This request never uses DeepInfra, even where it serves the model.

**cURL**

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistralai/mistral-small-3.2-24b-instruct",
    "messages": [{ "role": "user", "content": "Give me three names for a staging environment." }],
    "provider": {
      "ignore": ["deepinfra"]
    }
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

completion = client.chat.completions.create(
    model="mistralai/mistral-small-3.2-24b-instruct",
    messages=[{"role": "user", "content": "Give me three names for a staging environment."}],
    extra_body={"provider": {"ignore": ["deepinfra"]}},
)
print(completion.choices[0].message.content)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const completion = await client.chat.completions.create({
  model: "mistralai/mistral-small-3.2-24b-instruct",
  messages: [{ role: "user", content: "Give me three names for a staging environment." }],
  provider: { ignore: ["deepinfra"] },
} as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);

console.log(completion.choices[0].message.content);
```

### Pin a request to one provider

If data must only go to a specific provider, narrow the list with `only` and switch off fallbacks with `allow_fallbacks: false`. When that provider cannot answer, the request ends in an error and Lykia does not go anywhere else.

**cURL**

```bash
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",
    "messages": [{ "role": "user", "content": "Review this SQL for injection risks: SELECT * FROM users WHERE id = $1" }],
    "provider": {
      "only": ["anthropic"],
      "allow_fallbacks": false
    }
  }'
```

> **Warning:** `only` combined with `allow_fallbacks: false` trades availability for control: an outage at that one provider becomes an outage for you. Use it when you have a hard requirement, and make sure your [error handling](https://www.getlykia.com/en/docs/guides/errors) expects it.

## How project settings fit in

Projects have routing settings too: a default model, which models are allowed (patterns with a `*` wildcard, like `openai/*`), providers to leave out, a sort preference, and whether to use BYOK keys only. These rules apply to every request in the project, and the `provider` preferences in a request work **inside** them. A request can narrow and reorder what is left, but it cannot open up a model or provider the project has closed.

- A model outside the allowed list returns `403`. So does a request in a BYOK-only project when none of its provider keys can serve the model.
- If no candidate is left once the rules and preferences are applied, the response is `503`.
- If candidates are left but none of them can be paid for (for example, the available balance, key limit or budget cannot cover the request), the response is `402`, or `429` when the free-model limit or the limit on requests in flight is reached. See [Reservations](https://www.getlykia.com/en/docs/guides/credits-and-billing#reservations).
- If there were candidates but every one of them failed, you get `502`; when every attempt timed out, `408`; when every provider answered `429`, `429`.

Project settings are covered in [Projects](https://www.getlykia.com/en/docs/guides/projects#routing-settings).

## Next steps

- [Model fallbacks](https://www.getlykia.com/en/docs/guides/model-fallbacks): line up models, not just providers.
- [Errors](https://www.getlykia.com/en/docs/guides/errors): how to handle `403` and `503` responses.
- [Providers reference](https://www.getlykia.com/en/docs/api-reference/providers): list provider ids.
