Skip to content

Fix #604 Chat Completion model raises runtime error when response.choices is empty #935

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 25, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/agents/models/openai_chatcompletions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

from openai import NOT_GIVEN, AsyncOpenAI, AsyncStream
from openai.types import ChatModel
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from openai.types.chat import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage
from openai.types.chat.chat_completion import Choice
from openai.types.responses import Response
from openai.types.responses.response_prompt_param import ResponsePromptParam
from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails
Expand Down Expand Up @@ -74,8 +75,11 @@ async def get_response(
prompt=prompt,
)

first_choice = response.choices[0]
message = first_choice.message
message: ChatCompletionMessage | None = None
first_choice: Choice | None = None
if response.choices and len(response.choices) > 0:
first_choice = response.choices[0]
message = first_choice.message

if _debug.DONT_LOG_MODEL_DATA:
logger.debug("Received model response")
Expand All @@ -86,10 +90,8 @@ async def get_response(
json.dumps(message.model_dump(), indent=2),
)
else:
logger.debug(
"LLM resp had no message. finish_reason: %s",
first_choice.finish_reason,
)
finish_reason = first_choice.finish_reason if first_choice else "-"
logger.debug(f"LLM resp had no message. finish_reason: {finish_reason}")

usage = (
Usage(
Expand Down