# How do you set up OpenClaw API keys and choose a model?

Canonical: https://clawdocx.com/docs/api-key-setup
Author: Sam Okafor
Difficulty: BEGINNER
Published: 2026-02-24
Updated: 2026-09-19

> Where an OpenClaw API key goes, the provider/model refs that use it, and how fallbacks and per-agent models work, with current prices and commands.

Start with Anthropic and the model ref `anthropic/claude-sonnet-5`. Anthropic's pricing page lists Claude Sonnet 5 at $2 per million input tokens and $10 per million output tokens as of September 19, 2026, the key takes a couple of minutes to create in the Claude Console, and Anthropic documents `ANTHROPIC_API_KEY` as the environment variable its own tooling reads. Every other provider is the same three steps: create a key, put it somewhere OpenClaw can read that is not a config literal, and point `agents.defaults.model.primary` at a `provider/model` ref.

## Which provider should you start with?

Anthropic, unless you have a reason not to. Anthropic's models overview describes Claude Sonnet 5 as "The best combination of speed and intelligence", gives it a 1M token context window, and lists its Claude API ID as `claude-sonnet-5`. In OpenClaw that becomes the ref `anthropic/claude-sonnet-5`.

Two facts worth knowing before you budget. Anthropic's pricing page notes that the $2 and $10 rates for Claude Sonnet 5, announced at launch as introductory pricing through August 31, 2026, are now the standard price, and that the scheduled increase to $3 and $15 will not happen. It also warns that Claude 4.7 and later models use a newer tokenizer that "produces approximately 30% more tokens for the same text", so measure a real workload rather than trusting the sticker price.

If you would rather not pay anything to start, Google's Gemini API pricing page advertises a free tier in its own words: "Start building free of charge with generous limits, then scale up with prepaid then pay-as-you-go pricing". OpenClaw's provider id for it is `google`. The cheapest metered option among the three is OpenAI's `gpt-5.6-luna`, listed on OpenAI's pricing page at $0.20 input and $1.20 output per million tokens on short-context prompts as of September 19, 2026, and $0.40 and $1.80 on long context.

## How does OpenClaw talk to a provider?

Through a model ref. OpenClaw's models documentation puts it plainly: "A model ref (`provider/model`) chooses a provider and model, not the low-level agent runtime." The provider half of the ref is the provider id from OpenClaw's providers index, and the model half is the id that provider publishes.

Configuration lives in one file. The gateway configuration reference states that "OpenClaw reads an optional JSON5 config from `~/.openclaw/openclaw.json`", and that "JSON5 supports comments and trailing commas". If you keep the config elsewhere, the same page says to "point `OPENCLAW_CONFIG_PATH` directly at the real file".

The model itself is selected in a documented order: `agents.defaults.model.primary`, which the docs note may also be written as `agents.defaults.model` as a plain string, and then `agents.defaults.model.fallbacks`, "tried in order". OpenClaw's providers index gives the same two-step shape for any provider on the list: authenticate with the provider, "usually via `openclaw onboard`", then set the default model.

The providers index lists more than fifty LLM providers, including `anthropic`, `openai`, `google`, `openrouter`, `moonshot` and `ollama`. The version behind the commands and keys in this guide is v2026.9.5, the latest release listed in the OpenClaw docs as of September 19, 2026.

## Where do you get a key?

One key from one provider is enough to run an agent. The table lists only cells confirmed on the linked pages.

| Provider | Provider id in OpenClaw | Key page | Environment variable | Free tier |
|---|---|---|---|---|
| Anthropic | `anthropic` | Claude Console, Settings then API keys, at `platform.claude.com/settings/keys` | `ANTHROPIC_API_KEY` | No free tier, but Anthropic's pricing FAQ says new users receive a small amount of free credits to test the API. |
| OpenAI | `openai` | The API keys page in the OpenAI dashboard, at `platform.openai.com/settings/organization/api-keys` | `OPENAI_API_KEY` | Not verified |
| Google | `google` | Google AI Studio, at `aistudio.google.com/apikey` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Yes. Google's Gemini API pricing page advertises free input and output tokens with limited access to certain models. |

**Anthropic.** The Claude docs say keys live in the Claude Console and that you "Click **Create key**, name the key, choose an expiration, and set **Linked account** to yourself or a service account." They also warn that "The Console shows the full key, which starts with `sk-ant-`, only once, at creation." The client SDKs read `ANTHROPIC_API_KEY` automatically. OpenClaw's Anthropic provider page documents the non-interactive path as `openclaw onboard --anthropic-api-key "$ANTHROPIC_API_KEY"` (that form expands a variable; do not paste the key itself onto the command line), and `openclaw models list --provider anthropic` to confirm availability. Where onboard stores the key is outside this guide's scope.

