Skip to content

fix: guard against empty choices before accessing response.choices[0]#1552

Open
qizwiz wants to merge 1 commit into
TransformerOptimus:mainfrom
qizwiz:fix/llm-response-unguarded
Open

fix: guard against empty choices before accessing response.choices[0]#1552
qizwiz wants to merge 1 commit into
TransformerOptimus:mainfrom
qizwiz:fix/llm-response-unguarded

Conversation

@qizwiz

@qizwiz qizwiz commented May 18, 2026

Copy link
Copy Markdown

What

Add a guard before the response.choices[0] access in superagi/llms/openai.py.

Why

response.choices is an empty list — not an exception — when the provider applies content filtering or max_tokens is exceeded before any content is generated. Accessing choices[0] without a length check raises IndexError in production.

# before
content = response.choices[0].message["content"]

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

Pre-existing test note

tests/unit_tests/llms/test_open_ai.py fails to import on the base branch due to openai.InvalidRequestError being removed in openai v1 (renamed to BadRequestError). This is unrelated to this change.

🤖 Generated with Claude Code

response.choices is an empty list — not an exception — when the provider
applies content filtering or max_tokens is exceeded before any content is
generated. Accessing choices[0] without a length check raises IndexError.

Adds a guard before the choices access in the chat completion path.
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