Claude Code behind your own gateway: five places it breaksClaude Code на своём шлюзе: пять мест, где ломается
Claude Code is an ordinary HTTP client: two kinds of compatibility, one base URL without /v1, two header shapes for the key. Where the silent failures come from and in what order to check them.Claude Code — обычный HTTP-клиент: два вида совместимости, base URL без /v1 и два варианта заголовка с ключом. Откуда берутся молчаливые отказы и в каком порядке их проверять.
Two kinds of compatibilityДва вида совместимости
Claude Code does not integrate with Anthropic as a company: it sends a POST to /v1/messages in the Anthropic Messages shape and reads an SSE stream. Any server answering in that shape will do — the native API is only one of them.Claude Code не интегрируется с Anthropic как с компанией: он отправляет POST на /v1/messages в форме Anthropic Messages и читает поток SSE. Подойдёт любой сервер, который отвечает в этой форме, — нативный API лишь один из вариантов.
Compatibility comes in two flavours. OpenAI-compatible is /v1/chat/completions; Anthropic-compatible is /v1/messages. Claude Code needs the second. Cursor, Cline and Codex mostly need the first. A gateway that speaks only OpenAI is useless for Claude Code, however many models it lists.Совместимость бывает двух видов: OpenAI-совместимая — это /v1/chat/completions, Anthropic-совместимая — /v1/messages. Claude Code нужен второй. Cursor, Cline и Codex в основном первый. Шлюз, который умеет только OpenAI, для Claude Code бесполезен, сколько бы моделей он ни перечислял.
The /v1 in the base URLЛовушка /v1 в base URL
OpenAI SDKs expect base_url with /v1 and append /chat/completions themselves. Claude Code is the opposite: ANTHROPIC_BASE_URL takes the host without /v1, and the client appends /v1/messages on its own.SDK OpenAI ждут base_url с /v1 и сами дописывают /chat/completions. У Claude Code наоборот: ANTHROPIC_BASE_URL принимает хост без /v1, а клиент сам дописывает /v1/messages.
Set the URL with /v1 and the request goes to /v1/v1/messages: a 404 that looks like a bad model or a broken body, because the body was valid.Укажете адрес с /v1 — запрос уйдёт на /v1/v1/messages: 404, который выглядит как ошибка модели или тела, хотя тело было корректным.
The key goes in one of two headersКлюч живёт в одном из двух заголовков
ANTHROPIC_API_KEY sends x-api-key, ANTHROPIC_AUTH_TOKEN sends Authorization: Bearer. Gateways usually accept one of the two, and the key can be valid while the answer is still 401.ANTHROPIC_API_KEY отправляет x-api-key, ANTHROPIC_AUTH_TOKEN — Authorization: Bearer. Шлюзы обычно принимают что-то одно из двух, и ключ может быть валидным, а ответ всё равно 401.
One curl against GET /v1/models with each header tells you which one your gateway expects. The same 401 also appears when a native Anthropic key is used against a gateway key.Один curl на GET /v1/models с каждым заголовком показывает, какой из них ждёт шлюз. Тот же 401 бывает и тогда, когда вместо ключа шлюза подставили нативный ключ Anthropic.
Model ids must match the catalogИмя модели должно совпадать с каталогом
ANTHROPIC_MODEL and the default model variables take an id that has to exist in the gateway catalog character for character. A name from the Anthropic docs and a provider profile are different identifiers, and nothing obliges one to alias the other.ANTHROPIC_MODEL и переменные моделей по умолчанию принимают id, который должен существовать в каталоге шлюза символ в символ. Имя из документации Anthropic и профиль провайдера — разные идентификаторы, и никто не обязан делать один псевдонимом другого.
If the name is wrong, the CLI either gets a 404 on the model or falls back to the gateway default. The second is worse: it works, just not on the model you think.При неверном имени CLI получает либо 404 по модели, либо откат на модель по умолчанию. Второе хуже: всё работает, только не на той модели, о которой вы думали.
Limits and what the codes meanЛимиты и что значат коды
An agent is not a chat: dozens of calls per task, context dragged along, files re-read. Without a cap on the key, one long refactoring run eats the balance.Агент — не чат: десятки вызовов на задачу, контекст тащится за собой, файлы перечитываются. Без лимита на ключе один длинный рефакторинг съедает баланс.
Read the codes literally: 401 — the key or the header, 402 — balance or key limit, 403 — model not allowed for this key, 404 — the model name, 429 — rate. Collapsing them into one "error" costs an evening of guessing.Коды читаются буквально: 401 — ключ или заголовок, 402 — баланс или лимит ключа, 403 — модель не разрешена ключу, 404 — имя модели, 429 — частота. Свалить их в одно «ошибка» — потерять вечер на догадки.