-
-
Notifications
You must be signed in to change notification settings - Fork 1k
fix: Handle Gemini chunk.text ValueError when finish_reason=1 #1809
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
11ed2ea
fix: Handle Gemini chunk.text ValueError when finish_reason=1
jxnl 93615b8
Merge branch 'main' into fix-gemini-chunk-text-error
jxnl 21b4030
Merge branch 'main' into fix-gemini-chunk-text-error
jxnl 11558e3
Delete tests/test_gemini_chunk_error.py
jxnl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| """Tests for Gemini chunk.text error handling in partial.py""" | ||
|
|
||
| import pytest | ||
| from instructor.dsl.partial import PartialBase | ||
| from instructor.mode import Mode | ||
|
|
||
|
|
||
| class MockChunk: | ||
| """Mock chunk that raises ValueError when accessing .text""" | ||
|
|
||
| @property | ||
| def text(self): | ||
| raise ValueError( | ||
| "Invalid operation: The `response.text` quick accessor requires the response to contain a valid `Part`, but none were returned. The candidate's [finish_reason](https://ai.google.dev/api/generate-content#finishreason) is 1." | ||
| ) | ||
|
|
||
|
|
||
| class MockValidChunk: | ||
| """Mock chunk with valid text""" | ||
|
|
||
| @property | ||
| def text(self): | ||
| return '{"key": "value"}' | ||
|
|
||
|
|
||
| def test_extract_json_handles_gemini_json_invalid_part(): | ||
| """Test that extract_json gracefully handles chunks with invalid Parts for GEMINI_JSON mode""" | ||
| # Create mock chunks - one invalid, one valid | ||
| invalid_chunk = MockChunk() | ||
| valid_chunk = MockValidChunk() | ||
| completion = [invalid_chunk, valid_chunk] | ||
|
|
||
| # Extract JSON chunks | ||
| json_chunks = list(PartialBase.extract_json(completion, Mode.GEMINI_JSON)) | ||
|
|
||
| # Should only get the valid chunk's text, invalid chunk should be skipped | ||
| assert len(json_chunks) == 1 | ||
| assert json_chunks[0] == '{"key": "value"}' | ||
|
|
||
|
|
||
| def test_extract_json_handles_genai_structured_outputs_invalid_part(): | ||
| """Test that extract_json gracefully handles chunks with invalid Parts for GENAI_STRUCTURED_OUTPUTS mode""" | ||
| # Create mock chunks - one invalid, one valid | ||
| invalid_chunk = MockChunk() | ||
| valid_chunk = MockValidChunk() | ||
| completion = [invalid_chunk, valid_chunk] | ||
|
|
||
| # Extract JSON chunks | ||
| json_chunks = list( | ||
| PartialBase.extract_json(completion, Mode.GENAI_STRUCTURED_OUTPUTS) | ||
| ) | ||
|
|
||
| # Should only get the valid chunk's text, invalid chunk should be skipped | ||
| assert len(json_chunks) == 1 | ||
| assert json_chunks[0] == '{"key": "value"}' | ||
|
|
||
|
|
||
| def test_extract_json_handles_all_invalid_chunks(): | ||
| """Test that extract_json handles when all chunks have invalid Parts""" | ||
| # Create only invalid chunks | ||
| invalid_chunk1 = MockChunk() | ||
| invalid_chunk2 = MockChunk() | ||
| completion = [invalid_chunk1, invalid_chunk2] | ||
|
|
||
| # Extract JSON chunks | ||
| json_chunks = list(PartialBase.extract_json(completion, Mode.GEMINI_JSON)) | ||
|
|
||
| # Should get empty list when all chunks are invalid | ||
| assert len(json_chunks) == 0 | ||
|
|
||
|
|
||
| def test_extract_json_reraises_other_valueerrors(): | ||
| """Test that extract_json re-raises ValueErrors that aren't about invalid Parts""" | ||
|
|
||
| class MockChunkOtherError: | ||
| @property | ||
| def text(self): | ||
| raise ValueError("Some other error message") | ||
|
|
||
| other_error_chunk = MockChunkOtherError() | ||
| completion = [other_error_chunk] | ||
|
|
||
| # Should re-raise the ValueError since it's not about invalid Parts | ||
| with pytest.raises(ValueError, match="Some other error message"): | ||
| list(PartialBase.extract_json(completion, Mode.GEMINI_JSON)) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_extract_json_async_handles_gemini_json_invalid_part(): | ||
| """Test that extract_json_async gracefully handles chunks with invalid Parts for GEMINI_JSON mode""" | ||
|
|
||
| async def async_completion(): | ||
| yield MockChunk() # Invalid chunk | ||
| yield MockValidChunk() # Valid chunk | ||
|
|
||
| # Extract JSON chunks | ||
| json_chunks = [] | ||
| async for chunk in PartialBase.extract_json_async( | ||
| async_completion(), Mode.GEMINI_JSON | ||
| ): | ||
| json_chunks.append(chunk) | ||
|
|
||
| # Should only get the valid chunk's text, invalid chunk should be skipped | ||
| assert len(json_chunks) == 1 | ||
| assert json_chunks[0] == '{"key": "value"}' | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_extract_json_async_handles_genai_structured_outputs_invalid_part(): | ||
| """Test that extract_json_async gracefully handles chunks with invalid Parts for GENAI_STRUCTURED_OUTPUTS mode""" | ||
|
|
||
| async def async_completion(): | ||
| yield MockChunk() # Invalid chunk | ||
| yield MockValidChunk() # Valid chunk | ||
|
|
||
| # Extract JSON chunks | ||
| json_chunks = [] | ||
| async for chunk in PartialBase.extract_json_async( | ||
| async_completion(), Mode.GENAI_STRUCTURED_OUTPUTS | ||
| ): | ||
| json_chunks.append(chunk) | ||
|
|
||
| # Should only get the valid chunk's text, invalid chunk should be skipped | ||
| assert len(json_chunks) == 1 | ||
| assert json_chunks[0] == '{"key": "value"}' |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The try/except block wrapping 'yield chunk.text' is repeated for both GENAI_STRUCTURED_OUTPUTS and GEMINI_JSON (in sync and async functions). Consider extracting this logic into a helper to enforce DRY and simplify maintenance.