**OpenAI.** OpenAI's quickstart says to "create an API key in the dashboard, which you'll use to securely access the API", recommends `OPENAI_API_KEY` as the variable name, and shows `export OPENAI_API_KEY="your_api_key_here"` for macOS and Linux. OpenClaw's OpenAI setup page documents `openclaw onboard --auth-choice openai-api-key` and `openclaw onboard --openai-api-key "$OPENAI_API_KEY"`.

**Google.** Google's API key page points at `https://aistudio.google.com/apikey` and instructs you to "Set the environment variable GEMINI_API_KEY or GOOGLE_API_KEY", with `export GEMINI_API_KEY=<YOUR_API_KEY_HERE>` as the shell example. The same page adds that "If both are set, `GOOGLE_API_KEY` takes precedence." OpenClaw's Google provider page documents `openclaw onboard --auth-choice gemini-api-key`.

## Where does the key go?

Not into `models.providers.<id>.apiKey` as a bare string. OpenClaw's secrets and storage page places provider credentials in one of four documented spots: the Gateway process environment, `~/.openclaw/.env` (`$OPENCLAW_STATE_DIR/.env`), the config `env` block (which does live inside `openclaw.json`, so it still needs the `600` permission below), or an optional login-shell import. The same page notes that "Provider credential environment variables are blocked from untrusted workspace `.env` files", so a key dropped into a project directory will not be picked up.

For anything beyond a single machine, OpenClaw documents SecretRefs. Its secrets management page states that "OpenClaw supports additive SecretRefs so supported credentials do not need to live as plaintext in configuration", and names four sources: env, file, exec and store. The SecretRef credential surface lists `models.providers.*.apiKey` among the fields that accept one, and the secrets management page warns why it matters: "Plaintext credentials remain agent-readable when they sit in files the agent can inspect, including `openclaw.json`, `.env`, retired auth-profile JSON archives, or generated `agents/*/agent/models.json` files."

Putting a key into the shared store is one documented command:

```bash
openclaw secrets store set OPENAI_API_KEY --allow-host api.openai.com
```

The value never goes on the command line. OpenClaw's secrets CLI takes it from piped stdin, from `--value-file <path>` (or `-` for stdin), or from an interactive no-echo prompt, and warns that "command-line arguments can leak through shell history and process listings". For a secret entry, `--value` is not merely discouraged: the docs say it "is refused with exit code `2`". The flag is reserved for non-secret `env` entries such as `LOG_LEVEL`.

The config then names the entry instead of the secret. The `models.providers` block below is verbatim from OpenClaw's shared secret store page; the `agents.defaults.model` block is the shape its models documentation describes. Here the primary runs on Anthropic with `ANTHROPIC_API_KEY` in the Gateway environment, and the OpenAI fallback reads its key from the store.

```json5
// ~/.openclaw/openclaw.json
{
  models: {
    providers: {
      openai: {
        apiKey: { source: "store", provider: "default", id: "OPENAI_API_KEY" },
      },
    },
  },
  agents: {
    defaults: {
      model: {
        primary: "anthropic/claude-sonnet-5",
        fallbacks: ["openai/gpt-5.6-luna"],
      },
    },
  },
}
```

> **Warning**
>
> OpenClaw's secrets and storage page asks for restrictive permissions on the state directory: "`~/.openclaw/openclaw.json`: `600` (user read/write only)" and "`~/.openclaw`: `700` (user only)". It also notes that everything under `~/.openclaw/` may contain secrets, including the SQLite state file and per-agent auth profiles.

## How do you check that the key works?

Three documented commands, in increasing depth. None of them spends a token at the provider; for that, use the smoke test below.

```bash
openclaw models list --provider anthropic
openclaw models status
openclaw doctor
```

`openclaw models list --provider anthropic` is the command OpenClaw's Anthropic page gives for confirming the provider's models are available. `openclaw models status` is the shortcut you get from a bare `openclaw models`, and the docs say it surfaces "OAuth expiry for auth-store profiles (warns within 24h by default)". `openclaw doctor` is the broad one: its CLI page describes it as covering "the gateway, channels, plugins, skills, model routing, local state, and config migrations" and says to "Use it whenever something is not behaving as expected and you want one command to explain what is wrong." The doctor checks page names a **Model auth health** check that "checks OAuth expiry, can refresh expiring tokens, and reports auth-profile cooldown/disabled states".

For an end-to-end probe, OpenClaw's inference CLI documents a one-line smoke test:

```bash
openclaw infer model run --prompt "Reply with exactly: smoke-ok" --json
```

`model run` also takes `--model provider/model` to pin a specific ref, and `--local` to smoke-test a provider without going through the Gateway. The docs note that a `--prompt` must contain non-whitespace text, and that a local run exits non-zero when the provider returns no text output, so an unreachable provider does not look like a success.

