Trae

How to fix Trae returning 401 or an invalid API key

A 401 means the request reached the AI Code With server and failed at authentication. The problem is the API key itself, its validity, or the account state — not the Request URL or Model ID. Paste the key only in Trae's Add Model dialog.

Start with these checks

The request reached AI Code With, but authentication failed. Verify the API key in Add Model before changing the Request URL or Model ID.

  • After sending a message, Trae reports 401, Unauthorized, or Invalid API Key.
  • The pasted API key is incomplete, has extra spaces or newlines, or is the wrong key
  • Open Trae's Add Model dialog and select the custom model you added
401UnauthorizedInvalid API Key

01

Confirm the request reached the server

401 / Unauthorized / Invalid API Key means the HTTP request reached AI Code With and was rejected while checking the Authorization header. Do not change the Request URL or Model ID yet.

Timeouts, DNS failures, or 404s are address, protocol, or network problems — use the Request URL or protocol-mismatch articles first. Follow this page only when the error is explicitly 401.

02

Re-paste the API key in Add Model

Open Add Model, clear the API Key field, and paste the full key. Avoid copied newlines, surrounding spaces, or quotes.

The API key stays in Trae on this machine. Do not put a real key in a repo, screenshot, or shared config; this page never collects real keys.

  1. 1Open Trae's Add Model dialog and select the custom model you added
  2. 2Clear the API Key field and paste the full key again, with no spaces or newlines

03

Verify the key and account, then send a test message

In the AI Code With dashboard, confirm the key is still valid and the account has balance. Expired, disabled, or zero-balance keys also return 401 at authentication.

After saving, turn off Auto, pick that custom model, and send a short message. A normal reply with no 401 restores the credential chain. Then match the call by time in usage records.

  1. 1Clear the API Key field and paste the full key again, with no spaces or newlines
  2. 2In AI Code With Key Management, confirm the key is active and the account has balance

Copying or saving the model is not a successful connection. The checkable signals are a real reply and a matching usage-record entry.

If it is still not fixed

Sources

Reconfigure

Return to the integration center and continue the setup steps.

Return to the related setup step