Why Benign Technical Prompts Trigger finishReason: "SAFETY"
Even completely harmless engineering prompts can occasionally get blocked with finishReason: "SAFETY" in the Gemini API. This happens because Gemini evaluates both input prompts and generated candidate responses using automated safety classifiers that score the probability of harm across categories (DANGEROUS_CONTENT, HARASSMENT, HATE_SPEECH, SEXUALLY_EXPLICIT), rather than understanding benign engineering intent:
- Dual-use technical keywords: Words common in DevOps, security, and systems programming—such as kill process, exploit, payload, injection, brute-force, penetration, or Privilege Escalation—can push
HARM_CATEGORY_DANGEROUS_CONTENTinto aLOWorMEDIUMprobability bucket. - Strict default or inherited thresholds: If a threshold is set to
BLOCK_LOW_AND_ABOVEorBLOCK_MEDIUM_AND_ABOVE(or inherited from an older config/wrapper), even a moderate false-positive probability blocks the entire candidate response and strips its text. - Output-side triggers during streaming: Even when your prompt passes input checks, the model may start generating a code snippet, stack trace, or command example whose phrasing trips a response-level safety filter mid-generation, ending the candidate with
finishReason: "SAFETY". - Non-configurable core protections remain active: Alongside adjustable filters, Gemini enforces built-in protections against severe harms (such as child safety or severe cyberattacks/weapons) that cannot be overridden by threshold settings.
How to Inspect and Tune Safety Thresholds
- Inspect
safetyRatingsfirst: Whencandidate.finishReason === "SAFETY", logcandidate.safetyRatings(andresponse.promptFeedbackif blocked before generation) to see which exactcategoryandprobability(NEGLIGIBLE,LOW,MEDIUM,HIGH) triggered the block. - Relax only the noisy category: For technical and developer workflows, false positives most often hit
HARM_CATEGORY_DANGEROUS_CONTENT. Lower that threshold toBLOCK_ONLY_HIGH(orOFF/BLOCK_NONEwhere permitted by your policy and use case) while keeping stricter settings onHARASSMENT,HATE_SPEECH, andSEXUALLY_EXPLICIT. - Frame prompts with clear defensive/educational context: Adding system instructions such as “Provide defensive remediation and standard software engineering explanations” reduces the model’s tendency to generate risky-sounding phrasing that trips output filters.
- Handle
SAFETYgracefully in code: Always checkfinishReasonbefore readingresponse.text, because accessing.texton a safety-blocked response can return empty output or throw an error in SDK helpers.
Node.js Example Using /genai
import { GoogleGenAI, HarmCategory, HarmBlockThreshold } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
async function generateTechnicalAnswer(prompt) {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: prompt,
config: {
systemInstruction:
"You are a senior software engineer. Focus on defensive security, standard programming practices, and safe system administration.",
safetySettings: [
{
// Relax only Dangerous Content to reduce false positives on technical terms
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
},
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
],
},
});
// Check if the prompt itself was blocked before generation
if (response.promptFeedback?.blockReason) {
throw new Error(
`Prompt blocked (${response.promptFeedback.blockReason}):${JSON.stringify(
response.promptFeedback.safetyRatings
)}`
);
}
const candidate = response.candidates?.[0];
// Inspect finishReason and safetyRatings if the response was blocked
if (candidate?.finishReason === "SAFETY") {
console.warn("Blocked safety ratings:", candidate.safetyRatings);
throw new Error("Response blocked by Gemini safety filter.");
}
return response.text ?? "";
}
// Example: DevOps/security prompt with dual-use words like "kill" and "injection"
const answer = await generateTechnicalAnswer(
"How do I prevent SQL injection in Node.js and safely kill hung worker processes?"
);
console.log(answer);
Helpful Tips for Production Apps
- Check
OFFvs.BLOCK_NONEin your SDK version: Newer Gemini SDKs and models exposeHarmBlockThreshold.OFF(andBLOCK_NONEfor backward compatibility), while built-in core harm protections stay active regardless of threshold settings. - Test with real technical edge cases: Run your actual logs (Linux commands, regexes, SQL queries, incident postmortems) through a staging evaluation to find which specific category triggers false positives before relaxing thresholds globally.
- Avoid blind retries on
SAFETY: Retrying the exact same prompt usually hits the same classifier score—either rephrase the prompt context or show a clear message to the user.
You must log in or register to comment.
