Перейти к основному содержанию

Documentation Index

Fetch the complete documentation index at: https://docs.crazyrouter.com/llms.txt

Use this file to discover all available pages before exploring further.

Claude Code is one of the best terminal coding tools to connect to Crazyrouter. It speaks the Anthropic Messages API directly and works especially well for code reading, editing, refactoring, command execution, tool use, and long-context repository analysis.

Overview

With a few environment variables, Claude Code can send Anthropic requests directly to Crazyrouter:
  • recommended protocol: Anthropic Messages API
  • base URL: https://crazyrouter.com
  • China-optimized base URL: https://cn.crazyrouter.com
  • auth variable: ANTHROPIC_API_KEY
  • recommended default model: claude-sonnet-4-6
Claude Code appends the Anthropic request path itself, so the base URL must stay at the site root: https://crazyrouter.com or https://cn.crazyrouter.com. Do not append /v1 or /v1/messages.

View the Claude Code one-click setup repository

If you want a script to install Claude Code and write the Crazyrouter environment variables for you, review the crazyrouter-claude-code repository.

Best For

  • developers who want Crazyrouter as the backend for Claude Code
  • users who want stable tool use, long context, and terminal-first coding workflows
  • teams that want Claude Code billed separately from Cursor, Codex, or Aider
  • cross-platform setups that need one consistent CLI configuration

Protocol Used

Recommended protocol: Anthropic Messages API Use:
ANTHROPIC_BASE_URL=https://crazyrouter.com
For the China-optimized API route, use:
ANTHROPIC_BASE_URL=https://cn.crazyrouter.com
Do not use:
  • https://crazyrouter.com/v1
  • https://crazyrouter.com/v1/messages
  • https://crazyrouter.com/v1/complete
  • https://cn.crazyrouter.com/v1
  • https://cn.crazyrouter.com/v1/messages

System Requirements And Prerequisites

ItemNotes
Crazyrouter accountCreate one at crazyrouter.com
Crazyrouter tokenCreate a dedicated sk-... token for Claude Code
Gitgit 2.23+ is recommended for reviewing and rolling back AI edits
Node.jsNode.js 18+ is recommended
Claude CodeUse a current stable release
Claude model accessAllow at least claude-sonnet-4-6 on the token
Suggested starter allowlist:
  • claude-sonnet-4-6
  • claude-opus-4-6

Full Install Paths By OS

On Windows, the safest path is: Git + Node.js + npm global install for Claude Code + PowerShell for environment variables. Recommended order:
  1. Install Git
  2. Install Node.js LTS
  3. Install Claude Code with npm
  4. Set temporary variables in PowerShell
  5. Persist user-level variables in PowerShell
Recommended verification:
git --version
node -v
npm -v
claude --version
where.exe git
where.exe node
where.exe claude
If claude --version is still not found, close and reopen PowerShell before retrying. On macOS, the smoothest path is usually: Xcode Command Line Tools + Homebrew + Git + Node.js + npm global install for Claude Code + ~/.zshrc for persistent environment variables. Recommended order:
  1. Install Xcode Command Line Tools
  2. Install Homebrew if needed
  3. Install Git and Node.js
  4. Install Claude Code with npm
  5. Persist variables in ~/.zshrc
  6. Open a fresh terminal and verify the binary path
Recommended verification:
git --version
node -v
npm -v
claude --version
which git
which node
which claude

Why you should not append API paths manually

Claude Code uses the Anthropic-native protocol. You only provide the site root:
ANTHROPIC_BASE_URL=https://crazyrouter.com
The China-optimized route also uses only the site root:
ANTHROPIC_BASE_URL=https://cn.crazyrouter.com
Do not append /v1, /v1/messages, or any specific API path the way you would with an OpenAI-compatible client. If you prefer a script that installs Claude Code and writes the Crazyrouter-related environment variables automatically, see crazyrouter-claude-code. That repository provides one-click setup scripts for Windows, macOS, and Linux; this guide keeps the full manual path so you can audit each setting.

