Skip to content

Fix NoSuchElementException for safety-blocked candidates in GoogleGenAiChatModel - #6757

Open
yyyCode wants to merge 1 commit into
spring-projects:mainfrom
yyyCode:fix-google-genai-safety-blocked-nsee
Open

Fix NoSuchElementException for safety-blocked candidates in GoogleGenAiChatModel#6757
yyyCode wants to merge 1 commit into
spring-projects:mainfrom
yyyCode:fix-google-genai-safety-blocked-nsee

Conversation

@yyyCode

@yyyCode yyyCode commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Summary

GoogleGenAiChatModel.responseCandidateToGeneration calls candidate.content().get() without checking whether content() is present. When a response candidate is blocked by safety filters, the candidate carries a finishReason (e.g. SAFETY) but no content — an empty Optional. In the non-function-call path this throws NoSuchElementException: No value present, failing the whole call() even though the API responded successfully.

This is the same class of bug reported in #6665 for modelVersion().get(), but on a different accessor that is not covered by #6681.

Changes

  • Replace the chained candidate.content().get().parts() with candidate.content().flatMap(Content::parts) in the non-function-call branch, so an absent content falls back to an empty parts list (which then yields a single empty generation via the existing fallback).
  • Add regression test testSafetyBlockedCandidateWithoutContent that feeds a candidate with finishReason=SAFETY and no content, asserting the call returns a valid ChatResponse instead of throwing.

Testing

Unit test added. Note: I was unable to run ./mvnw locally because the build enforces JDK 17.0.19+ (-XDaddTypeAnnotationsToSymbol) and my environment has 17.0.12. Please verify in CI.

Fixes #6665

…AiChatModel

Guard the unguarded Optional.get() call on candidate.content() in
responseCandidateToGeneration. When a response candidate is blocked by
safety filters, content() may be an empty Optional, causing a
NoSuchElementException in the non-function-call path. Replace the
chained .get().parts() with .flatMap(Content::parts) to handle the
absent case gracefully.

Adds a regression test simulating a safety-blocked candidate with
finishReason=SAFETY and no content field.

Fixes spring-projects#6665

Signed-off-by: yqz <2678785492@qq.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GoogleGenAiChatModel throws NoSuchElementException for models that omit modelVersion in GenerateContentResponse (e.g. Vertex Gemma MaaS)

2 participants