fix(langchain): handle unrecognized FinishReason enum gracefully #33448
+638
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR fixes an unhandled exception that occurs when the
Gemini API
returns aFinishReason
enum value that is not recognized by the current version of thegoogle.generativeai
library.Previously, this caused the
ChatGoogleGenerativeAI.with_structured_output()
method to raise:This fix adds a safeguard that gracefully handles unknown enum values by defaulting to a string representation, rather than raising an exception. As a result, structured output parsing remains stable even when the Gemini API introduces new or experimental FinishReason codes.
A dedicated unit test has been added for
ChatGoogleGemini
to ensure graceful handling of unrecognized FinishReason enum values. The test uses a fully mockedGemini API
response to simulate an unknown finish reason (12) and verifies that the model safely returns"UNKNOWN(12)"
without raising an exception.Rationale
The Gemini API recently started returning a new
FinishReason
code (12) that is not yet covered in the existing enum definitions. This change prevents downstream crashes by:How to Reproduce (Before Fix)
Result (Before):
Result (After):
Changes
1. Added defensive handling for unknown
FinishReason
values ingoogle_gemini.py
.2. Added
fix-handle-unknown-finish-reason.rst
changelog entry.Tested with
langchain-core==0.3.79
langchain-google-genai==2.0.10
Python 3.13.0 (Windows 11)
Notes
Gemini API
updates.libs/core
(test_runnable_lambda_context_config
).This is a known intermittent issue with the FakeTracer callback when run under pytest-xdist (see cli: fix typo in doc-string #31284 and fix: azure OpenAIrResponses API fallback for unsupported endpoints #32077), and is not related to this change. All community and partner tests pass successfully.
Fixes:
Unrecognized FinishReason enum value: 12 from Gemini API causes crash in ChatGoogleGenerativeAI #33444