Full Setup From Scratch

1

Step 1: Install Git

If Git is not installed yet, install it first before touching Claude Code.
winget install --id Git.Git -e --source winget
git --version
After installation, set your global identity once:
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
2

Step 2: Install Node.js 18+

Claude Code depends on Node.js. Verify the installed version before going further.
winget install OpenJS.NodeJS.LTS
node -v
npm -v
If node -v is still below 18 after installation, upgrade through nvm or the official Node installer before continuing.
3

Step 3: Install Claude Code

npm install -g @anthropic-ai/claude-code
claude --version
where.exe claude
Do not use sudo npm install -g @anthropic-ai/claude-code. If global npm permissions are broken, fix the npm/Node environment first instead of forcing a privileged install.
4

Step 4: Create a dedicated Crazyrouter token for Claude Code

Log in to Crazyrouter and create a separate token named something obvious like claude-code.For the first pass, allow only:
  • claude-sonnet-4-6
  • claude-opus-4-6
Give it its own budget so it does not share spend with Cursor, Codex, or OpenClaw.
5

Step 5: Set temporary environment variables in the current terminal

Start with a temporary setup first. Once validation succeeds, make it persistent.
export ANTHROPIC_BASE_URL=https://crazyrouter.com
export ANTHROPIC_API_KEY=sk-xxx
echo $ANTHROPIC_BASE_URL
echo $ANTHROPIC_API_KEY
If you use the China-optimized route, set ANTHROPIC_BASE_URL to the root domain https://cn.crazyrouter.com, not https://cn.crazyrouter.com/v1.
6

Step 6: Persist the environment variables

Temporary variables disappear after the shell closes. For regular use, write them to your shell profile.
echo 'export ANTHROPIC_BASE_URL=https://crazyrouter.com' >> ~/.bashrc
echo 'export ANTHROPIC_API_KEY=sk-xxx' >> ~/.bashrc
source ~/.bashrc
If you use the China-optimized route, persist ANTHROPIC_BASE_URL as https://cn.crazyrouter.com.Then open a fresh terminal and re-check:
claude --version
echo $ANTHROPIC_BASE_URL
7

Step 7: Prepare your Git repository

Claude Code can edit files and run commands. For the first validation, use a repo you know well.If the current folder is not a Git repo yet:
git init
git add .
git commit -m "chore: initial snapshot before Claude Code"
If it is already an existing repo, at least confirm the current state first:
git status
8

Step 8: Launch Claude Code and complete the first validation

Enter the project directory and run:
cd /path/to/your/project
claude
For the first validation, use this order:
  1. Reply with only OK
  2. Read the current repository structure only. Do not modify any files.
  3. Find obvious typos in the README, but do not edit files yet.
If all three work and Crazyrouter logs show matching requests, the setup is good.
Use caseRecommended modelWhy
default daily driverclaude-sonnet-4-6best balance of quality, speed, and cost for most coding tasks
difficult refactorsclaude-opus-4-6stronger complex reasoning, planning, and code understanding
long-context repo analysisclaude-sonnet-4-6stable and strong for long sessions
cost-sensitive first validationclaude-sonnet-4-6first get the main path working reliably
Recommended rollout: stabilize normal work on claude-sonnet-4-6, then switch to claude-opus-4-6 only for genuinely heavier tasks.

Использование не-Claude моделей в Claude Code

Помимо нативного семейства Claude, Crazyrouter транслирует ряд сторонних моделей через протокол Anthropic Messages. В Claude Code их можно использовать простой сменой имени модели. Список ниже проверен сквозным тестированием (текст / system / tool use / streaming SSE — все четыре пункта пройдены).

Проверенные рабочие модели

