OpenCode

OpenCode "API key has expired" or 401 Unauthorized: How to Fix

"API key has expired" means OpenCode is still using its own key: switch to AI Code With at https://api.aicodewith.ai/v1. "Unauthorized: 请在请求中提供有效的 API Key。" means your AI Code With key is wrong or expired.

Start with these checks

The request reached the service but authentication failed.

  • OpenCode returns 401, Unauthorized, or Invalid API Key.
  • The API Key is incomplete or expired
  • Copy a fresh API Key from AI Code With
401Unauthorized

01

Error: "Unauthorized: 请在请求中提供有效的 API Key。"

There are two cases. Case 1: if OpenCode says "API key has expired", you are still using OpenCode's own key. Switch to AI Code With: edit ~/.config/opencode/opencode.json, set options.baseURL to https://api.aicodewith.ai/v1 for both Anthropic and OpenAI-compatible models, and put your AI Code With API Key in options.apiKey. Case 2: if the error is "Unauthorized: 请在请求中提供有效的 API Key。", your AI Code With key is wrong or expired; create a new key in the AI Code With console and paste it into options.apiKey. If you see "Not Found: 不支持的请求路径", the address is missing /v1. Save, reopen OpenCode, run /models and send a test message. A 401 or Unauthorized response means the request arrived at the service, so check the API Key and Provider before changing the model.

02

Check the credential and Provider

In the generated JSON, confirm apiKey is inside the provider options and the Provider ID exactly matches the value generated on this page.

  1. 1Copy a fresh API Key from AI Code With
  2. 2Replace the placeholder with the complete key

03

Verify again

Save, reopen OpenCode, run /models, and send a short message. No 401 means the credential path is working.

  1. 1Replace the placeholder with the complete key
  2. 2Confirm the Provider ID matches the generated config

If it is still not fixed

Sources

Reconfigure

Return to the integration center and continue the setup steps.

Return to the related setup step

Related problems

Model missing from /models or Model Not Found · Model is listed but the request does not complete · Wrong Base URL, 404, or connection failure · opencode command not found · Rate limit or 429 · Usage is recorded but OpenCode shows no reply · reasoning part/text part not found or summaryParts parsing error · Invalid opencode.json · 403 Forbidden · BunInstallFailedError or models.dev download failure

Back to OpenCode