{"record":{"id":"248f4525b518358a","repo":"microsoft/semantic-kernel","slug":"prompt-was-blocked-due-to-gemini-api-safety-reason","errorCode":null,"errorMessage":"Prompt was blocked due to Gemini API safety reasons.","messagePattern":"Prompt was blocked due to Gemini API safety reasons\\.","errorType":"exception","errorClass":"KernelException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Connectors/Connectors.Google/Core/Gemini/Clients/GeminiChatCompletionClient.cs","lineNumber":809,"sourceCode":"            yield return DeserializeResponse<GeminiResponse>(json);\n        }\n    }\n\n    private List<GeminiChatMessageContent> ProcessChatResponse(GeminiResponse geminiResponse)\n    {\n        ValidateGeminiResponse(geminiResponse);\n\n        var chatMessageContents = this.GetChatMessageContentsFromResponse(geminiResponse);\n        this.LogUsage(chatMessageContents);\n        return chatMessageContents;\n    }\n\n    private static void ValidateGeminiResponse(GeminiResponse geminiResponse)\n    {\n        if (geminiResponse.PromptFeedback?.BlockReason is not null)\n        {\n            // TODO: Currently SK doesn't support prompt feedback/finish status, so we just throw an exception. I told SK team that we need to support it: https://github.com/microsoft/semantic-kernel/issues/4621\n            throw new KernelException(\"Prompt was blocked due to Gemini API safety reasons.\");\n        }\n    }\n\n    private void LogUsage(List<GeminiChatMessageContent> chatMessageContents)\n    {\n        GeminiMetadata? metadata = chatMessageContents[0].Metadata;\n\n        if (metadata is null || metadata.TotalTokenCount <= 0)\n        {\n            this.Logger.LogDebug(\"Token usage information unavailable.\");\n            return;\n        }\n\n        if (this.Logger.IsEnabled(LogLevel.Information))\n        {\n            this.Logger.LogInformation(\n                \"Prompt tokens: {PromptTokens}. Completion tokens: {CompletionTokens}. Total tokens: {TotalTokens}.\",\n                metadata.PromptTokenCount,","sourceCodeStart":791,"sourceCodeEnd":827,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Clients/GeminiChatCompletionClient.cs#L791-L827","documentation":"Thrown by GeminiChatCompletionClient.ValidateGeminiResponse when the GeminiResponse.PromptFeedback.BlockReason is not null. This means the Gemini API rejected the prompt before generating any content due to a safety filter. The exception carries no retry guidance; the prompt itself is blocked.","triggerScenarios":"Any Gemini chat completion or streaming call where the response includes a non-null PromptFeedback.BlockReason. This is a server-side safety decision, not a client error. The TODO comment in the source notes that SK does not yet expose prompt feedback as structured data — it only surfaces it as this exception.","commonSituations":"Prompt content triggers Gemini's safety categories (hate, harassment, sexually explicit, dangerous content). User-generated or RAG-sourced content that matches safety filter patterns. Regional or organizational safety policy settings on the Google Cloud project that are stricter than default.","solutions":["Review the prompt content for material that may trigger safety filters and rephrase as needed.","Catch KernelException and check the message for 'safety' to handle blocked prompts gracefully (e.g. return a fallback message to the user).","If using Vertex AI, review and potentially adjust safety_settings in the GeminiPromptExecutionSettings to relax thresholds where appropriate.","Avoid sending raw untrusted content to the model without preprocessing or content moderation."],"exampleFix":"try\n{\n    var response = await client.GetChatMessageContentAsync(history, settings);\n}\ncatch (KernelException ex) when (ex.Message.Contains(\"safety\"))\n{\n    return \"I cannot respond to that request due to safety guidelines.\";\n}","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"null","tryCatchPattern":"try\n{\n    var response = await client.GetChatMessageContentAsync(history, settings, ct);\n}\ncatch (KernelException ex) when (ex.Message.Contains(\"safety\"))\n{\n    logger.LogWarning(\"Gemini blocked prompt due to safety filters.\");\n    return new ChatMessageContent(AuthorRole.Assistant,\n        \"I cannot respond to this request due to content safety guidelines.\");\n}","preventionTips":["Sanitize or pre-moderate untrusted user content before sending it to Gemini.","When using Vertex AI, tune SafetySettings in GeminiPromptExecutionSettings to adjust category thresholds.","Implement graceful fallback responses for safety-blocked prompts.","Log blocked prompts to identify patterns in user input that trigger filters."],"tags":["google","gemini","safety","content-filter","kernel-exception"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}