AI & Agents

How to Set Up API Keys in OpenClaw

OpenClaw resolves API keys through a four-level environment variable priority chain, checking session overrides first and falling back through multi-key lists, standard keys, and numbered variants. Rate-limit errors trigger automatic rotation to the next available key without any retry logic in your agent code. The setup covers Anthropic, OpenAI, Google, xAI, and local models through Ollama.

Fastio Editorial Team 11 min read
AI model provider integration and key configuration

How OpenClaw Resolves API Keys Through Four Priority Levels

Most AI frameworks resolve provider credentials from a single environment variable. OpenClaw checks four distinct levels per provider, from session overrides through multi-key rotation lists to numbered key variants, before the gateway makes its first API call. This four-level priority chain, documented in OpenClaw's authentication reference, is what allows a single installation to balance load across billing accounts and recover from rate limits without any retry logic in your agent code.

The resolution order, from highest to lowest priority:

  1. A session-level override variable following the OPENCLAW_LIVE_<PROVIDER>_KEY pattern sets a temporary key for the current process only. Use this when testing a new key without changing your permanent configuration. The key does not persist after the session ends.
  2. <PROVIDER>_API_KEYS accepts a comma or semicolon-delimited list of keys. OpenClaw rotates through these automatically on rate-limit errors, making this the primary mechanism for high-throughput workloads.
  3. <PROVIDER>_API_KEY holds your standard single key. This is what most developers set first and what the openclaw onboard wizard configures by default.
  4. <PROVIDER>_API_KEY_* matches numbered variants like ANTHROPIC_API_KEY_1 and ANTHROPIC_API_KEY_2. This pattern works well when managing keys from separate billing accounts or organizational units.

OpenClaw deduplicates the collected key list before making any requests. If the same key string appears at multiple priority levels, it resolves to a single entry so the gateway does not waste retries on the same credential.

For Google providers, GOOGLE_API_KEY acts as an additional fallback after the standard provider-specific chain. If you already have GOOGLE_API_KEY set for other Google services, it works with OpenClaw's Gemini integration without additional configuration.

Priority hierarchy for OpenClaw API key resolution

Key Priority vs. Environment Loading

The API key priority chain is separate from OpenClaw's environment variable loading order. The loading order controls where variable values come from: process environment, local .env file, global ~/.openclaw/.env, the config env block in openclaw.json, and optional shell import. Later sources fill gaps but never override values already set by a higher-priority source. The key priority chain then determines which variable name to check first for a given provider. Both systems work together: the loading order resolves a variable's value, and the key priority chain decides which resolved variable to use first.

Where to Get API Keys for Each Provider

Each model provider issues API keys through its own dashboard. Here is where to get keys for the providers OpenClaw supports.

Anthropic (Claude)

Create an account at console.anthropic.com and add a payment method. Navigate to the API Keys section and generate a new key. New Anthropic accounts receive $5 in complimentary credits, enough for initial testing and development. Set the variable as ANTHROPIC_API_KEY. Claude Sonnet 4 is the recommended default model for balanced cost and quality.

OpenAI (GPT)

Visit platform.openai.com, create an account, and generate an API key from the API section of the dashboard. Add pay-as-you-go billing before making API calls, as OpenAI requires an active payment method. Set the variable as OPENAI_API_KEY. GPT-4o handles most tasks well, while GPT-4o-mini suits high-volume, cost-sensitive workloads.

Google (Gemini)

Sign in at aistudio.google.com with your Google account and retrieve an API key. Google's free tier provides generous request limits for development. Set the variable as GEMINI_API_KEY or GOOGLE_API_KEY. Gemini 3 Pro supports a million-token context window, which is particularly useful for document analysis and long-form content tasks.

xAI (Grok)

Go to console.x.ai, create an account, and generate an API key. New accounts receive complimentary starting credits. Set the variable as XAI_API_KEY. Grok 4.1 Fast offers competitive pricing at approximately $0.20 per million input tokens and $0.50 per million output tokens.

Haimaker

Register at app.haimaker.ai and generate an API key from your dashboard. Haimaker provides a unified interface for accessing Llama, Qwen, and MiniMax models through a single API key. Set the variable as HAIMAKER_API_KEY.

Ollama (Local Models)

