Skip to content
PromptFable guideTroubleshooting

Troubleshooting LLM API Errors

How to diagnose the errors you are most likely to meet when calling a model API: authentication, permissions and billing, rate limits, timeouts, malformed tool arguments, truncated output and unknown models.

For: Developers integrating an LLM API into an application or agent

Start by reading the whole error

Read the whole error response, not just the exception name: note the HTTP status code, the error type and message, and any request ID. The message often names the exact problem, and support teams can trace a request ID.

SymptomTypical statusRetry?
Key missing, invalid, expired or revoked401No: fix the credential
Key valid but not allowed to use this model, project or feature403No: fix access or settings
Billing not set up, or a quota or spending cap reachedVaries by providerNo, until billing or the quota changes
Unknown model or wrong endpoint404 or 400No: fix the model ID or URL
Malformed request body400No: fix the request
Too many requests or tokens429Yes, with backoff
Server error or overload500, 503 or another 5xxYes, with backoff
No response in time408, 504 or a client-side timeoutUsually, with care
Typical mappings only. Confirm them in your provider's documentation.

Authentication errors

The API rejects your credential. Usually the variable is not set in the process running your code, has a different name from the one your SDK expects, contains stray quotes or spaces, or holds a revoked or expired key.

  1. Step 1: Check the variable without printing it

    A variable set in one terminal is not visible in another, and IDE run configurations have their own environment.

    Pythoncheck_key.py
    import os
    
    NAME = "GEMINI_API_KEY"  # the name your SDK reads
    value = os.environ.get(NAME)
    if value is None:
        print(NAME, "is not set in this process")
    else:
        # Describe the key without revealing it
        print(NAME, "has", len(value), "characters")
        print("Stray spaces or quotes:", value != value.strip().strip('"'))

    What you should see: You learn whether the key is set and clean without it ever appearing on screen.

  2. Step 2: Confirm the key in the provider's console

    Check that it still exists, belongs to the account or project you expect and has not expired. If in doubt, create a new key and revoke the old one.

  3. Step 3: Restart whatever reads the environment

    Running processes keep the environment they started with, so restart the terminal, server or notebook after changing a variable or a .env file.

Permission and billing errors

The credential is valid, but the account cannot do what you asked: the model or feature is not enabled for your account, project or region; the key belongs to another project; billing is not set up; or a quota or spending limit has been reached.

  • Check which account, project or workspace the key belongs to.
  • Check your billing status and any spending limits set by you or your organisation.
  • Check the provider's current documentation for the models and features your plan and region include.
  • Do not create extra keys to get round the error. A new key on the same account normally has the same restrictions.

Rate limits and retries with backoff

A rate-limit error means too many requests or tokens in a time window. It is usually temporary: wait, then retry. Some rate-limit responses instead mean a quota or spending cap is used up, and retrying will not help until it resets.

  • Retry only transient failures: rate limits, server errors, overloads and network errors. Never retry authentication, permission or validation errors.
  • Wait longer after each attempt (exponential backoff) and add randomness (jitter) so that clients do not all retry at the same moment.
  • If the response includes a retry-after header, wait at least that long.
  • Cap the number of attempts and the total waiting time, then fail with a clear message.
  • Check whether your SDK already retries; official SDKs often do, and an extra loop around one multiplies the attempts.
Pythonbackoff.py
import random
import time

RETRYABLE = {408, 429, 500, 502, 503, 504}  # adjust from your provider's error reference


def send_with_backoff(send, max_attempts=5, base_delay=1.0, max_delay=30.0):
    for attempt in range(1, max_attempts + 1):
        response = send()
        if response.status_code < 400:
            return response
        if response.status_code not in RETRYABLE or attempt == max_attempts:
            # Truncate: error bodies can echo parts of your request
            raise RuntimeError(f"HTTP {response.status_code}: {response.text[:200]}")
        retry_after = response.headers.get("retry-after", "")
        if retry_after.isdigit():
            delay = float(retry_after)  # the server said how long to wait
        else:
            # Full jitter: a random wait under a growing ceiling
            delay = random.uniform(0, min(max_delay, base_delay * 2 ** (attempt - 1)))
        time.sleep(delay)

A sketch for raw HTTP calls, for example with requests or httpx. With an official SDK, configure its built-in retries instead.

Timeouts

No complete response arrived in time. The limit may sit in your HTTP client, a proxy or the provider. Long outputs are the usual cause: generation takes time, and networks may drop a connection that looks idle.

  • Set an explicit client timeout rather than trusting an unchecked default.
  • For long outputs, stream the response or ask for a shorter one.
  • Send only the conversation history and retrieved passages the task needs.
  • Before retrying, check for side effects. Repeating a model call costs tokens; repeating a tool that sends an email or issues a refund is unsafe unless that operation is idempotent.

Malformed tool arguments

In an agent, the model may request a tool with arguments that break your schema: a missing required field, a wrong type, an invented option or, occasionally, invalid JSON. The API call itself succeeded; its content is the problem.

  • Validate every tool request in your code before running anything, and treat a failure as a normal outcome, not a crash.
  • Return a short, specific error as the tool result, such as 'order_id must look like BW-1042', so the model can correct the call.
  • Stop after two or three failed corrections and ask the user for the missing information.
  • Make the schema easier to follow: clear descriptions, enumerated values for fixed choices, fewer optional fields.
  • If your provider offers a strict or validated mode for arguments, consider it, but keep validating: matching the schema is not the same as passing your business rules.

Truncated output

A response that stops mid-sentence, or JSON that ends abruptly, has usually hit its output token limit. The response's stop reason (some providers say finish reason) tells you why generation ended, including other early stops such as a safety filter.

  • Log the stop reason of every response, and treat a token-limit stop as incomplete output.
  • Raise the maximum output tokens for that request, within the model's documented limit.
  • Ask for less: a tighter format, fewer items, or the work split across several requests.
  • Parse and validate structured output before using it, so a truncated object fails loudly instead of being half-processed.

Model not found

The API does not recognise the model name, or your account cannot use it. Check for a typo, an ID copied from another provider or an old tutorial, a retired model, or one not offered on your plan or in your region.

  • Copy model IDs from the provider's current models page or list-models endpoint.
  • Keep the model ID in configuration, in one place, so changing it is a one-line change.
  • Follow the provider's deprecation notices, and re-run your evaluations whenever you change models.

When you are still stuck

  1. Check the provider's status page for an ongoing incident.
  2. Reproduce the failure with the smallest request you can: a short prompt, no tools, default settings.
  3. Compare your request with the provider's current quickstart for your SDK.
  4. Contact support with the request ID, the time and the error message, never your API key.
Written by
PromptFable Editorial
Last updated 13 Nov 2026
Review
Not yet reviewed
All developer resources

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.