Home Models & Providers Cloud Providers OpenClaw + OpenRouter
Models & Providers Cloud Providers OpenRouter

OpenClaw + OpenRouter: One Key to Rule Every AI Model

Managing four separate API keys, four billing accounts, and four rate limit ceilings is exactly the kind of overhead that kills agent projects before they ship. OpenRouter collapses all of it into a single key and a single invoice — with 100+ models available on demand.

SR
S. Rivera
AI Infrastructure Lead
Feb 5, 2025 16 min read 11.2k views
Updated Feb 2025
Key Takeaways
One OPENROUTER_API_KEY replaces separate Anthropic, Google, xAI, and OpenAI keys — one billing account, one rate limit to manage
OpenRouter uses OpenAI-compatible endpoints, so the base_url override in openclaw.yaml is all that's needed to switch from direct APIs
Model strings follow provider/model-name format — e.g., anthropic/claude-sonnet-4-5, google/gemini-2.0-flash
Fallback model config is the most underused feature — one line prevents a single-provider outage from killing your entire agent pipeline
OpenRouter adds a small price margin (~5–10%) over direct API pricing; the operational simplicity almost always justifies it for teams managing multiple models

Teams running multi-model OpenClaw agents without OpenRouter are maintaining a configuration nightmare. Separate API keys that rotate on different schedules. Separate billing accounts with separate spend limits. Different rate limit structures per provider. Different error code formats to handle in retry logic.

OpenRouter eliminates all of it. One key, one endpoint, one bill, one error format. And when one provider has an outage — which they all do, eventually — your fallback model kicks in automatically without any code change.

Here's the complete setup guide, including the model routing decisions and fallback configurations that turn a basic integration into a production-ready multi-model agent system.

What OpenRouter Actually Does

OpenRouter sits between your OpenClaw agent and every major AI provider. Your agent sends a request to OpenRouter's endpoint with a model string like anthropic/claude-sonnet-4-5. OpenRouter authenticates with Anthropic using its own API key, forwards your request, and returns the response — all transparently from your agent's perspective.

The result: you manage one key and one account. OpenRouter handles the provider relationships, rate limit pooling across their customer base, and billing consolidation.

As of early 2025, OpenRouter supports over 100 models from Anthropic, Google, xAI, OpenAI, Meta (Llama), Mistral, Cohere, and a growing roster of open-source providers. You switch models by changing a string in your config — no new account, no new key, no new billing setup.

Getting Set Up with OpenRouter

Go to openrouter.ai and create an account. Add a payment method and purchase credits — the minimum top-up is $5, which is enough to run meaningful tests across multiple models.

Generate an API key in the Keys section. Set it in your environment:

# Add to your shell config or deployment environment
export OPENROUTER_API_KEY="sk-or-v1-..."

# Confirm it's available
echo $OPENROUTER_API_KEY
Create Separate Keys Per Environment
OpenRouter lets you create multiple API keys per account. Create one key for development and a separate key for production. Assign different spending limits to each. This gives you isolation — a runaway dev script can't burn through your production budget — and cleaner usage analytics per environment.

The OpenClaw Config for OpenRouter

OpenRouter uses an OpenAI-compatible API format. That means the OpenClaw config only needs two changes from a standard provider setup: a different base URL and the OpenRouter model string format.

# openclaw.yaml
providers:
  openrouter:
    api_key_env: OPENROUTER_API_KEY
    base_url: https://openrouter.ai/api/v1
    default_model: anthropic/claude-sonnet-4-5
    max_tokens: 8192
    temperature: 0.3
    retry_on_rate_limit: true
    retry_delay: 2s
    retry_max_attempts: 3
    timeout: 90s
    headers:
      HTTP-Referer: https://aiagentsguides.com   # optional but recommended
      X-Title: OpenClaw Agent                     # identifies your app in OR dashboard

agent:
  primary_provider: openrouter

