microsoft/semantic-kernel · error · KernelException

Prompt was blocked due to Gemini API safety reasons.

Error message

Prompt was blocked due to Gemini API safety reasons.

What it means

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.

Source

Thrown at dotnet/src/Connectors/Connectors.Google/Core/Gemini/Clients/GeminiChatCompletionClient.cs:809

            yield return DeserializeResponse<GeminiResponse>(json);
        }
    }

    private List<GeminiChatMessageContent> ProcessChatResponse(GeminiResponse geminiResponse)
    {
        ValidateGeminiResponse(geminiResponse);

        var chatMessageContents = this.GetChatMessageContentsFromResponse(geminiResponse);
        this.LogUsage(chatMessageContents);
        return chatMessageContents;
    }

    private static void ValidateGeminiResponse(GeminiResponse geminiResponse)
    {
        if (geminiResponse.PromptFeedback?.BlockReason is not null)
        {
            // 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
            throw new KernelException("Prompt was blocked due to Gemini API safety reasons.");
        }
    }

    private void LogUsage(List<GeminiChatMessageContent> chatMessageContents)
    {
        GeminiMetadata? metadata = chatMessageContents[0].Metadata;

        if (metadata is null || metadata.TotalTokenCount <= 0)
        {
            this.Logger.LogDebug("Token usage information unavailable.");
            return;
        }

        if (this.Logger.IsEnabled(LogLevel.Information))
        {
            this.Logger.LogInformation(
                "Prompt tokens: {PromptTokens}. Completion tokens: {CompletionTokens}. Total tokens: {TotalTokens}.",
                metadata.PromptTokenCount,

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Review the prompt content for material that may trigger safety filters and rephrase as needed.
  2. Catch KernelException and check the message for 'safety' to handle blocked prompts gracefully (e.g. return a fallback message to the user).
  3. If using Vertex AI, review and potentially adjust safety_settings in the GeminiPromptExecutionSettings to relax thresholds where appropriate.
  4. Avoid sending raw untrusted content to the model without preprocessing or content moderation.

Example fix

try
{
    var response = await client.GetChatMessageContentAsync(history, settings);
}
catch (KernelException ex) when (ex.Message.Contains("safety"))
{
    return "I cannot respond to that request due to safety guidelines.";
}
Defensive patterns

Strategy: try-catch

Validate before calling

null

Type guard

null

Try / catch

try
{
    var response = await client.GetChatMessageContentAsync(history, settings, ct);
}
catch (KernelException ex) when (ex.Message.Contains("safety"))
{
    logger.LogWarning("Gemini blocked prompt due to safety filters.");
    return new ChatMessageContent(AuthorRole.Assistant,
        "I cannot respond to this request due to content safety guidelines.");
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/248f4525b518358a. Report an issue: GitHub.