Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Fix OpenCode Model Auth & Rate Limit Errors on OpenRouter

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

If you use OpenCode with OpenRouter as your model provider, you've likely hit authentication failures or rate limit errors mid-session. These usually stem from a missing or expired API key, incorrect environment variable names, or hitting your OpenRouter tier's request cap. This guide walks you through diagnosing and fixing both error types, from verifying your key to configuring retry logic.

What You'll Need

  • Your OpenRouter API key (from openrouter.ai/keys)
  • Access to your terminal or command line
  • Your OpenCode configuration file location (typically ~/.config/opencode/ on Linux/macOS, or %USERPROFILE%\.config\opencode\ on Windows)
  • Optional: a text editor to modify config files

Step-by-Step

  1. Confirm your OpenRouter API key is valid
    Visit openrouter.ai/keys and check that your key exists and hasn't been revoked. If you see no keys, create a new one. Copy the key exactly – it starts with sk-or-.
  2. Set the environment variable correctly
    OpenCode reads the OPENROUTER_API_KEY environment variable. In your terminal, run:
    echo $OPENROUTER_API_KEY
    (On Windows Command Prompt: echo %OPENROUTER_API_KEY%)
    If it's empty or wrong, set it permanently. On Linux/macOS, add this to your ~/.bashrc or ~/.zshrc:
    export OPENROUTER_API_KEY="your_key_here"
    Then run source ~/.bashrc (or restart your terminal). On Windows, use setx OPENROUTER_API_KEY "your_key_here" and restart your terminal.
  3. Verify OpenCode picks up the key
    Run opencode auth list (or opencode auth status in newer versions) to see which providers are configured. You should see OpenRouter listed as authenticated. If not, run opencode auth login and choose OpenRouter, then paste your key when prompted.
  4. Check your OpenCode config for hardcoded keys
    Open ~/.config/opencode/config.json (or opencode.json in your project). Look for a provider section with an apiKey field. If it's there, update it to your current key. Also ensure the model name is correct – for example, openrouter/anthropic/claude-3.5-sonnet (the format is provider/model).
  5. Test a simple request directly
    Run a minimal OpenCode command:
    opencode run "Say hello" --model openrouter/anthropic/claude-3.5-sonnet
    If this works, your auth is fine. If you get a 401 error, your key is still wrong or missing.
  6. Handle rate limit errors (429)
    OpenRouter rate limits depend on your account tier (free vs paid). If you hit a 429, you have three options:
    • Wait and retry – the error message usually includes a Retry-After header in seconds.
    • Switch to a less busy model – some models have separate rate limits.
    • Upgrade your OpenRouter plan for higher limits.
    In OpenCode, you can also configure automatic retries. In your config.json, add:
    {
      "provider": {
        "openrouter": {
          "maxRetries": 3,
          "retryDelay": 5000
        }
      }
    }
    This tells OpenCode to retry up to 3 times with a 5-second delay between attempts.
  7. Restart OpenCode completely
    After any config or environment change, close all OpenCode sessions and start a new terminal window. Environment variables set with export only apply to the current shell.
  8. Clear any cached credentials
    If you previously used a different provider or key, OpenCode may cache old auth. Delete the auth cache file (often ~/.local/share/opencode/auth.json on Linux, ~/Library/Application Support/opencode/auth.json on macOS) and re-run opencode auth login.

Common Mistakes

  • Using the wrong environment variable name – Some tools use OPENROUTER_API_KEY, others use OPENROUTER_KEY. OpenCode specifically expects OPENROUTER_API_KEY.
  • Copying the key with extra spaces or newline – When pasting into a terminal, a trailing newline can break the key. Use echo -n to test.
  • Hardcoding a key in a shared config file – If you commit config.json to a repo, your key leaks. Use environment variables instead.
  • Ignoring the model name prefix – OpenCode requires openrouter/ before the model name. Omitting it causes a "model not found" error that looks like an auth issue.
  • Assuming rate limits are per-model – OpenRouter's free tier has a global limit (e.g., 50 requests/day). Check your usage on the OpenRouter dashboard.

Tips

  • Use a dedicated key for OpenCode, not one shared with other apps – this makes it easier to revoke if needed.
  • Set a generous maxRetries (3-5) and a delay of at least 2000ms to avoid hammering the API during transient rate limits.
  • Monitor your OpenRouter usage page to see real-time request counts and which models are consuming your quota.
  • If you're on a free tier, consider using a cheaper or faster model (like openrouter/meta-llama/llama-3.1-8b-instruct) for routine tasks to stay under limits.
  • Keep your OpenCode version updated – auth handling and retry logic improve frequently.

Troubleshooting

Still getting 401 after following steps?

  • Run opencode auth list and confirm the key is shown. If it shows a different key, use opencode auth logout then re-login.
  • Check if your key has expired – OpenRouter keys don't expire by default, but you may have regenerated it.
  • Try using the key directly in a curl command:
    curl https://openrouter.ai/api/v1/auth/key -H "Authorization: Bearer $OPENROUTER_API_KEY"
    If this returns an error, your key is invalid.

Rate limit persists even after waiting?

  • Check your OpenRouter dashboard for the exact limit and your current usage. Free tier limits reset daily (UTC).
  • If you're using a proxy or VPN, OpenRouter may see shared IPs and apply stricter limits. Try disabling it.
  • Some models have separate limits – switch to a less popular model temporarily.

OpenCode says "provider not found"

  • Ensure you're using the exact provider string: openrouter (all lowercase).
  • Check your OpenCode version – older versions may not support OpenRouter natively. Update via your package manager.

Frequently Asked Questions

Q: Does OpenCode support OpenRouter out of the box?
A: Yes, OpenCode has built-in support. You just need to set the API key and use the openrouter/ prefix in model names.

Q: Why do I get a 401 even with a valid key?
A: Usually because the environment variable isn't set in the same shell, or the key has a typo. Double-check with echo and re-login.

Q: How do I increase my rate limit on OpenRouter?
A: Rate limits are tied to your OpenRouter account tier. You can add credits or subscribe to a paid plan to raise limits. Free tier limits are shown on your dashboard.

Q: Can I use multiple providers with OpenCode?
A: Yes, OpenCode supports multiple providers simultaneously. You can set API keys for each and specify the provider per model.

Q: What does the error "model_not_found" mean?
A: It means the model name you specified doesn't exist on OpenRouter. Check the model list at openrouter.ai/models and use the exact slug.

Q: Is there a way to test my OpenRouter key without OpenCode?
A: Yes, you can use curl to hit the API directly. A simple request to /api/v1/models with your key as a Bearer token should return a list of models.