Ollama runs models entirely on your hardware and requires no API key. Install it, pull a model, and point OpenClaw at your local endpoint. No costs, no rate limits, no key management overhead. This is a strong option for development, privacy-sensitive work, or air-gapped environments where external API calls are not allowed.

How to Configure Environment Variables for OpenClaw

With your provider keys ready, the next step is getting them into OpenClaw's environment. The fast path is the onboard wizard:

openclaw onboard

This interactive tool walks you through provider selection, key entry, and default model configuration. It stores your credentials in ~/.openclaw/.env and sets sensible defaults for common models.

For manual configuration, export variables directly in your shell profile (.bashrc, .zshrc, or equivalent):

export ANTHROPIC_API_KEY="sk-ant-..."
export OPENAI_API_KEY="sk-..."
export GEMINI_API_KEY="AIza..."

These variables take effect in new terminal sessions. Restart your shell or run source ~/.zshrc to apply them immediately.

Daemon installations through systemd, launchd, or Docker do not inherit shell profile variables. For these environments, store credentials in ~/.openclaw/.env. OpenClaw reads this file on startup regardless of how the process was launched. If you have customized your state directory with OPENCLAW_STATE_DIR, the file lives at $OPENCLAW_STATE_DIR/.env instead.

You can also enter tokens interactively:

openclaw models auth paste-token --provider anthropic

This writes the key to auth-profiles.json with a versioned profile structure, keeping credentials separate from your main openclaw.json configuration file. The profile system lets you maintain multiple key versions for the same provider, which is helpful during planned key rotation.

The config file at ~/.openclaw/openclaw.json can also hold keys in its env block, but this is the lowest-priority method. Keys defined here only apply when no higher-priority source provides a value for the same variable. After editing openclaw.json, run openclaw gateway config.apply to reload the configuration without restarting the daemon.

Fastio features

Store your OpenClaw agent output in one shared workspace

Free 50GB workspace with semantic search, no credit card required. Your agents get MCP access for persistent reads, writes, and file queries across sessions.

Multi-Key Lists and Rate-Limit Rotation

Running multiple agents in parallel can exhaust a single key's rate limits within minutes. OpenClaw's multi-key rotation handles this by distributing requests across your available credentials.

Configure a rotation list by setting <PROVIDER>_API_KEYS with comma or semicolon-separated keys:

export ANTHROPIC_API_KEYS="sk-ant-key1,sk-ant-key2,sk-ant-key3"

When a request returns a rate-limit error, including HTTP 429 responses, quota exhaustion, throttling, and concurrency limits, OpenClaw retries the same request with the next key in the list. This happens transparently at the gateway level. Your agent code does not need retry logic or rate-limit handling for these scenarios.

Rotation triggers only on rate-limit errors. Authentication failures, invalid requests, and other non-rate-limit errors are returned immediately without trying alternate keys. This behavior is intentional: if a key is misconfigured or revoked, you want to know immediately rather than having the error masked by a silent retry on a different credential.

When all keys in the rotation list are exhausted, OpenClaw returns the error from the last key it attempted. At that point, you can wait for provider quotas to reset (typically within a minute for most providers), add keys from separate billing accounts, or reduce agent concurrency to stay within limits.

For teams managing shared infrastructure, numbered key variants offer a cleaner pattern:

export ANTHROPIC_API_KEY_1="sk-ant-team-alpha"
export ANTHROPIC_API_KEY_2="sk-ant-team-beta"
export ANTHROPIC_API_KEY_3="sk-ant-personal"

Each key can belong to a different team member or billing account. OpenClaw collects all matching *_KEY_* variants and adds them to the rotation pool after deduplication. This approach scales better than maintaining a single comma-separated string as your key count grows.

Best Practices for API Key Security

API keys are bearer credentials. Anyone with your key can make calls billed to your account.

Keep keys out of version control. Add openclaw.json, .env, and auth-profiles.json to your .gitignore. The config file's env block accepts literal strings only and does not expand file references. For file-backed secrets or integration with secret managers, use the SecretRef system:

{
  "apiKey": {
    "$secretRef": {
      "provider": "env",
      "key": "ANTHROPIC_API_KEY"
    }
  }
}

SecretRef supports environment variables, file reads, and command execution as secret sources. This lets you works alongside tools like HashiCorp Vault, AWS Secrets Manager, or 1Password CLI without exposing credentials in plain text configuration files.

