GoogleAPICallError
google.api_core.exceptions.PermissionDenied: 7 PERMISSION_DENIED: Safety filter blocked the request
Stack trace
google.api_core.exceptions.PermissionDenied: 7 PERMISSION_DENIED: Safety filter blocked the request at google.cloud.aiplatform_v1.services.content_service.client.ContentServiceClient.generate_content at main.py line 42
Why it happens
Vertex AI includes a safety filter that blocks content generation requests containing disallowed or sensitive content based on Google's content policies. When the input prompt or requested output triggers this filter, the API returns a PermissionDenied error to prevent unsafe or policy-violating content.
Detection
Catch google.api_core.exceptions.PermissionDenied exceptions when calling generate_content and inspect the error message for 'Safety filter blocked' to identify blocked requests before crashing.
Causes & fixes
Input prompt contains disallowed or sensitive content triggering the safety filter
Review and sanitize the input prompt to remove or rephrase content that violates Google's content policies before calling generate_content.
Requested output content violates safety policies even if input is clean
Adjust prompt instructions to avoid generating disallowed content and use moderation tools to pre-check outputs.
Using an outdated or misconfigured client library version incompatible with current safety filter enforcement
Upgrade google-cloud-aiplatform to the latest stable version to ensure compatibility with safety filter behavior.
Code: broken vs fixed
from google.cloud import aiplatform
client = aiplatform.gapic.ContentServiceClient()
response = client.generate_content(
model="models/text-bison@001",
prompt="Generate content about illegal activities.", # This triggers safety filter
parent="projects/my-project/locations/us-central1"
)
print(response) import os
from google.cloud import aiplatform
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS') # Use env var for auth
client = aiplatform.gapic.ContentServiceClient()
safe_prompt = "Generate content about legal and safe activities."
response = client.generate_content(
model="models/text-bison@001",
prompt=safe_prompt, # Prompt sanitized to avoid safety filter
parent="projects/my-project/locations/us-central1"
)
print(response) Workaround
Catch the PermissionDenied exception, log the blocked prompt, and fallback to a simpler or pre-approved prompt to continue operation without crashing.
Prevention
Implement prompt validation and sanitization before calling generate_content, and monitor usage with moderation APIs to ensure compliance with safety policies.