Spring › Spring-AI

Configuring Gemini safety settings and guardrails in Spring AI

Configure Gemini safety thresholds in Spring AI 2.0.1, catch NoSuchElementException on blocked responses, and return RFC 9457 ProblemDetail 400 errors.

Configuring Gemini safety settings and guardrails in Spring AI

Shipping a generative AI endpoint without content guardrails exposes your API to harmful outputs and jailbreak prompts. Worse, with Spring AI 2.0.1 defaults, a Gemini safety block triggers an unhandled NoSuchElementException and surfaces as a 500 Internal Server Error. In this post, I’ll wrap Gemini’s SafetySettings behind domain-level policies, intercept the conversion bug, and return a clean RFC 9457 ProblemDetail (400 Bad Request).

Tested with Spring Boot 4.1.1, Kotlin 2.3.21, Spring AI 2.0.1, and gemini-3.5-flash-lite.


Two stages of safety filtering

Google Gemini evaluates every request against four harm categories: hate speech, harassment, sexually explicit content, and dangerous content. Filtering happens at two distinct points in the request lifecycle:

sequenceDiagram
    autonumber
    actor User as Client
    participant API as SafetyController
    participant Service as SafeChatService
    participant Gemini as Google Gemini API
    User->>API: GET /api/safety/chat (message, level=STRICT)
    API->>Service: chat(message, STRICT)
    Service->>Gemini: prompt().options(safetySettings)

    alt Stage 1 - Prompt blocked
        Note over Gemini: Input violates safety policy
        Gemini-->>Service: promptFeedback.blockReason = SAFETY (0 candidates)
        Service->>Service: throw SafetyBlockedException(PROMPT)
    else Stage 2 - Response blocked
        Note over Gemini: Generated tokens cross threshold
        Gemini-->>Service: candidate.finishReason = SAFETY (empty content)
        Service->>Service: throw SafetyBlockedException(RESPONSE)
    else Completed normally
        Gemini-->>Service: candidate.finishReason = STOP
        Service-->>API: SafeChatResponse(content)
        API-->>User: 200 OK
    end

    opt Safety block triggered
        Service-->>API: throws SafetyBlockedException
        API-->>User: 400 Bad Request (RFC 9457 ProblemDetail)
    end
  1. Prompt evaluation (promptFeedback): If the user’s input itself crosses the configured threshold, Gemini refuses to start generation. The response comes back with zero candidates and a blockReason such as SAFETY.
  2. Response generation (candidates): If the prompt looks safe but the model’s output drifts over the threshold mid-stream, Gemini halts generation and marks finishReason: "SAFETY" with an empty content body.

Both paths look different at the wire level, so your service layer needs to handle each one explicitly.


Project setup and default thresholds

The full runnable module lives in spring-ai-examples (safety-settings).

build.gradle.kts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}

Default thresholds in application.yaml

I configure a baseline threshold of BLOCK_MEDIUM_AND_ABOVE across all four categories so no endpoint runs unguarded even if a caller forgets to pass per-request options:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server:
  port: 8087

spring:
  application:
    name: safety-settings
  ai:
    google:
      genai:
        api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY:demo-key}
        chat:
          model: gemini-3.5-flash-lite
          safety-settings:
            - category: HARM_CATEGORY_HATE_SPEECH
              threshold: BLOCK_MEDIUM_AND_ABOVE
            - category: HARM_CATEGORY_HARASSMENT
              threshold: BLOCK_MEDIUM_AND_ABOVE
            - category: HARM_CATEGORY_SEXUALLY_EXPLICIT
              threshold: BLOCK_MEDIUM_AND_ABOVE
            - category: HARM_CATEGORY_DANGEROUS_CONTENT
              threshold: BLOCK_MEDIUM_AND_ABOVE

Policy selection guide and limits

Rather than exposing Gemini’s raw HarmBlockThreshold enum across controllers, map thresholds to domain policy levels:

Policy levelGemini thresholdGood fit forFalse-positive risk
STRICTBLOCK_LOW_AND_ABOVEYouth, education, and public-facing Q&A botsHigh on edgy or technical phrasing
DEFAULTBLOCK_MEDIUM_AND_ABOVEGeneral customer support and internal assistantsBalanced
RELAXEDBLOCK_ONLY_HIGHSecurity incident analysis, medical triage, legal reviewLow, requires downstream review

When not to rely on SafetySettings alone: Gemini’s built-in classifier only covers general harm categories. It won’t block company-specific data leaks, PII exfiltration, unauthorized tool calls, or domain policy violations (such as giving financial or legal advice). Treat SafetySettings as your outer infrastructure floor, not your only guardrail.


Modeling safety policies in domain code

