Skip to content

Commit 6701d88

Browse files
committed
fix: handle None choices in ChatCompletion response (provider error payloads)
When a provider (e.g. OpenRouter) returns an error payload, the ChatCompletion response object has choices=None. Previously this caused a silent no-op or a downstream TypeError. Now a ModelBehaviorError is raised before choices[0] is accessed, including the provider's error field in the message when present.
1 parent fa50899 commit 6701d88

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

src/agents/models/openai_chatcompletions.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
from .. import _debug
2222
from ..agent_output import AgentOutputSchemaBase
23-
from ..exceptions import UserError
23+
from ..exceptions import ModelBehaviorError, UserError
2424
from ..handoffs import Handoff
2525
from ..items import ModelResponse, TResponseInputItem, TResponseStreamEvent
2626
from ..logger import logger
@@ -131,6 +131,16 @@ async def get_response(
131131
prompt=prompt,
132132
)
133133

134+
if not response.choices:
135+
provider_error = getattr(response, "error", None)
136+
error_details = (
137+
f": {provider_error}" if provider_error is not None else ""
138+
)
139+
raise ModelBehaviorError(
140+
f"ChatCompletion response has no choices (possible provider error payload)"
141+
f"{error_details}"
142+
)
143+
134144
message: ChatCompletionMessage | None = None
135145
first_choice: Choice | None = None
136146
if response.choices and len(response.choices) > 0:

0 commit comments

Comments
 (0)