Skip to content

Commit 4ee6112

Browse files
authored
openai[patch]: Improve error message when response type is malformed (#31619)
1 parent 9de4f22 commit 4ee6112

File tree

1 file changed

+17
-5
lines changed
  • libs/partners/openai/langchain_openai/chat_models

1 file changed

+17
-5
lines changed

libs/partners/openai/langchain_openai/chat_models/base.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1111,15 +1111,27 @@ def _create_chat_result(
11111111
response_dict = (
11121112
response if isinstance(response, dict) else response.model_dump()
11131113
)
1114-
# Sometimes the AI Model calling will get error, we should raise it.
1115-
# Otherwise, the next code 'choices.extend(response["choices"])'
1116-
# will throw a "TypeError: 'NoneType' object is not iterable" error
1117-
# to mask the true error. Because 'response["choices"]' is None.
1114+
# Sometimes the AI Model calling will get error, we should raise it (this is
1115+
# typically followed by a null value for `choices`, which we raise for
1116+
# separately below).
11181117
if response_dict.get("error"):
11191118
raise ValueError(response_dict.get("error"))
11201119

1120+
# Raise informative error messages for non-OpenAI chat completions APIs
1121+
# that return malformed responses.
1122+
try:
1123+
choices = response_dict["choices"]
1124+
except KeyError as e:
1125+
raise KeyError(
1126+
f"Response missing `choices` key: {response_dict.keys()}"
1127+
) from e
1128+
1129+
if choices is None:
1130+
raise TypeError("Received response with null value for `choices`.")
1131+
11211132
token_usage = response_dict.get("usage")
1122-
for res in response_dict["choices"]:
1133+
1134+
for res in choices:
11231135
message = _convert_dict_to_message(res["message"])
11241136
if token_usage and isinstance(message, AIMessage):
11251137
message.usage_metadata = _create_usage_metadata(token_usage)

0 commit comments

Comments
 (0)