## How do fallbacks and per-agent models work?

`agents.defaults.model.fallbacks` is an ordered list that OpenClaw tries when the primary is unavailable. Inside a provider it first tries other credentials: the docs state that "Auth-profile rotation happens inside a provider before OpenClaw moves to the next fallback model." The behaviour depends on where the selection came from. A configured default uses the fallbacks list; a user's own session selection is documented as "Exact and strict", and the same page says that if that provider/model becomes unreachable "the run fails visibly instead of falling through to another configured model"; and a cron or payload selection uses the configured fallbacks unless `fallbacks: []` forces strict mode.

Per-agent overrides replace the default for one agent. The docs describe `agents.entries.*.model` as replacing `agents.defaults.model`, so it takes the same `model` block and a summarizing agent can sit on a cheap model while your main agent stays on Sonnet. `agents.defaults.modelPolicy.allow` gates which refs are selectable at all: it accepts exact refs or trailing wildcards such as `provider/*`, and an empty or omitted list allows any model. A blocked selection returns the documented error `Model override "provider/model" is not allowed by agents.defaults.modelPolicy.allow.`

```json5
{
  agents: {
    defaults: {
      model: {
        primary: "anthropic/claude-sonnet-5",
        fallbacks: ["anthropic/claude-haiku-4-5", "openai/gpt-5.6-luna"],
      },
      modelPolicy: { allow: ["anthropic/*", "openai/gpt-5.6-luna"] },
    },
    entries: {
      inbox: { model: { primary: "anthropic/claude-haiku-4-5" } },
    },
  },
}
```

The same settings are reachable from the CLI, which the models page documents as `openclaw models set <provider/model>`, `openclaw models fallbacks list|add|remove|clear` and `openclaw models auth list|add|login|paste-api-key|paste-token|setup-token|order`.

> **Note**
>
> OpenClaw has no task-type routing keys. Its documented model configuration contains no key that sends heartbeats, code generation, summarization or quick replies to a different model, and the fallback list is failover rather than a routing table. Use `agents.entries.<id>.model` to give a cheaper model to an agent that only does cheap work.

## How do you keep keys safe?

Set an expiry and rotate on a schedule, and keep the secret out of anything you commit. The three providers each document their own mechanism.

Anthropic's authentication page is direct about it: "Store API keys in a secrets manager, rotate them periodically, and disable or delete any key you suspect has leaked." On the Console's API keys page, **Disable** is reversible and **Delete** is permanent. Anthropic also lets you choose an expiration when the key is created, from presets of 3 hours, 1 day, 7 days or 30 days, a custom duration, or **Never** for keys you store in a secrets manager and rotate yourself. The page adds that expiration "is not a substitute for secret hygiene".

OpenAI's production best practices say to "Avoid exposing the API keys in your code or in public repositories; instead, store them in a secure location", and give a rotation order: "We strongly recommend setting an expiration date when you create a project API key and establishing a regular key rotation process. Before a key expires, create a replacement, update your applications to use it, and revoke the old key once you've verified that the replacement works."

Google's API key page is blunt on the two failure modes: "Never check API keys into source control systems like Git" and "Do not hardcode API keys directly in web or mobile apps." For a compromised key it says to "Disable or delete the compromised key".

On the OpenClaw side, the guidance is to stop keeping credentials as config literals at all. Moving a provider key to a SecretRef is how you get there: "SecretRefs reduce that local blast radius once every supported credential is migrated and `openclaw secrets audit --check` reports no plaintext residue." Redaction comes free alongside it: "Log/transcript redaction is always on and cannot be disabled by config". The audit named in that first sentence is a command you run yourself:

```bash
openclaw secrets audit --check
```

As general practice rather than vendor instruction, rotate on a fixed calendar rather than when you remember, give each machine its own key so one revocation does not take everything down, and treat any key that has ever been pasted into a chat, a ticket or a screenshot as leaked.

## Which model should be the default?

`anthropic/claude-sonnet-5`, at $2 and $10 per million input and output tokens on Anthropic's pricing page as of September 19, 2026. Step up to `anthropic/claude-opus-5` at $5 and $25 when a wrong step in a long tool-use chain is expensive; Anthropic's models overview positions it "For complex agentic coding and enterprise work". Drop background agents to `anthropic/claude-haiku-4-5` at $1 and $5, which the same page calls "The fastest model with near-frontier intelligence"; `claude-haiku-4-5` is the Claude API alias, and the pinned id behind it is `claude-haiku-4-5-20251001`.

That is the short answer. [The best LLM models for OpenClaw](/blog/best-llm-models-openclaw) compares ten models across providers with current prices and context windows, and [cost optimization](/docs/cost-optimization) covers what to do once the bill starts arriving.

