Nothing derails a productive coding session quite like running into an error you've never seen before — especially when the error message itself isn't particularly helpful:
FAILED_PRECONDITION: Request contains an invalid argument.
Or slightly more descriptive:
FAILED_PRECONDITION: Billing account not found. Please set up a billing account.
The frustrating thing about FAILED_PRECONDITION is that the same error code can mean completely different things depending on the situation. Billing issues, API activation problems, context cache expiry, model access restrictions — they all surface as FAILED_PRECONDITION. The official docs don't give you a clean breakdown, so I've put together this case-by-case guide based on what I've actually encountered.
What FAILED_PRECONDITION Means — And What It Doesn't
First, let's separate this from errors that look similar:
PERMISSION_DENIED(403): Your API key or credentials are invalid, or you lack the required permissionsRESOURCE_EXHAUSTED(429): You've hit a quota or rate limitNOT_FOUND(404): The model or resource doesn't existFAILED_PRECONDITION(400): Your credentials are fine, but the system isn't in the right state to execute this request
Think of FAILED_PRECONDITION as "you're allowed to do this, but some prerequisite isn't met." The HTTP status is 400, and it's distinct from INVALID_ARGUMENT (which means the request itself is malformed).
There are four main causes. Let me walk through each one.
Case 1: Billing Account Not Configured
Even the Gemini API free tier can require a billing account to be linked to your Google Cloud project in certain situations. This is especially common when:
- You created a new Google Cloud project and used it directly without setting up billing
- Your free trial period ended
- You're using an AI Studio API key, but the associated GCP project has no billing account
How to Diagnose
import google.generativeai as genai
try:
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemini-2.5-pro")
response = model.generate_content("Hello")
print(response.text)
except Exception as e:
print(f"Error type: {type(e).__name__}")
print(f"Error message: {str(e)}")
# If "billing" appears in the message, you're in Case 1
if "billing" in str(e).lower():
print("→ This is a billing configuration issue")How to Fix
- Go to Google Cloud Console
- Navigate to Billing → Link a billing account
- If you don't have a billing account, create one (credit card required)
If you're using an AI Studio API key, check billing via Google AI Studio → Get API key → the project settings for the relevant key.
Case 2: Gemini API Not Enabled
When using a Google Cloud project directly, each API must be explicitly enabled. Even with billing set up, the Generative Language API might not be turned on yet.
# Check which APIs are currently enabled
gcloud services list --enabled | grep generativelanguage
# Enable the Generative Language API if it's missing
gcloud services enable generativelanguage.googleapis.comIf you're using Vertex AI, you'll need to enable that too:
# Enable Vertex AI API
gcloud services enable aiplatform.googleapis.comA Vertex AI-specific variant of this error reads:
FAILED_PRECONDITION: The Vertex AI API is not enabled for this project.
That one's almost always Case 2.
Case 3: Context Caching Precondition Violations
When you're using Gemini's context caching feature, FAILED_PRECONDITION can appear for two distinct reasons.
Minimum token count not met
Context caching requires at least 32,768 tokens of content. Trying to cache anything shorter triggers this error.
import google.generativeai as genai
# ❌ Too short for context caching
short_system_instruction = "You are a helpful assistant." # Only a few tokens
try:
cache = genai.caching.CachedContent.create(
model="gemini-2.5-pro",
system_instruction=short_system_instruction, # Below 32,768 token minimum
)
except Exception as e:
print(e) # FAILED_PRECONDITION: ...minimum token count...
# ✅ Context caching is designed for large documents: PDFs, long transcripts, codebases
# Use it when you have substantial content to cache, not short system promptsCached content has expired
If you see FAILED_PRECONDITION: The cached content has expired, the cache you're referencing has passed its TTL and been deleted.
import google.generativeai as genai
def get_or_recreate_cache(cache_name: str, model: str, content, ttl_seconds: int = 3600):
"""
Utility that transparently handles expired caches.
Tries to use an existing cache, and recreates it if it has expired.
"""
try:
model_with_cache = genai.GenerativeModel.from_cached_content(
cached_content=cache_name
)
response = model_with_cache.generate_content("Your question here")
return response
except Exception as e:
if "expired" in str(e).lower() or "FAILED_PRECONDITION" in str(e):
print("Cache expired. Recreating...")
new_cache = genai.caching.CachedContent.create(
model=model,
contents=content,
ttl={"seconds": ttl_seconds}
)
model_with_cache = genai.GenerativeModel.from_cached_content(
cached_content=new_cache
)
return model_with_cache.generate_content("Your question here")
raise # Re-raise other errors
# Usage
result = get_or_recreate_cache(
cache_name="my-cache-name",
model="gemini-2.5-pro",
content=my_large_document,
ttl_seconds=7200 # 2 hours instead of the default 1 hour
)Default TTL is one hour. For long-running batch jobs that reference a cache across multiple hours, either extend the TTL explicitly or build cache recreation logic into your pipeline.
Case 4: Preview Model Access Restrictions
Some Gemini 3.x models are in preview and only accessible to specific accounts or projects. Attempting to access them with a standard API key may return FAILED_PRECONDITION:
FAILED_PRECONDITION: This model is not available for general access.
Please contact Google for access.
To investigate:
- Try the same model in Google AI Studio — if it works there, the issue is that your API key's associated project doesn't have access
- If AI Studio works but the API doesn't, check that both are using the same Google Cloud project
- For enterprise access to preview models, Vertex AI on an enterprise contract often unlocks additional models
Error Handling Best Practices
FAILED_PRECONDITION from configuration issues (billing, API activation, model access) cannot be resolved by retrying. Cache expiry is the one case where retry logic with recreation makes sense.
import google.generativeai as genai
from google.api_core import exceptions as google_exceptions
import time
def call_gemini_with_precondition_handling(prompt: str) -> str:
"""
Wraps Gemini API calls with appropriate FAILED_PRECONDITION handling.
Strategy:
- Billing / API enablement errors: fail immediately with a clear message
- Cache expiry: signal to caller that cache needs recreation
- Unknown precondition failures: log and re-raise
"""
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemini-2.5-pro")
try:
response = model.generate_content(prompt)
return response.text
except google_exceptions.FailedPrecondition as e:
error_msg = str(e)
# Billing or API activation — no point retrying
if any(keyword in error_msg.lower() for keyword in
["billing", "not enabled", "not available for general access"]):
raise RuntimeError(
f"Configuration error (non-retriable): {error_msg}\n"
"Check billing and API activation in Google Cloud Console."
) from e
# Context cache expired — caller should recreate the cache
if "expired" in error_msg.lower():
raise RuntimeError(
"Context cache has expired. Please recreate the cache before retrying."
) from e
# Unknown FAILED_PRECONDITION — re-raise for investigation
raiseQuick Diagnosis Checklist
When FAILED_PRECONDITION appears, scan the error message for these keywords to narrow down the cause fast:
If the message contains billing → Case 1 (billing account setup)
If the message contains not enabled → Case 2 (API not activated)
If the message contains expired → Case 3 (context cache TTL exceeded)
If the message contains not available or general access → Case 4 (model access restriction)
If none of these match, cross-reference with the Gemini API error reverse lookup reference to narrow down from the error code. For errors that look like authentication issues, the Gemini API authentication error guide covers related territory.
What to Do Right Now
The core takeaway: FAILED_PRECONDITION is a state problem, not a transient one. Retrying without changing anything won't help.
If you're hitting this error today, read the error message carefully — it almost always contains a keyword that points to the specific cause. Once you've identified which of the four cases you're in, the fix is usually straightforward.
If you're building a production system that uses context caching, I'd strongly recommend implementing cache recreation logic from the start. Cache expiry during a long batch run is easy to miss and disruptive to debug after the fact.