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.
| Symptom | Typical status | Retry? |
|---|---|---|
| Key missing, invalid, expired or revoked | 401 | No: fix the credential |
| Key valid but not allowed to use this model, project or feature | 403 | No: fix access or settings |
| Billing not set up, or a quota or spending cap reached | Varies by provider | No, until billing or the quota changes |
| Unknown model or wrong endpoint | 404 or 400 | No: fix the model ID or URL |
| Malformed request body | 400 | No: fix the request |
| Too many requests or tokens | 429 | Yes, with backoff |
| Server error or overload | 500, 503 or another 5xx | Yes, with backoff |
| No response in time | 408, 504 or a client-side timeout | Usually, with care |
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.
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.
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.
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
.envfile.
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-afterheader, 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.
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
- Check the provider's status page for an ongoing incident.
- Reproduce the failure with the smallest request you can: a short prompt, no tools, default settings.
- Compare your request with the provider's current quickstart for your SDK.
- Contact support with the request ID, the time and the error message, never your API key.
Related lessons
- Get Ready: Accounts, API Access and SafetyBuild Your First Claude AI Agent
- Get Ready: Google AI Studio and API KeyBuild Your First Google Gemini AI Agent
- Test, Improve and Finish Your Claude AgentBuild Your First Claude AI Agent
- Test, Improve and Finish Your Gemini AgentBuild Your First Google Gemini AI Agent
- Written by
- PromptFable Editorial
- Last updated 13 Nov 2026
- Review
- Not yet reviewed
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.