Skip to content

fix(tutorials): guard against empty choices and message=None in LLM responses#5

Open
qizwiz wants to merge 1 commit into
rokbenko:mainfrom
qizwiz:fix/guard-llm-response-access
Open

fix(tutorials): guard against empty choices and message=None in LLM responses#5
qizwiz wants to merge 1 commit into
rokbenko:mainfrom
qizwiz:fix/guard-llm-response-access

Conversation

@qizwiz

@qizwiz qizwiz commented May 18, 2026

Copy link
Copy Markdown

What

Add explicit guards before accessing choices[0].message and choices[0].logprobs in two tutorial files.

Why

The OpenAI Chat Completions API can return two different empty-response shapes, neither of which is currently guarded:

  1. choices = [] — on network errors, content-policy rejections, or provider-side filtering
  2. choices[0].message = None — Gemini 2.5 Flash (via the OpenAI-compatible endpoint) returns HTTP 200 with finish_reason: PROHIBITED_CONTENT and message=None rather than raising an exception

Both currently crash with IndexError or AttributeError. The guard raises a clear ValueError instead.

Files changed

File Fix
openai-tutorials/1-Get_response_in_JSON_format/return_json.py Guard choices + message before first access (covers the second access on line 27 too)
openai-tutorials/8-LLMs_explained/llms_explained.py Guard choices + logprobs before accessing .logprobs.content

Corpus context

Detected by pact (llm_response_unguarded mode), a Z3-verified static analyzer for LLM crash vectors. These two patterns account for the most common unhandled LLM failures across 13.5k violations in 761 repos.

…esponses

OpenAI's Chat Completions API can return choices=[] (e.g. on network/content
errors) or choices[0].message=None (e.g. Gemini PROHIBITED_CONTENT via the
OpenAI-compatible endpoint). Both paths currently crash with IndexError or
AttributeError; explicit guards raise clear ValueError instead.

The logprobs tutorial also guards against logprobs being absent when the
API is called from a provider that doesn't support it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant