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

Ошибка API-ключа OpenClaw: 401, No API Key, 429 и gateway auth

A
18 мин чтенияУстранение неполадок ИИ

У ошибок API key в OpenClaw нет универсального исправления. Сначала проверьте status, gateway status, logs, doctor и models status, затем определите owner: provider auth, gateway token, channel permission, model cooldown, request shape, context pressure или Docker env override.

Ошибка API-ключа OpenClaw: 401, No API Key, 429 и gateway auth

Ошибки API key в OpenClaw могут выглядеть как 401 Unauthorized, No API key found for provider, AUTH_TOKEN_MISMATCH, all in cooldown, 429 Too Many Requests или общий gateway/channel failure. Не начинайте с ротации всех ключей. Сначала докажите, какой слой дал первую ошибку: model provider, OpenClaw gateway, channel/client, Docker env override или context pressure, который выглядит как API failure.

Короткий ответ

Перед изменением credentials выполните:

bash
openclaw status openclaw gateway status openclaw logs --follow openclaw doctor openclaw models status

Если logs показывают No API key found for provider "anthropic" или другой provider, запустите openclaw onboard или добавьте provider auth profile, затем проверьте openclaw models status. Если видно AUTH_TOKEN_MISMATCH, device nonce, pairing required или gateway 1008, исправляйте gateway/client auth, not Anthropic key. Если это 429, соблюдайте retry-after, уменьшайте context/tool loops или переходите на configured and tested fallback provider. Если проблема только в Docker, сначала смотрите env | grep OPENCLAW внутри container.

Определите owner, а не меняйте key вслепую

SymptomLikely ownerFirst evidenceFirst action
No API key found for providerProvider auth profileopenclaw models statusRun onboarding или add provider auth
401, invalid bearer token, incorrect api keyProvider key, base URL или account accessprovider console + OpenClaw logsReplace key, fix base URL, confirm model access
AUTH_TOKEN_MISSING / AUTH_TOKEN_MISMATCHGateway/client authopenclaw gateway status --json или connect detailsUpdate client token или re-pair device
PAIRING_REQUIRED, channel 401/403Channel/device permissionchannel status/logsFix pairing, scope, allowlist
429, all in cooldownProvider quota/cooldownprovider headers + first logWait, reduce concurrency/context, switch fallback
context_length_exceeded after fallbackContext или quota symptomfirst provider logClassify quota/fallback before context tuning
Docker-only token mismatchEnv override`docker exec envgrep OPENCLAW`

Последнее visible message часто не является root cause. Например, all in cooldown может быть последним summary, а первый log был 401, 429, network timeout или wrong gateway token.

401: provider auth, gateway token, channel permission

Layer 1: provider authentication. Если log говорит No API key found for provider, OpenClaw не нашел credential для выбранного provider/model route. Используйте openclaw onboard или current provider-specific auth command, затем openclaw models status. Не проверяйте валидность только по key prefix: formats меняются, custom gateways могут иметь другой token shape.

Для Anthropic key вне OpenClaw используйте current Anthropic API docs и модель, доступную вашему account. Важно не конкретное имя модели из статьи, а принимает ли provider этот key сегодня.

bash
curl -s https://api.anthropic.com/v1/messages \ -H "x-api-key: YOUR_KEY_HERE" \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d '{"model":"YOUR_ACCESSIBLE_MODEL","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}' \ | head -c 200

Layer 2: gateway token / device identity. AUTH_TOKEN_MISSING, AUTH_TOKEN_MISMATCH, AUTH_DEVICE_TOKEN_MISMATCH, PAIRING_REQUIRED — gateway/client issues. Shared-token clients need current gateway token. Device-token flows require re-approval or rotation. Pairing-required clients need approved request. Не заменяйте provider key только потому, что увидели 401-like failure.

Layer 3: upstream provider rejection. Upstream может отклонить запрос из-за revoked key, billing/account state, unavailable model, wrong base URL или env override. Account tier, region, model access и billing — volatile facts; проверяйте provider console.

Cooldown is a symptom. all in cooldown означает, что OpenClaw временно не использует route. Найдите first failure before cooldown. Clearing cooldown without fixing root cause повторит loop.

429: headers, owner and recovery

429 обычно означает, что selected provider, gateway route, hub route или account/project owner отказывает в новой работе в текущем window. Это не доказывает invalid key и не всегда Anthropic. OpenAI-compatible providers, Gemini routes, private gateways и download hubs могут показывать rate-limit language через OpenClaw.

Provider limits меняются по account, model, region, project и route. Не копируйте старые tier tables. Evidence — provider dashboard и response headers. На Anthropic route ответ может включать retry-after и anthropic-ratelimit-* headers:

HeaderWhat to readHow to use
retry-afterprovider wait timesleep returned value
anthropic-ratelimit-requests-limitrequest ceiling for current key/account/routetreat as live contract
anthropic-ratelimit-requests-remainingrequest budget leftreduce request frequency if exhausted
anthropic-ratelimit-requests-resetreset timeresume after live reset
anthropic-ratelimit-tokens-limittoken ceilingcompare with OpenClaw payload
anthropic-ratelimit-tokens-remainingtoken budget leftshorten context/tool output if exhausted
anthropic-ratelimit-tokens-resettoken reset timeretry after returned reset

Если request budget gone, batch small calls или reduce concurrency. Если token budget gone, shorten context, trim tool output, split tasks. Multiple keys или gateway вроде laozhang.ai — routing strategy only after each route has owner, billing, quota и tool support verified. Это не guaranteed extra quota.

400: invalid beta flag and context_length_exceeded

invalid_request_error: Invalid beta flag означает, что selected route не поддерживает provider feature flag в config. Proxy, Bedrock, Vertex или OpenAI-compatible gateway могут реализовывать только часть upstream API. Проверьте beta or capability fields и подтвердите support у actual provider route; иначе remove flag или switch route.

context_length_exceeded означает, что assembled request превышает usable context выбранного route. Payload может включать system prompt, tool schema, workspace context, memory/search, channel metadata и history. Не публикуйте fixed context-window number, если не verified exact model + provider + gateway route today. См. OpenClaw context_length_exceeded guide.

Если context error внезапно появляется after 429, cooldown или failover, сначала читайте rate-limit and first provider log.

502, 1008, SSL and Docker

502 Bad Gateway обычно значит invalid upstream response. Проверьте provider status, затем direct curl -v from host. Если direct connection работает, проверяйте proxy, base URL, connection pooling или gateway config.

1008 WebSocket / token mismatch требует connect detail code. Shared token drift, device token drift и pairing required имеют разные fixes. Сначала gateway status или failed connect response, затем update client token, approve device или handle pairing.

SSL errors бывают certificate chain или expiry. Не переносите NODE_TLS_REJECT_UNAUTHORIZED=0 в production. Enterprise TLS inspection должен идти через trusted CA / Node trust store.

Docker env override:

bash
docker exec <container_name> env | grep OPENCLAW

Если OPENCLAW_GATEWAY_TOKEN, provider key или base URL есть в container env и conflict with mounted config, исправляйте compose/env first.

Production retry and fallback boundary

ErrorRetry?Strategy
429Yesobey retry-after, reduce concurrency/context
529 / overloadYesback off, prefer provider guidance
502 / timeoutLimitedretry few times, then inspect upstream
401Nofix credentials
400Nofix request payload / route capabilities
403Nofix permissions/account/model access

Fallback is availability pattern, not permission to ignore limits. Backup provider must already be configured, authenticated, allowlisted, and compatible with tools, context, attachments and output requirements. Fallback does not fix invalid credentials, unsupported beta flags or broken hub downloads.

FAQ

How do I fix OpenClaw API key not working?

Run openclaw status, openclaw gateway status, openclaw logs --follow, openclaw doctor, openclaw models status. Use the first failure to classify provider auth, gateway auth, channel permission, quota or env override.

Why unauthorized if the key is correct?

Unauthorized can come from upstream provider, OpenClaw gateway or channel/client. Provider key may be valid while gateway token is stale, device token revoked or Docker env overrides config.

Should I reset gateway token?

Only if evidence points to AUTH_TOKEN_MISMATCH or shared-token drift. Device identity flow should re-approve or rotate device instead of changing provider key.

How to prevent OpenClaw 429?

Record billing/quota owner, monitor headers/dashboard, shorten context-heavy loops, limit concurrent agents and configure tested fallbacks before incidents.

Are skill loading errors API key errors?

Usually no. Run openclaw skills list, openclaw logs --follow and openclaw doctor; debug skill syntax, directory, dependency and allowlist separately.

Поделиться:

laozhang.ai

Один API, все модели ИИ

AI Изображения

Gemini 3 Pro Image

$0.05/изобр.
-80%
AI Видео

Sora 2 · Veo 3.1

$0.15/видео
Async API
AI Чат

GPT · Claude · Gemini

200+ моделей
Офиц. цена
Обслужено 100K+ разработчиков
|@laozhang_cn|$0.1 бонус