# Bring Your Own Key (BYOK)

> Attach your own provider API keys so AnyRouter routes requests through your accounts at list price with no markup.


# Bring Your Own Key (BYOK)

BYOK lets you attach your own provider keys (OpenAI, Anthropic, Google, Groq, DeepSeek, Together AI, Mistral AI, DeepInfra, xAI, OpenRouter, Z-AI and others). Matching requests go out on your key, you pay the provider at list price, and AnyRouter adds no markup or fee. Logs, analytics, presets and routing still work. Azure OpenAI, Amazon Bedrock and Vertex AI take structured credentials; the dialog shows the format. Your key is only sent to the provider it is scoped to (or Cloudflare AI Gateway as transport).

## Add a key

::::steps

:::step{title="Open the BYOK dashboard"}
Go to [Dashboard → BYOK](https://anyrouter.dev/dashboard/byok) and click **Add key** on a provider.
:::

:::step{title="Paste the key and options"}
Paste the key (write-only). Optionally set a **Key alias** (shown in logs), a **Base URL** for regional or enterprise deployments, and **Priority** / **Weight** for multiple keys. For Z-AI pick Standard (`https://api.z.ai/api/paas/v4`) or Coding Plan (`https://api.z.ai/api/coding/paas/v4`).
:::

:::step{title="Save"}
AnyRouter validates the key with the provider once, then stores it. If validation fails the key is not saved.
:::

::::

To limit a key to certain AnyRouter API keys, edit its scope on the provider card; other keys fall back to credits. Delete with the trash icon (no undo, in-flight requests finish). Toggle **Enabled** off first to watch traffic shift. Per-provider key steps are in the [BYOK Provider Setup Guide](/features/byok-providers).

## How requests are routed

### Routing precedence: BYOK vs. managed capacity

1. **Per-request override.** An `X-AnyRouter-BYOK-Key` header naming a key alias uses only that key. If it is missing, disabled or cannot serve the model, the request fails.
2. **Always use keys.** Tried first for matching models (see below).
3. **Regular BYOK keys**, chosen by the load-balancing strategy. If all fail, the request falls to managed capacity.
4. **Managed capacity**, billed in credits, when you have no key for the provider or every attempt failed and no Strict pin applies.

The `byok_key_alias` field in the request log shows which path was taken.

### Always use modes

- **Prefer** (default): the pinned key goes first. On 401, 402, 429 or 5xx, other keys and then managed capacity are used.
- **Strict**: only the pinned key serves matching models. No credits and no community pool. If it fails the request fails with `byok_always_use_exhausted`.

**Only these models** limits a pin to listed model ids. A pin is skipped for a model its provider cannot serve. After three 401 or 402 responses in a row the pin relaxes (Strict becomes Prefer, Prefer is released); any success resets the count. Fix the key, then turn **Always use** on again or press **Re-enable pin**.

When a pin applies, the response has `anyrouter_metadata.routingReason`:

| Value | Meaning |
|-------|---------|
| `pinned:<provider>` | The pinned key served the request. |
| `pin_fallback:<status>` | The pinned key failed with this status and another route served it (Prefer). |
| `pin_skipped:unservable` | The pinned provider cannot serve this model. |

### Load balancing multiple keys

Set per provider card. Disabled keys are always skipped, and **Always use** keys go first.

- **Fallback** (default): lowest priority number first, next key on error.
- **Round Robin**: cycle through enabled keys evenly.
- **Weighted**: proportional to each key's **Weight**.
- **Random**: random key per request.

### Auto-routing models

With keys added, these ids route across all of them:

| Model id | Routes to |
|---|---|
| `anyrouter/byok` | Every model your keys can reach |
| `anyrouter/coding` | The coding-capable subset |
| `anyrouter/agent` | The tool-calling subset |

```bash
curl https://anyrouter.dev/api/v1/chat/completions \
  -H "Authorization: Bearer $ANYROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "model": "anyrouter/coding", "messages": [{ "role": "user", "content": "Refactor this function" }] }'
```

The strongest available model goes first, with fallback. New providers join automatically. Candidates respect your privacy and Zero Data Retention settings; preview them under **Dashboard → BYOK → Auto-routing models**. They never spend credits; with no matching keys they return an error asking you to add one.

## Failures and key health

| Failure | What happens |
|---|---|
| Invalid or revoked key | The provider's `401`/`403` is returned; the key is marked **Unhealthy** after repeated auth failures. |
| Rate limit (`429`) or 5xx | The provider error and `Retry-After` are returned. With several keys and **Fallback**, the next key is tried first. |
| Quota exhausted | Treated as a 4xx, not retried on the same key; round-robin and weighted move on. |
| Key removed mid-request | In-flight requests finish; new requests follow the precedence above. |

Health (healthy, warning, unhealthy) comes from the last 24 hours. Unhealthy keys are skipped by load balancing until healthy; re-test from the dialog.

## Security

Keys are encrypted at rest with a per-row salt, write-only in the UI and API (only the alias and a masked id show), and stripped from logs. If a key is compromised, rotate it at the provider and delete it here. Use a separate provider key per AnyRouter account.

## Shared pool

The shared pool routes requests through **donated** keys. It is open to **donors** (flip **Donate to pool** on an eligible key: you get Go plus $0 Pool requests while the key stays valid) and to **Go ($2/mo)**, **Pro ($10/mo)**, **Pro+ ($45/mo)** and **Max ($100/mo)** subscribers. Free-plan users need a donated key or Go. Donation is per key and withdrawable instantly; your account keeps first call on its own key. See [/pool](https://anyrouter.dev/pool) and [Share a Key to the Shared Pool](/features/shared-pool).

## Costs

AnyRouter charges nothing for BYOK traffic. You pay the provider on their billing cycle (plus any fee from an external gateway you put in front). **Dashboard → Usage** reports credit and BYOK usage separately.

## From the CLI

```bash
anyr byok providers                              # providers that accept BYOK
anyr byok test openai                            # one real call with your saved key
echo $KEY | anyr byok test openai --key-stdin    # check a key before saving it
anyr byok rm openai --yes                        # delete the saved key
```

`byok` needs a management key (`ANYROUTER_MANAGEMENT_KEY`) with BYOK read and write permissions. `test` exits 1 when the provider rejects the key. Your key never appears in output.

## FAQ

- **Send a key inline per request?** No. Only saved keys are accepted, so they can be validated, encrypted and health-checked.
- **Streaming and tools?** Work the same as with managed capacity.
- **Which key served a request?** **Dashboard → Logs** shows the provider and key alias (or `managed`).


## Related

- [Pricing & Plans](/docs/features/pricing.md)
- [Free Tier](/docs/features/free-tier.md)
- [Smart Routing](/docs/features/routing.md)
- [How AnyRouter Chooses a Credential](/docs/features/credential-selection.md)
- [BYOK Provider Setup Guide](/docs/features/byok-providers.md)
- [Get a provider API key](/docs/guides/byok-provider-keys.md)
- [Share a Key to the Shared Pool](/docs/features/shared-pool.md)