Encapsulating the threshold mapping in a small @Component keeps Google-specific types out of your web and domain layers and makes per-request overrides trivial to test.

service/SafetyLevel.kt and SafetyPolicy.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package io.github.cmsong111.safety_settings.service

import org.springframework.ai.google.genai.common.GoogleGenAiSafetySetting
import org.springframework.ai.google.genai.common.GoogleGenAiSafetySetting.HarmBlockThreshold
import org.springframework.ai.google.genai.common.GoogleGenAiSafetySetting.HarmCategory
import org.springframework.stereotype.Component

enum class SafetyLevel(val threshold: HarmBlockThreshold) {
    STRICT(HarmBlockThreshold.BLOCK_LOW_AND_ABOVE),
    DEFAULT(HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE),
    RELAXED(HarmBlockThreshold.BLOCK_ONLY_HIGH)
}

@Component
class SafetyPolicy {

    fun settingsFor(level: SafetyLevel): List<GoogleGenAiSafetySetting> {
        return CATEGORIES.map { category ->
            GoogleGenAiSafetySetting.Builder()
                .withCategory(category)
                .withThreshold(level.threshold)
                .build()
        }
    }

    companion object {
        val CATEGORIES = listOf(
            HarmCategory.HARM_CATEGORY_HATE_SPEECH,
            HarmCategory.HARM_CATEGORY_HARASSMENT,
            HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
            HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT
        )
    }
}

Catching the Spring AI 2.0.1 NoSuchElementException bug

When I first tested blocked prompts against GoogleGenAiChatModel in Spring AI 2.0.1, I expected a clean ChatResponse with finishReason = "SAFETY". Instead, the server crashed with a 500 error.

Spring AI 2.0.1 NoSuchElementException pitfall: When Gemini blocks a response with finishReason: "SAFETY", the returned candidate has an empty or null content part. While converting the SDK response into an AssistantMessage, GoogleGenAiChatModel calls .get() on an empty Optional, throwing java.util.NoSuchElementException: No value present.

If you leave that exception unhandled, your API reports a server outage (500) whenever a user triggers a safety block. Monitoring alerts fire, retry clients hammer your endpoint, and callers can’t tell a policy rejection from a backend crash.

service/SafeChatService.kt

In SafeChatService, I inspect the exception cause chain for NoSuchElementException, translate it into SafetyBlockedException(BlockStage.RESPONSE, "SAFETY"), and check both null results (prompt blocks) and blocking finish reasons explicitly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package io.github.cmsong111.safety_settings.service

import io.github.cmsong111.safety_settings.dto.SafeChatResponse
import io.github.cmsong111.safety_settings.exception.BlockStage
import io.github.cmsong111.safety_settings.exception.SafetyBlockedException
import org.slf4j.LoggerFactory
import org.springframework.ai.chat.client.ChatClient
import org.springframework.ai.google.genai.GoogleGenAiChatOptions
import org.springframework.stereotype.Service

@Service
class SafeChatService(
    private val chatClient: ChatClient,
    private val safetyPolicy: SafetyPolicy
) {

    private val log = LoggerFactory.getLogger(javaClass)

    fun chat(message: String, level: SafetyLevel): SafeChatResponse {
        val chatResponse = try {
            chatClient.prompt()
                .user(message)
                .options(
                    GoogleGenAiChatOptions.builder()
                        .safetySettings(safetyPolicy.settingsFor(level))
                )
                .call()
                .chatResponse()
        } catch (e: RuntimeException) {
            // Spring AI 2.0.1 throws NoSuchElementException (Optional.get) when mapping
            // a SAFETY-blocked candidate with empty content. Treat it as a response block.
            if (e.hasCause<NoSuchElementException>()) {
                throw SafetyBlockedException(BlockStage.RESPONSE, "SAFETY")
            }
            throw e
        }

        // Stage 1: prompt rejected before any candidate was generated
        val generation = chatResponse?.result
            ?: throw SafetyBlockedException(BlockStage.PROMPT, "PROMPT_BLOCKED")

        // Stage 2: generation halted mid-response due to safety policy
        val finishReason = generation.metadata.finishReason ?: "UNKNOWN"
        log.info("Gemini finishReason={}, safetyLevel={}", finishReason, level)

        if (finishReason.uppercase() in BLOCKING_FINISH_REASONS) {
            throw SafetyBlockedException(BlockStage.RESPONSE, finishReason)
        }

        return SafeChatResponse(
            content = generation.output.text.orEmpty(),
            finishReason = finishReason,
            safetyLevel = level
        )
    }

    private inline fun <reified T : Throwable> Throwable.hasCause(): Boolean =
        generateSequence(this) { it.cause }.any { it is T }

    companion object {
        val BLOCKING_FINISH_REASONS = setOf("SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII")
    }
}