## What to read next

- [The best LLM models for OpenClaw](/blog/best-llm-models-openclaw) has the full price and context comparison behind the default pick above.
- [Cost optimization](/docs/cost-optimization) turns a working key into a predictable monthly bill.
- [Security hardening](/docs/security-hardening) covers the rest of the agent's attack surface, once the keys are out of your config.

Prices and model ids in this guide are dated September 19, 2026. Check the provider pricing pages in the sources below before you commit to a budget.

## Frequently asked questions

**Which provider should I start with for OpenClaw?**

Anthropic, on the model ref anthropic/claude-sonnet-5. Anthropic's pricing page lists Claude Sonnet 5 at $2 per million input tokens and $10 per million output tokens as of September 19, 2026, and its models overview gives it a 1M token context window. If you want to spend nothing first, Google's Gemini API pricing page advertises a free tier, and OpenClaw's provider id for it is google.

**Where does an OpenClaw API key actually go?**

Not into models.providers.<id>.apiKey as a bare string. OpenClaw's security docs say provider credentials belong in the Gateway process environment, in ~/.openclaw/.env, in the config env block (which does live inside openclaw.json, so it still needs the 600 permission), or in an optional login-shell import. For the config file itself, models.providers.<id>.apiKey accepts a SecretRef object that points at an env, file, exec or store entry instead of holding the secret.

**How do OpenClaw model fallbacks work?**

agents.defaults.model.fallbacks is an ordered list of provider/model refs that OpenClaw tries when the primary is unavailable. The docs state that auth-profile rotation happens inside a provider before OpenClaw moves to the next fallback model. It is failover, not routing by task type, and OpenClaw's documented model config has no task-type routing keys at all.

**Can OpenClaw use more than one provider at once?**

Yes. Each provider gets its own entry under models.providers, and any model ref you use names its provider, so a primary on anthropic and a fallback on openai coexist in one config. Per-agent overrides under agents.entries.<id>.model let a second agent run on a different provider entirely.

**What should I do if an API key leaks?**

Revoke it at the provider. Anthropic's authentication docs say to disable or delete any key you suspect has leaked, where Disable is reversible and Delete is permanent. OpenAI's production guidance is to create a replacement, update your applications to use it, and revoke the old key once the replacement works, and Google's API key docs say to disable or delete the compromised key.

## Sources

- [OpenClaw: Models CLI](https://docs.openclaw.ai/concepts/models)
- [OpenClaw: Configuration](https://docs.openclaw.ai/gateway/configuration)
- [OpenClaw: Environment variables](https://docs.openclaw.ai/gateway/configuration/environment-variables)
- [OpenClaw: Provider directory](https://docs.openclaw.ai/providers)
- [OpenClaw: Anthropic](https://docs.openclaw.ai/providers/anthropic)
- [OpenClaw: OpenAI](https://docs.openclaw.ai/providers/openai)
- [OpenClaw: OpenAI setup](https://docs.openclaw.ai/providers/openai/setup)
- [OpenClaw: Google (Gemini)](https://docs.openclaw.ai/providers/google)
- [OpenClaw: Secrets management](https://docs.openclaw.ai/gateway/secrets)
- [OpenClaw: Shared secret store and egress proxy](https://docs.openclaw.ai/gateway/secrets/secret-store-and-egress)
- [OpenClaw: SecretRef credential surface](https://docs.openclaw.ai/reference/secretref-credential-surface)
- [OpenClaw: Secrets, storage, and logs](https://docs.openclaw.ai/gateway/security/secrets-and-storage)
- [OpenClaw: Secrets CLI](https://docs.openclaw.ai/cli/secrets)
- [OpenClaw: Inference CLI](https://docs.openclaw.ai/cli/infer)
- [OpenClaw: Doctor CLI](https://docs.openclaw.ai/cli/doctor)
- [OpenClaw: What doctor checks](https://docs.openclaw.ai/gateway/doctor/checks)
- [OpenClaw: v2026.9.5](https://docs.openclaw.ai/releases/2026.9.5)
- [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key)
- [Claude API authentication](https://platform.claude.com/docs/en/manage-claude/authentication)
- [Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing)
- [Claude models overview](https://platform.claude.com/docs/en/about-claude/models/overview)
- [OpenAI developer quickstart](https://developers.openai.com/api/docs/quickstart)
- [OpenAI: production best practices](https://developers.openai.com/api/docs/guides/production-best-practices)
- [OpenAI API pricing](https://developers.openai.com/api/docs/pricing)
- [Gemini API: using API keys](https://ai.google.dev/gemini-api/docs/api-key)
- [Gemini API pricing](https://ai.google.dev/gemini-api/docs/pricing)