"Gemini Safety Settings in Python: HarmCategory Example"
"A working gemini safety settings python example: set HarmCategory thresholds in the current google-genai SDK and check whether the model blocked your prompt."
One config object gives you per-category control over what Gemini blocks — strict for a kids' chatbot, relaxed for a creative writing tool, and a reliable way to detect when a block happened. Here's the copy-paste gemini safety settings python example for the current google-genai SDK (2.28.0), using the enum names the SDK actually exports today. Copy-paste Gemini safety settings example in Python import os from google import genai from google.genai import types # pip install "google-genai==2.28.0", then export GEMINI_API_KEY client = genai.Client(api_key=os.environ["GEMINI_API_KEY"]) safety_settings = [ { "category": types.HarmCategory.HARM_CATEGORY_HATE_SPEECH, "threshold": types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, }, { "category": types.HarmCategory.HARM_CATEGORY_HARASSMENT, "threshold": types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE, }, { "category": types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, "threshold": types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, }, { "category": types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, "threshold": types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, }, ] config = types.GenerateContentConfig(safety_settings=safety_settings) response = client.models.generate_content( model="gemini-2.5-flash", contents="Summarize the plot of Hamlet in two sentences.", config=config, ) # Detect a block instead of crashing on response.text if response.prompt_feedback and response.prompt_feedback.block_reason: print("Prompt blocked:", response.prompt_feedback.block_reason) else: cand = response.candidates[0] if response.candidates else None if cand and cand.finish_reason == types.FinishReason.SAFETY: print("Response blocked by safety filters.") else: print(response.text) The four harm categories above cover the standard set: harassment,…