Skip to content

fix: guard choices[0] and message=None before content access#5

Open
qizwiz wants to merge 1 commit into
Annyfee:mainfrom
qizwiz:fix/guard-unguarded-llm-choices
Open

fix: guard choices[0] and message=None before content access#5
qizwiz wants to merge 1 commit into
Annyfee:mainfrom
qizwiz:fix/guard-unguarded-llm-choices

Conversation

@qizwiz

@qizwiz qizwiz commented May 17, 2026

Copy link
Copy Markdown

Summary

OpenAI-compatible APIs can return empty choices on error or rate-limiting, causing IndexError at choices[0]. Gemini additionally returns choices[0].message = None on PROHIBITED_CONTENT safety filtering (HTTP 200 — no exception raised), causing AttributeError at .content.

This PR adds:

if not response.choices or response.choices[0].message is None:
    raise ValueError("LLM returned empty or filtered response")

before every bare choices[0].message.content access (8 sites, 5 files).

Files changed

  • m02_llm_fundamentals/s01_basic_llm_invocation.py
  • m02_llm_fundamentals/s02_conversational_agent.py
  • m02_llm_fundamentals/s03_llm_temperature.py (two different response vars)
  • m03_function_calling_tools/s01_custom_function_calling.py
  • m03_function_calling_tools/s02_api_invocation.py

Static analysis via pact found all 8 sites; post-fix scan returns 0 violations.

OpenAI-compatible APIs can return empty choices on error or content
filtering; Gemini returns choices[0].message=None on PROHIBITED_CONTENT
(HTTP 200). Both cause unhandled exceptions at runtime.

Adds guard before every bare choices[0].message.content access (8 sites, 5 files).
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