页面简介
Use Claude Code with OpenRouter
正文摘录
Claude Code with OpenRouter is only guaranteed to work with the Anthropic first-party provider. Because Claude Code sends standard Anthropic Messages API payloads without OpenRouter’s provider object, you have two ways to route it — see Provider Selection: Prioritize Anthropic while keeping fallbacks: Create an OpenRouter Preset with provider.order: ["anthropic"] and reference it in your Claude Code model override (for example, ANTHROPIC_DEFAULT_SONNET_MODEL="@preset/claude-code"). Restrict to Anthropic only: Use your OpenRouter privacy / provider settings to allow only Anthropic. Note that this removes non-Anthropic backups for all requests in that account or workspace scope. Why Use OpenRouter with Claude Code? OpenRouter adds a reliability and management layer between Claude Code and Anthropic’s API, giving you and your organization several key benefits. Provider Failover for High Availability Anthropic’s API occasionally experiences outages or rate limiting. When you route Claude Code through OpenRouter, your requests automatically fail over between multiple Anthropic providers. If one provider is unavailable or rate-limited, OpenRouter seamlessly routes to another, keeping your coding sessions uninterrupted. Organizational Budget Controls For teams and organizations, OpenRouter provides centralized budget management. You can set spending limits, allocate credits across team members, and prevent unexpected cost overruns. This is especially valuable when multiple developers are using Claude Code across your organization. Usage Visibility and Analytics OpenRouter gives you complete visibility into how Claude Code is being used across your team. Track usage patterns, monitor costs in real-time, and understand which projects or team members are consuming the most resources. All of this data is available in your OpenRouter Activity Dashboard. Quick Start This guide will get you running Claude Code powered by OpenRouter in just a few minutes. Step 1: Install Claude Code Native Install (Recommended) npmmacOS, Linux, WSL:curl -fsSL https://claude.ai/install.sh | bash Windows PowerShell:irm https://claude.ai/install.ps1 | iex Requires Node.js 18 or newer.npm install -g @anthropic-ai/claude-code Step 2: Connect Claude to OpenRouter Instead of logging in with Anthropic directly, connect Claude Code to OpenRouter. This requires setting a few environment variables. Requirements: Use the full OpenRouter Anthropic-compatible base URL, including the scheme: https://openrouter.ai/api (not https://openrouter.ai/api/v1 — Claude Code appends /v1/messages, so /api/v1 doubles the path to /api/v1/v1/messages and returns 404) Provide your OpenRouter API key as ANTHROPIC_AUTH_TOKEN Important: Explicitly blank out ANTHROPIC_API_KEY to prevent conflicts Why ANTHROPIC_AUTH_TOKEN: OpenRouter is an LLM gateway that authenticates requests with a bearer token, and Claude Code sends ANTHROPIC_AUTH_TOKEN as Authorization: Bearer <token> — the credential variable Anthropic documents for bearer-authenticated gateways. ANTHROPIC_API_KEY is instead sent as x-api-key, is treated as a direct-Anthropic credential, and prompts you once in interactive mode to approve it over a saved login. Setting it to an empty string keeps Claude Code from falling back to authenticating against Anthropic directly. Shell Profile Project Settings FileAdd these environment variables to your shell profile:# Open your shell profile in nano nano ~/.zshrc # or ~/.bashrc for Bash users # Add these lines to the file: export OPENROUTER_API_KEY="<your-openrouter-api-key>" export ANTHROPIC_BASE_URL="https://openrouter.ai/api" export ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY" export ANTHROPIC_API_KEY="" # Important: Must be explicitly empty export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1 # Optional: enables the gateway model picker Then reload your shell so the new values are live — otherwise you will keep testing the old environment and conclude the configuration does not work:source ~/.zshrc # or ~/.bashrc, or open a new terminal Persistence: We recommend adding these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.config/fish/config.fish).Ordering matters: ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY" is expanded when the profile is sourced. If OPENROUTER_API_KEY is defined later in the file, in a different file, or injected by a secrets manager after your profile runs, the auth token expands to an empty string and every request fails with an auth error. Ensure the key is defined before it is consumed by ANTHROPIC_AUTH_TOKEN, or put it in a file that loads earlier (e.g. ~/.zshenv for zsh).Secret hygiene: This puts a plaintext API key in your shell profile — a file that is easy to accidentally commit to a dotfiles repo or paste into a gist. Consider loading the key from your OS keychain instead, e.g. on macOS: export OPENROUTER_API_KEY="$(security find-generic-password -s openrouter -w)". If a key does leak, revoke and rotate it at openrouter.ai/settings/keys.Alternatively, you can configure Claude Code using a project-level settings file at .claude/settings.local.json in your project root:Claude Code’s settings.json / settings.local.json env values are literal strings (shell variables like $OPENROUTER_API_KEY are not expanded). To avoid writing your plaintext API key into a settings file, export OPENROUTER_API_KEY in the shell that launches claude (without setting ANTHROPIC_AUTH_TOKEN, which takes precedence over apiKeyHelper):# macOS / Linux / WSL export OPENROUTER_API_KEY="<your-openrouter-api-key>" # Windows (PowerShell) $env:OPENROUTER_API_KEY = "<your-openrouter-api-key>" Then configure apiKeyHelper in .claude/settings.local.json (macOS / Linux / WSL):{ "env": { "ANTHROPIC_BASE_URL": "https://openrouter.ai/api", "ANTHROPIC_API_KEY": "", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1" }, "apiKeyHelper": "printf '%s' \"$OPENROUTER_API_KEY\"" } On native Windows, Claude Code runs apiKeyHelper through cmd, so invoke PowerShell explicitly to print the key:{ "env": { "ANTHROPIC_BASE_URL": "https://openrouter.ai/api", "ANTHROPIC_API_KEY": "", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1" }, "apiKeyHelper": "powershell -NoProfile -Command \"[Console]::Write($env:OPENROUTER_API_KEY)\"" } Cost statusline: If you also set up the optional cost statusline below, its script reads ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY. When authenticating via apiKeyHelper, update that script to read OPENROUTER_API_KEY instead.Or, if you keep .claude/settings.local.json untracked in .gitignore and prefer a static token:{ "env": { "ANTHROPIC_BASE_URL": "https://openrouter.ai/api", "ANTHROPIC_AUTH_TOKEN": "<your-openrouter-api-key>", "ANTHROPIC_API_KEY": "", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1" } } Replace <your-openrouter-api-key> with your actual OpenRouter API key.Note: .claude/settings.local.json is ignored by Git by default in Claude Code projects, while .claude/settings.json is intended for shared repo config. With apiKeyHelper, you can safely commit .claude/settings.json without putting any secret on disk. Variable Location: Do not put these in a project-level .env file. The native Claude Code installer does not read standard .env files. Step 3: Clear any cached Anthropic login If you were previously logged in to Claude Code with an Anthropic account, you must run /logout once to remove the cached session. Claude Code warns about auth conflicts when both a cached login and a gateway credential are present, and the conflict can cause unexpected behaviour on startup — typically surfacing as confusing model-not-found errors (e.g. for openrouter/auto, openrouter/pareto-code, or any other OpenRouter-only model). > /logout Then quit and re-launch claude so it picks up the new environment variables. If you have never logged in to Claude Code with Anthropic, you can skip this step. Where the cached login lives: On macOS the cached session is stored in the Keychain as a generic password named Claude Code-credentials (native installs do not write ~/.claude/.credentials.json). If you are debugging a stubborn auth conflict, you can confirm a stale session exists with:security find-generic-password -s "Claude Code-credentials" If it prints an entry after /logout, delete it with security delete-generic-password -s "Claude Code-credentials" and relaunch claude. Step 4: Start your session Navigate to your project directory and start Claude Code: cd /path/to/your/project claude You are now connected! Any prompt you send will be routed through OpenRouter. Step 5: Verify You can confirm your connection by running the /status command inside Claude Code. > /status Auth token: ANTHROPIC_AUTH_TOKEN Anthropic base URL: https://openrouter.ai/api If the Auth token line names ANTHROPIC_API_KEY, or a Login method line names a Claude account instead, the environment did not reach the session — reload your shell and relaunch claude. You can also check the OpenRouter Activity Dashboard to see your requests appearing in real-time. How It Works OpenRouter exposes an input that is compatible with the Anthropic Messages API. Direct Connection: When you set ANTHROPIC_BASE_URL to https://openrouter.ai/api, Claude Code speaks its native protocol directly to OpenRouter. No local proxy server is required. Anthropic Skin: OpenRouter’s “Anthropic Skin” behaves exactly like the Anthropic API. It handles model mapping and passes through advanced features like “Thinking” blocks and native tool use. Billing: You are billed using your OpenRouter credits. Usage (including reasoning tokens) appears in your OpenRouter dashboard. Configuring Models Claude Code uses several environment variables to determine which models to use for different tasks. You can override these to route each role through a specific model: export ANTHROPIC_DEFAULT_FABLE_MODEL="~anthropic/claude-fable-latest[1m]" export ANTHROPIC_DEFAULT_OPUS_MODEL="~anthropic/claude-opus-latest[1m]" export ANTHROPIC_DEFAULT_SONNET_MODEL="~anthropic/claude