Model IDПоставщикTool UseStreamingThinkingНазначение
deepseek-v4-proDeepSeekУниверсальный кодинг и рефакторинг, лучшее соотношение цена/качество
deepseek-v4-flashDeepSeek✅ нативноРассуждения с видимыми блоками thinking
deepseek-reasonerDeepSeekreasoningМатематика, сложная логика
deepseek-chat / deepseek-v3 / deepseek-v3.2 / deepseek-r1DeepSeekОбщие текстовые задачи
MiniMax-M2.7MiniMax⚠️ внутри text-блока как теги <think>Длинный контекст, китайские задачи
MiniMax-M2.5MiniMax⚠️ внутри text-блокаОбщий чат
MiniMax-M2.1MiniMaxБез thinking, чистейший вывод
kimi-k2.5 / kimi-k2 / kimi-k2-instructMoonshot KimiДлинный контекст, работа на китайском
kimi-k2-thinkingMoonshot KimireasoningСложные рассуждения
kimi-k2-0711-preview / kimi-k2-0905-previewMoonshot KimiSnapshot-версии
Тестирование выполнялось на https://crazyrouter.com/v1/messages с заголовком anthropic-version: 2023-06-01 и стандартным телом запроса Anthropic Messages.
Следующие модели сейчас возвращают get_channel_failed на протоколе Anthropic (это вопрос доступности upstream-канала, а не несовместимости протокола). Используйте их пока через /v1/chat/completions (протокол OpenAI):
  • moonshot-v1-8k / moonshot-v1-32k / moonshot-v1-128k
  • kimi-k2-0905 (без суффикса -preview)
Каналы вроде grok-*, coze, jimeng, baidu, zhipu, tencent, xunfei, mistral, cohere, palm не реализуют конвертацию протокола Anthropic и не могут быть использованы в Claude Code.

Как переключать модели

Claude Code берёт модель из переменной окружения ANTHROPIC_MODEL либо из команды /model внутри сессии. Подставьте любой ID из таблицы выше.
export ANTHROPIC_BASE_URL=https://crazyrouter.com
export ANTHROPIC_API_KEY=sk-xxx

# По умолчанию — DeepSeek V4 Pro
export ANTHROPIC_MODEL=deepseek-v4-pro
claude

# Разовый запуск с Kimi thinking
ANTHROPIC_MODEL=kimi-k2-thinking claude

# Разовый запуск с MiniMax
ANTHROPIC_MODEL=MiniMax-M2.1 claude
Также можно переключаться внутри запущенной сессии Claude Code:
/model deepseek-v4-pro
/model kimi-k2-thinking
/model MiniMax-M2.1

Замечания по использованию и известные различия

  • Семейство DeepSeek: максимальная совместимость с протоколом. Tool calls, streaming и stop_reason=tool_use соответствуют спецификации Anthropic; deepseek-v4-flash отдаёт нативные блоки thinking, которые Claude Code показывает в виде панели рассуждений. Рекомендуемое значение по умолчанию: deepseek-v4-pro.
  • Семейство Kimi: стабильная работа с длинным контекстом, tool calls работают штатно. kimi-k2-thinking содержит трассу рассуждений — полезно для сложных задач.
  • Семейство MiniMax: единственные модели, у которых в записи прайс-листа поле supported_endpoint_types явно содержит anthropic, поэтому уровень протокола подходит лучше всего. Однако M2.5 / M2.7 отдают рассуждения в обычном text-блоке обёрнутыми тегами <think>...</think> — Claude Code показывает их как есть. Способы избежать:
    1. Использовать MiniMax-M2.1 (без рассуждений).
    2. Добавить system-подсказку: «Не выводите теги <think> и сами рассуждения, только итоговый ответ».
  • Allowlist токена: если на вашем выделенном для Claude Code токене включён whitelist моделей, добавьте туда нужные модели в панели Crazyrouter, иначе будет 403 model not allowed.
  • Thinking и тарификация: модели с thinking (-thinking, -flash, reasoner, MiniMax-M2.5/2.7) расходуют дополнительные output-токены. Установите отдельный лимит бюджета на токен для Claude Code.

