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.
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
NoSuchElementExceptionand surfaces as a500 Internal Server Error. In this post, I’ll wrap Gemini’sSafetySettingsbehind domain-level policies, intercept the conversion bug, and return a clean RFC 9457ProblemDetail(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
- 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 ablockReasonsuch asSAFETY. - Response generation (
candidates): If the prompt looks safe but the model’s output drifts over the threshold mid-stream, Gemini halts generation and marksfinishReason: "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 level | Gemini threshold | Good fit for | False-positive risk |
|---|---|---|---|
STRICT | BLOCK_LOW_AND_ABOVE | Youth, education, and public-facing Q&A bots | High on edgy or technical phrasing |
DEFAULT | BLOCK_MEDIUM_AND_ABOVE | General customer support and internal assistants | Balanced |
RELAXED | BLOCK_ONLY_HIGH | Security incident analysis, medical triage, legal review | Low, 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
NoSuchElementExceptionpitfall: When Gemini blocks a response withfinishReason: "SAFETY", the returned candidate has an empty ornullcontent part. While converting the SDK response into anAssistantMessage,GoogleGenAiChatModelcalls.get()on an emptyOptional, throwingjava.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)
}
}
}
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()
)
}
}
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
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 everyChatClientcall inheritsBLOCK_MEDIUM_AND_ABOVEeven without per-request overrides. - Catch
NoSuchElementExceptionin your chat wrapper: Until Spring AI handles empty blocked candidates cleanly, translate it to a domain block exception so safety rejections don’t trigger500alerts. - Return
400 Bad RequestwithProblemDetail: Includestageandreasonproperties 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
@Toolin Spring AI 2.0.1.