Troubleshooting LLM API Errors: Diagnose Issues Layer by Layer Using Error Codes

    When an AI coding tool throws an error, repeatedly tweaking configuration files rarely helps. This guide shows a faster approach: read the error code first to determine whether the fault lies with the API key, endpoint, model name, rate limits, or network, then verify that layer with a single complete request. It covers common status codes such as 401, 402/403, 404, 400, 429, and connection timeouts, along with concrete verification commands and fixes for each layer.

    Start by Identifying the Fault Layer from the Error Code

    When an AI coding tool reports an error, many people keep editing configuration files while the problem persists. A more time-efficient approach is to look at the error code first, determine whether the failure involves the key, endpoint, model name, call rate, or network, and then verify that specific layer with one complete request.

    Status code or message Common causes How to verify Fix
    401 Unauthorized, Invalid API Key Key copied incorrectly, with leading/trailing spaces or newlines; key expired or revoked; missing Authorization header or wrong authentication scheme Check key length, use curl -v to inspect request headers, and confirm key status in the provider console Regenerate the key, rewrite the environment variable, and verify the authentication header format
    402 or 403, billing- or permission-related messages Insufficient account balance, or the key lacks permission to access the model. Status codes vary by provider; refer to the provider’s documentation Check balance and the key’s permission scope in the console Top up the balance, or grant the key access to the model
    404 Not Found, Endpoint not found Base URL is missing a version path such as /v1 Send a curl request to the full endpoint and inspect the response Complete the path according to the provider’s documentation
    400 Bad Request, Model not found The model ID does not match the identifier registered in the provider’s system Call the model list endpoint, or consult the official documentation Correct the model ID in the tool, or add a model mapping
    429 Too Many Requests Exceeding RPM or TPM limits, or too many concurrent requests Check usage in the console and see whether errors cluster at certain times Reduce concurrency and add backoff retries
    Connection timeout Network unreachable, proxy not configured, or blocked by a firewall or corporate gateway Use curl -v to see whether the request stalls at DNS, TCP, or TLS Configure a proxy, or allow the target domain

    Step 1: Check the API Key

    First, confirm the key itself is valid. After writing the key to an environment variable, run the following command to check its length:

    1. echo "${#LLM_API_KEY}"

    This command outputs only a number and never prints the full key to the terminal. If the length is one or two characters longer than the key format described in the provider’s documentation, the copy likely included a newline or space. Copy the key again, wrap the value in double quotes, and make sure the export statement is on a single line.

    If the key contains special characters such as backticks, &, or backslashes, wrap it in single quotes in the shell to prevent premature expansion. When writing the key to a configuration file, also check whether the tool escapes these characters.

    Step 2: Check the Endpoint and Network

    ping and traceroute only help determine whether the domain resolves. Many servers and gateways disable ICMP, so a failed ping does not mean the API is unavailable, and a successful ping does not mean the API returns data correctly. A more reliable method is to send one complete request to the real endpoint:

    1. curl -v "$LLM_BASE_URL/chat/completions" \
    2. -H "Authorization: Bearer $LLM_API_KEY" \
    3. -H "Content-Type: application/json" \
    4. -d '{"model": "your-model-id", "messages": [{"role": "user", "content": "hello"}], "max_tokens": 16}'

    /chat/completions works for most providers that are compatible with the OpenAI protocol. For non-OpenAI-compatible protocols, replace it with the provider’s actual path and request body fields. If the provider requires an api-key header instead of Authorization: Bearer, substitute it according to the documentation. Otherwise the request returns 401 and can easily be misdiagnosed as a key problem. Replace the model field with the real model ID from the console.

    Interpret the output as follows:

    • Returns HTTP/1.1 200 or HTTP/2 200 with JSON content: the network path, key, and model all work, so the problem most likely lies in the tool’s configuration panel.
    • Could not resolve host: DNS resolution failed; check the domain spelling and local DNS settings.
    • SSL certificate problem or handshake failure: check the system time and confirm whether a corporate gateway has replaced the certificate. If necessary, add the corporate root certificate to the trust store.
    • Stuck at Trying for a long time: the TCP connection cannot be established; check proxy settings and firewall rules.

    Step 3: Verify the Model ID

    Some providers offer a model list endpoint that returns the available model IDs directly:

    1. curl "$LLM_BASE_URL/models" \
    2. -H "Authorization: Bearer $LLM_API_KEY"

    The id field in the response is the model name you should enter in the tool. For some providers, the model list endpoint also requires specific permissions or a separate management key. If the list endpoint returns 403, go back to Step 1 and confirm permissions instead of repeatedly editing the model name. If the provider has no list endpoint, rely on the identifier shown in the official documentation or console.

    Identifiers with version numbers or date suffixes are different strings from the generic names, and the two are not interchangeable.

    If the tool supports custom model mapping, you can map the tool’s built-in generic names to the provider’s real IDs. Keep the mapping table under version control, update it whenever you switch provider models, and record the date and reason in the change log.

    Step 4: Handle 429 Rate Limiting

    A 429 status means the request rate exceeds the provider’s limits. Quotas usually fall into two categories: requests per minute (RPM) and tokens per minute (TPM). First check the account’s RPM and TPM limits in the console, then compare them against the tool’s request logs to determine whether you exceeded the request count, or whether a single overly long context caused the token limit to be exceeded.