fix(openai): guard against choices=None in OpenAI integration#6216
Open
cla7aye15I4nd wants to merge 2 commits intogetsentry:masterfrom
Open
fix(openai): guard against choices=None in OpenAI integration#6216cla7aye15I4nd wants to merge 2 commits intogetsentry:masterfrom
cla7aye15I4nd wants to merge 2 commits intogetsentry:masterfrom
Conversation
Some providers (e.g. OpenRouter) can return choices=None on upstream error responses. hasattr(response, 'choices') returns True even when the attribute is None, causing a TypeError when iterating. Add an explicit None check before iterating response.choices.
When a streaming chunk has choices=None, the existing hasattr check passes but the subsequent iteration raises TypeError. Inside capture_internal_exceptions() this is silently suppressed, causing the usage capture on the next line to be skipped — leaving token usage and response text missing from the Sentry span. Add explicit None checks in both the sync and async streaming iterators.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Some providers (e.g. OpenRouter) can return
choices=Noneon upstream error responses. The current code checkshasattr(response, "choices")before iterating, buthasattrreturnsTrueeven when the attribute value isNone, causing:This crash happens inside Sentry's patched
create()wrapper before the calling code ever receives the response, making it impossible to handle on the caller side without catching a bareTypeError.Fix
Add an explicit
response.choices is not Noneguard alongside the existinghasattrcheck at both affected locations.Reproduction
Use the OpenAI SDK client pointed at OpenRouter (
base_url="https://openrouter.ai/api/v1"). When an upstream provider fails, OpenRouter returns a response withchoices=null, which triggers this crash in Sentry's telemetry hook.