Skip to content

Commit 640c48d

Browse files
fix(openai): Guard against choices=None (#6216)
Avoid an unhandled `TypeError` exception caused by trying to iterate of `None` choices in the model response. Some providers (e.g. OpenRouter) can return `choices=None` on upstream error responses.
1 parent 575edf9 commit 640c48d

1 file changed

Lines changed: 4 additions & 4 deletions

File tree

sentry_sdk/integrations/openai.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ def _calculate_completions_token_usage(
208208
if streaming_message_responses is not None:
209209
for message in streaming_message_responses:
210210
output_tokens += count_tokens(message)
211-
elif hasattr(response, "choices"):
211+
elif hasattr(response, "choices") and response.choices is not None:
212212
for choice in response.choices:
213213
if hasattr(choice, "message") and hasattr(choice.message, "content"):
214214
output_tokens += count_tokens(choice.message.content)
@@ -583,7 +583,7 @@ def _set_common_output_data(
583583
set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_MODEL, response.model)
584584

585585
# Chat Completions API
586-
if hasattr(response, "choices"):
586+
if hasattr(response, "choices") and response.choices is not None:
587587
if should_send_default_pii() and integration.include_prompts:
588588
response_text = [
589589
choice.message.model_dump()
@@ -839,7 +839,7 @@ def _wrap_synchronous_completions_chunk_iterator(
839839
span.set_data(SPANDATA.GEN_AI_RESPONSE_MODEL, x.model)
840840

841841
with capture_internal_exceptions():
842-
if hasattr(x, "choices"):
842+
if hasattr(x, "choices") and x.choices is not None:
843843
choice_index = 0
844844
for choice in x.choices:
845845
if hasattr(choice, "delta") and hasattr(choice.delta, "content"):
@@ -901,7 +901,7 @@ async def _wrap_asynchronous_completions_chunk_iterator(
901901
span.set_data(SPANDATA.GEN_AI_RESPONSE_MODEL, x.model)
902902

903903
with capture_internal_exceptions():
904-
if hasattr(x, "choices"):
904+
if hasattr(x, "choices") and x.choices is not None:
905905
choice_index = 0
906906
for choice in x.choices:
907907
if hasattr(choice, "delta") and hasattr(choice.delta, "content"):

0 commit comments

Comments
 (0)