Set spending limits at each provider's dashboard before running production workloads. Anthropic, OpenAI, and Google all support monthly spend caps. A runaway agent loop can burn through credits faster than you might expect.

Use separate keys for different environments. Generate distinct keys for development, staging, and production. If a development key leaks through a log or error message, your production workload continues unaffected. The session-level override (OPENCLAW_LIVE_<PROVIDER>_KEY) is especially useful during debugging: you can point a single session at a test key without changing your permanent environment.

Rotate keys on a regular schedule and immediately when you suspect a compromise. Regenerate the key from the provider's console, update your environment variables or .env file, and verify with openclaw models status. The old key stops working as soon as you regenerate it at the provider level.

For teams storing agent output, Fastio workspaces add audit trails that track file access and changes. This complements key-level security with workspace-level visibility into what your agents actually produce.

Audit trail and credential security monitoring

How to Verify Your Key Configuration

After configuring your keys, confirm that OpenClaw can connect to each provider:

openclaw models status

This command tests connectivity for every configured provider and reports which models are accessible. A successful response means your keys are valid, properly loaded, and authorized for the models you plan to use.

If a provider shows as unavailable, check these common issues:

  • Key not detected. Confirm the variable name matches OpenClaw's expected pattern exactly. ANTHROPIC_API_KEY works. ANTHROPIC_KEY or CLAUDE_API_KEY does not.

  • Daemon cannot see shell variables. If you set keys in your shell profile but run OpenClaw as a daemon, the daemon process does not inherit those variables. Move keys to ~/.openclaw/.env and restart the service.

  • Config not reloaded. After editing openclaw.json, run openclaw gateway config.apply to apply changes without a full restart.

  • Legacy variable names ignored. OpenClaw does not read older CLAWDBOT_* or MOLTBOT_* prefixes. Migrate to current naming if you see deprecation warnings in the logs.

  • Key format mismatch. Each provider has a distinct key format. Anthropic keys start with sk-ant-, OpenAI keys start with sk-, and Google keys start with AIza. Pasting a key into the wrong provider's variable produces immediate authentication errors.

  • Ubuntu path differences. Some Ubuntu installations fall back to ~/.config/openclaw/gateway.env for compatibility. Check both paths if your keys are not loading.

Once your keys work and openclaw models status shows green across providers, your agents can call any configured model. The Business Trial on Fastio gives each agent 50GB of persistent storage and included credits for storing outputs, sharing results with humans, and querying documents through built-in semantic search.

Frequently Asked Questions

How do I add an API key to OpenClaw?

Run `openclaw onboard` for interactive setup, or export the key as an environment variable like `export ANTHROPIC_API_KEY="sk-ant-..."` in your shell profile. For daemon installations, store the key in `~/.openclaw/.env` and restart the service.

Where do I put my OpenAI API key in OpenClaw?

Set the environment variable `OPENAI_API_KEY` in your shell profile or in `~/.openclaw/.env`. OpenClaw detects this variable automatically through its environment loading chain. You can also use `openclaw models auth paste-token --provider openai` to enter the key interactively.

Can OpenClaw use multiple API keys?

Yes. Set `<PROVIDER>_API_KEYS` with comma or semicolon-separated keys. OpenClaw deduplicates the list and rotates through keys on rate-limit errors. You can also use numbered variants like `ANTHROPIC_API_KEY_1` and `ANTHROPIC_API_KEY_2` for cleaner management across billing accounts.

How does OpenClaw handle API key rotation?

When a request returns a rate-limit error (HTTP 429, quota exhaustion, or throttling), OpenClaw retries with the next key in the rotation list. Non-rate-limit errors like authentication failures are returned immediately without rotation, so configuration problems surface right away.

What happens if all my API keys hit rate limits?

OpenClaw returns the error from the last key it tried. You will need to wait for provider quotas to reset, which typically takes under a minute, or add keys from separate billing accounts to increase your total available quota.

Do I need API keys for local models like Ollama?

No. Ollama and other local model runners operate entirely on your hardware and do not require API keys. Install Ollama, pull a model, and configure OpenClaw to use the local endpoint. This eliminates key management, rate limits, and per-token costs.

Related Resources

Fastio features

Store your OpenClaw agent output in one shared workspace

Free 50GB workspace with semantic search, no credit card required. Your agents get MCP access for persistent reads, writes, and file queries across sessions.