Однострочная проверка работоспособности модели

curl -sS https://crazyrouter.com/v1/messages \
  -H "Authorization: Bearer $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4-pro",
    "max_tokens": 32,
    "messages": [{"role":"user","content":"reply OK"}]
  }'
Ответ 200 с непустым content[].text означает, что Claude Code может использовать эту модель.

Token Setup Best Practices

SettingRecommendationNotes
dedicated tokenRequiredDo not share Claude Code tokens with Cursor, Codex, or OpenClaw
model allowlistStrongly recommendedMost Claude Code setups only need 1 to 2 Claude models
IP restrictionRecommended on fixed-egress environmentsBe careful on laptops with changing IPs
quota capStrongly recommendedLong sessions and tool use can steadily consume budget
developer / host splitRecommendedGive each developer or shared host its own token
incident rotationRequiredIf shell history, recordings, or shared terminals expose the token, rotate it immediately

Verification Checklist

  • git --version works
  • node -v is at least 18
  • claude --version works
  • ANTHROPIC_BASE_URL is set to https://crazyrouter.com or https://cn.crazyrouter.com
  • ANTHROPIC_API_KEY is set correctly
  • Claude Code launches successfully
  • the first plain-text request succeeds
  • repository read-only inspection works
  • Crazyrouter logs show the Claude Code traffic
  • token quota and model allowlist match your intended setup

Common Errors And Fixes

SymptomLikely causeFix
claude: command not foundClaude Code did not install cleanly, or the npm global path is not on PATHreinstall and make sure the global npm bin directory is in PATH
Node version is too oldlocal Node.js version is below the requirementupgrade to Node.js 18+ and reinstall Claude Code
401 unauthorizedinvalid, expired, or badly pasted ANTHROPIC_API_KEYcreate a new token and set the variables again
403 or model not allowedthe token does not allow the selected Claude modelallow the required model in Crazyrouter
404base URL was set with /v1 or /v1/messagesreset it to https://crazyrouter.com or https://cn.crazyrouter.com
logs show /v1/v1/messages, /v1/v1/models, or /v1/messages/v1/messagesClaude Code was given a base URL that already contains /v1 or a full endpoint, then appended its own pathset ANTHROPIC_BASE_URL to the root domain with no path
Claude Code still uses old settingsnew environment variables were not reloadedreopen the terminal or run source ~/.bashrc / source ~/.zshrc
Git changes become messyno repository snapshot was created before AI editscommit an initial snapshot before larger changes
cost is higher than expectedlong context, repeated tool use, and long sessionsshorten sessions, split tasks, and cap budget per token

Performance And Cost Tips

  • start with claude-sonnet-4-6
  • switch to claude-opus-4-6 only for hard architecture analysis or heavy refactors
  • validate first in a small repo, not a large production repo
  • check git status before each new task
  • watch Crazyrouter logs and quota more closely when tool use becomes frequent

FAQ

Which base URL should I use for Claude Code?

Use the site root: https://crazyrouter.com For the China-optimized route, use the site root: https://cn.crazyrouter.com

Why should I not include /v1 here?

Because Claude Code appends the Anthropic Messages path itself. You only provide the site root.

What should I use on Windows?

If you mainly develop from the command line, prefer PowerShell or WSL2. In either case, make sure Git, Node.js, and Claude Code itself are installed correctly first.

On Windows, should I use PowerShell or Git Bash?

For first-time setup, prefer PowerShell. Environment-variable persistence, where.exe checks, and user-level configuration are all more direct there.

Why should I create a Git snapshot before the first real task?

Because Claude Code can edit files and run commands. A clean snapshot makes review and rollback much easier.

Which model should I try first?

Start with claude-sonnet-4-6. It is usually the safest baseline.
If your first priority is Claude-family models plus a terminal-first coding workflow, Claude Code should be near the front of your Crazyrouter integration order.

View the crazyrouter-claude-code repository

Review the one-click setup scripts, README, and latest usage notes.