The HTTP-Referer and X-Title headers are optional but recommended. They appear in your OpenRouter dashboard, making it easier to identify traffic from different applications when you're running multiple OpenClaw agents under the same account.

Model String Format

Every model on OpenRouter follows the same format: provider/model-name. Get the exact string from the OpenRouter models page — copy-paste rather than guessing, because an incorrect model string returns a 404 that can look like a configuration error.

# Common model strings for OpenClaw agents
anthropic/claude-sonnet-4-5          # primary agent reasoning
anthropic/claude-haiku-3-5           # fast, cheap subtasks
google/gemini-2.0-flash              # high-volume, multimodal
google/gemini-1.5-pro                # large context documents
meta-llama/llama-3.1-8b-instruct     # open-source, very cheap
openai/gpt-4o-mini                   # reliable fallback
mistralai/mistral-7b-instruct        # fast open-source option

Fallback Model Configuration

We'll get to cost controls in a moment — but the fallback configuration is more important for production reliability, and it's the feature most teams configure last when they should configure it first.

Here's what happens without a fallback: Anthropic has a 20-minute partial outage. Your agent hits 529 errors. Every task in the queue fails. Users see errors. You get paged.

Here's what happens with a fallback: OpenClaw retries through OpenRouter with your fallback model. Tasks complete, possibly slightly slower or with marginally different output quality. Nobody gets paged.

# Fallback configuration in openclaw.yaml
providers:
  openrouter:
    default_model: anthropic/claude-sonnet-4-5
    fallback_model: openai/gpt-4o-mini          # activates on 429, 503, 529
    fallback_on_status_codes: [429, 503, 529]
    fallback_max_attempts: 2
Test Your Fallback Before You Need It
Most teams set up a fallback model and assume it works. Verify it. Temporarily force a 429 response in your test environment by sending rapid requests until the rate limit triggers, then confirm your fallback model actually activates. A misconfigured fallback_on_status_codes list means the fallback never fires when you need it most.

Cost Controls That Actually Matter

OpenRouter exposes two levels of cost control. Use both.

Dashboard-level limits. In the OpenRouter dashboard, set a daily spending cap per API key and a monthly maximum. These are hard limits — once hit, the key returns a 402 error until the next billing period. Set the daily cap at 2–3x your expected daily spend so normal usage never hits it, but a runaway agent loop can't cause a catastrophic bill.

Task-level model assignment in openclaw.yaml. This is where you actually control spend in practice. Here's what we've seen consistently across deployments: teams that assign models deliberately by task type spend 50–70% less than teams running a single premium model across all operations.

tasks:
  planning:
    model: anthropic/claude-sonnet-4-5      # worth the cost for reasoning
  document_summarization:
    model: google/gemini-2.0-flash          # fast, cheap, good enough
  quick_classification:
    model: meta-llama/llama-3.1-8b-instruct # open-source, near-zero cost
  fallback_reasoning:
    model: openai/gpt-4o-mini               # reliable, economical

Monitor the x-openrouter-cost response header during your first week. It returns the exact cost in USD for each API call. Pipe these values into your logging system and you'll spot cost anomalies — a task type generating unexpectedly large responses, a loop that's running more iterations than designed — before they become a billing problem.

Direct API vs OpenRouter: The Real Tradeoff

OpenRouter adds roughly 5–10% to provider pricing. That's the only meaningful downside. Here's the full comparison:

Factor Direct APIs Via OpenRouter
API keys to manage 1 per provider (4+) 1 total
Billing accounts 1 per provider 1 total
Fallback on outage Manual config per provider One fallback_model line
Add a new model New account + key + config Change one model string
Price vs direct Baseline +5–10% markup

For teams running a single model at very high volume, direct API access can justify the added management overhead through cost savings. For every other use case — especially multi-model agents — OpenRouter wins on total cost including engineering time.

Best Models to Route Through OpenRouter for OpenClaw