Converting blocks to RFC 9457 ProblemDetail (400 Bad Request)

A safety rejection is a client policy violation, not a server fault. Mapping SafetyBlockedException to 400 Bad Request with Spring’s built-in ProblemDetail gives clients structured fields (stage, reason) without leaking raw stack traces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package io.github.cmsong111.safety_settings.exception

import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

@RestControllerAdvice
class SafetyExceptionHandler {

    private val log = LoggerFactory.getLogger(javaClass)

    @ExceptionHandler(SafetyBlockedException::class)
    fun handleSafetyBlocked(e: SafetyBlockedException): ProblemDetail {
        log.warn("Safety guardrail triggered: stage={}, reason={}", e.stage, e.reason)

        return ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST,
            "This request cannot be processed under our safety guidelines."
        ).apply {
            title = "Request blocked by safety guardrail"
            setProperty("stage", e.stage.name)
            setProperty("reason", e.reason)
        }
    }
}

RFC 9457 ProblemDetail 400 response returned on a safety block Figure 1. Standard RFC 9457 ProblemDetail 400 response returned when Gemini blocks a harmful prompt.


Inspecting per-category safety ratings via the SDK client

Spring AI’s ChatResponse metadata only exposes the finishReason string. It drops the per-category probability breakdown (NEGLIGIBLE, LOW, MEDIUM, HIGH) from safetyRatings.

When you need detailed scores for an admin audit dashboard or threshold tuning, inject the Google GenAI SDK Client bean that Spring AI auto-configures and call generateContent directly:

service/SafetyInspectionService.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Service
class SafetyInspectionService(
    private val genAiClient: Client,
    private val safetyPolicy: SafetyPolicy,
    @Value("\${spring.ai.google.genai.chat.model}") private val model: String
) {

    fun inspect(message: String, level: SafetyLevel): SafetyInspection {
        val config = GenerateContentConfig.builder()
            .safetySettings(
                safetyPolicy.settingsFor(level).map {
                    SafetySetting.builder()
                        .category(it.category.name)
                        .threshold(it.threshold.name)
                        .build()
                }
            )
            .build()

        val response = genAiClient.models.generateContent(model, message, config)

        val promptFeedback = response.promptFeedback().orElse(null)
        val candidate = response.candidates().orElse(emptyList()).firstOrNull()

        return SafetyInspection(
            promptBlockReason = promptFeedback?.blockReason()?.orElse(null)?.toString(),
            finishReason = candidate?.finishReason()?.orElse(null)?.toString(),
            promptRatings = promptFeedback?.safetyRatings()?.orElse(emptyList()).orEmpty().map { it.toView() },
            responseRatings = candidate?.safetyRatings()?.orElse(emptyList()).orEmpty().map { it.toView() },
            text = candidate?.content()?.orElse(null)?.text()
        )
    }
}

Per-category safetyRatings inspection output from the Google GenAI SDK Figure 2. Per-category harm probability ratings retrieved directly through the auto-configured Google GenAI SDK Client.


Verification and production checklist

I verified normal completions, SAFETY finish reasons, empty candidates, and the NoSuchElementException path using a FakeChatModel in unit tests alongside a live Gemini integration test:

1
./gradlew :safety-settings:test

Console output showing safety-settings unit and integration tests passing Figure 3. Passing unit, MockMvc controller, and live Gemini integration tests for the safety-settings module.

You can also test the HTTP endpoints directly with curl:

1
2
3
4
5
6
# 1. Normal request under STRICT policy (200 OK)
curl -G "http://localhost:8087/api/safety/chat" \
  --data-urlencode "message=Explain your refund policy" -d "level=STRICT"

# 2. Inspect configured thresholds for a policy level
curl "http://localhost:8087/api/safety/policy?level=RELAXED"

Production checklist

  • Set global defaults in application.yaml: Ensure every ChatClient call inherits BLOCK_MEDIUM_AND_ABOVE even without per-request overrides.
  • Catch NoSuchElementException in your chat wrapper: Until Spring AI handles empty blocked candidates cleanly, translate it to a domain block exception so safety rejections don’t trigger 500 alerts.
  • Return 400 Bad Request with ProblemDetail: Include stage and reason properties so clients stop retrying blocked prompts and can display clear user feedback.
  • Log ratings without storing raw toxic payloads: If you audit blocks using SafetyInspectionService, store the category ratings and request ID rather than raw unredacted prompts.
  • Layer tool guardrails next: Once text generation is guarded, apply execution limits and structured error handling when exposing backend functions—see building Gemini tool calling with @Tool in Spring AI 2.0.1.
This post is licensed under CC BY 4.0 by the author.