Why do Gemini API calls fail with finishReason SAFETY on benign technical prompts and how do you tune thresholds? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

Why do Gemini API calls fail with finishReason SAFETY on benign technical prompts and how do you tune thresholds?

message-square
0

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_CONTENT into a LOW or MEDIUM probability bucket.
  • Strict default or inherited thresholds: If a threshold is set to BLOCK_LOW_AND_ABOVE or BLOCK_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

  1. Inspect safetyRatings first: When candidate.finishReason === "SAFETY", log candidate.safetyRatings (and response.promptFeedback if blocked before generation) to see which exact category and probability (NEGLIGIBLE, LOW, MEDIUM, HIGH) triggered the block.
  2. Relax only the noisy category: For technical and developer workflows, false positives most often hit HARM_CATEGORY_DANGEROUS_CONTENT. Lower that threshold to BLOCK_ONLY_HIGH (or OFF / BLOCK_NONE where permitted by your policy and use case) while keeping stricter settings on HARASSMENT, HATE_SPEECH, and SEXUALLY_EXPLICIT.
  3. 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.
  4. Handle SAFETY gracefully in code: Always check finishReason before reading response.text, because accessing .text on a safety-blocked response can return empty output or throw an error in SDK helpers.

Node.js Example Using @google/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 OFF vs. BLOCK_NONE in your SDK version: Newer Gemini SDKs and models expose HarmBlockThreshold.OFF (and BLOCK_NONE for 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.