fix: guard LLM response access in 39 cookbook examples - #138
Open
qizwiz wants to merge 1 commit into
Open
Conversation
response.choices[0].message.content is Optional[str] — returns None when
the provider applies content filtering or the response consists entirely
of tool calls (finish_reason="tool_calls"). Accessing .content without a
guard raises AttributeError or propagates None silently.
Adds a uniform check before every unguarded .content access across all
cookbook utility files:
if not r.choices or r.choices[0].message is None or r.choices[0].message.content is None:
raise ValueError("LLM returned empty or filtered response")
Anthropic calls guarded analogously: len(response.content) == 0 or
response.content[0].text is None.
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
response.choices[0].message.contentis typedOptional[str]in the OpenAI SDK — it returnsNone(not raises) when the provider applies content filtering or whenfinish_reasonis"tool_calls". Every unguarded.contentaccess in the cookbook is a latent crash site.This PR adds a uniform three-layer guard before every unguarded access across all 39 cookbook utility files:
Anthropic calls are guarded analogously (
len(response.content) == 0/.text is None).Files changed: all
cookbook/*/utils.pyandcookbook/*/utils/call_llm.pyfiles — 39 files, 138 insertions.Why this matters
The OpenAI SDK types
ChatCompletionMessage.contentasOptional[str]. The silentNonereturn propagates downstream — the crash happens far from the API call, often in user-facing code, with a confusingTypeError: argument of type 'NoneType' is not iterableor similar message.Test plan
call_llmraisesValueErrorwhen given a mockresponse.choices = []🤖 Generated with Claude Code