Not every model available on OpenRouter is worth using in an agent pipeline. Based on testing across real OpenClaw deployments, here's the practical ranking by use case:

  • Primary reasoning and tool use: anthropic/claude-sonnet-4-5 — most reliable for structured agent tasks, best instruction-following
  • Large document analysis: google/gemini-1.5-pro — 1M context window, strong comprehension
  • High-volume classification: google/gemini-2.0-flash or meta-llama/llama-3.1-8b-instruct — fast and cheap
  • Reliable fallback: openai/gpt-4o-mini — consistent quality, widely available, rarely down
  • Complex planning tasks: anthropic/claude-opus-4 — expensive, but worth it for multi-step orchestration

Common Mistakes with the OpenRouter Integration

Forgetting the base_url override. Without base_url: https://openrouter.ai/api/v1, OpenClaw sends requests to the default endpoint and the key fails authentication. This is the most common setup error and produces a confusing 401.

Using incorrect model strings. The format is always provider/model-name. A string like claude-sonnet-4-5 without the provider prefix will fail. Verify every model string against the OpenRouter models catalog before adding it to your config.

Not setting spending caps. An agent with a bug that causes infinite retries or runaway loops will generate API calls until your account balance runs out. Daily and monthly caps are not optional — set them before going live.

Skipping the fallback config. The whole point of OpenRouter for reliability is automatic fallback. A setup without a configured fallback model loses that benefit and behaves identically to a direct API connection during outages.

Frequently Asked Questions

What is OpenRouter and how does it work with OpenClaw?

OpenRouter is an API aggregator that routes requests to 100+ AI models through a single OpenAI-compatible endpoint and API key. In OpenClaw, you configure one openrouter provider block and access any supported model — Claude, Gemini, Grok, Llama, Mistral — by specifying the model string. No separate API keys per provider required.

How do I set up OpenRouter in OpenClaw?

Create an account at openrouter.ai, add credits, and generate an API key. Set it as OPENROUTER_API_KEY in your environment. In openclaw.yaml, configure the openrouter provider with base_url: https://openrouter.ai/api/v1 and set your default_model using OpenRouter's model string format (e.g., anthropic/claude-sonnet-4-5).

Is OpenRouter more expensive than using provider APIs directly?

OpenRouter adds a small margin on top of provider pricing — typically 5–10% depending on the model. For most teams, the operational simplicity of one key, one invoice, and built-in fallbacks more than justifies the markup. High-volume deployments should compare total cost including engineering time to maintain multiple provider accounts.

Can I set fallback models in OpenClaw through OpenRouter?

Yes — this is one of OpenRouter's most valuable features for agent reliability. Set a fallback_model in your openclaw.yaml provider block. If the primary model returns a 429 or 503, OpenClaw automatically retries through OpenRouter with the fallback model. This eliminates single-provider outages from disrupting your agent pipeline.

What models work best with OpenClaw through OpenRouter?

For primary agent reasoning: anthropic/claude-sonnet-4-5. For cost-sensitive high-volume tasks: meta-llama/llama-3.1-8b-instruct or google/gemini-2.0-flash. For fallback during outages: openai/gpt-4o-mini. Route each task type to the model that matches its requirements — OpenRouter's unified interface makes this straightforward to configure.

How do I control costs when using OpenRouter with OpenClaw?

Set spending limits in the OpenRouter dashboard — both per-key daily limits and monthly caps. In openclaw.yaml, assign cheaper models to high-volume subtasks and reserve premium models for tasks that genuinely need them. Monitor the x-openrouter-cost header in API responses to track per-request spend and catch unexpected token usage patterns early.

SR
S. Rivera
AI Infrastructure Lead

S. Rivera designs and operates multi-provider AI agent infrastructure, including production OpenRouter deployments that route across Claude, Gemini, and open-source models. Has built the provider comparison and routing frameworks used across a dozen OpenClaw production deployments, with a consistent focus on reliability and cost efficiency.

Get the Build-Smarter Newsletter
New OpenClaw guides, model updates, and agent patterns — every two weeks.