File tree Expand file tree Collapse file tree 1 file changed +17
-5
lines changed
libs/partners/openai/langchain_openai/chat_models Expand file tree Collapse file tree 1 file changed +17
-5
lines changed Original file line number Diff line number Diff line change @@ -1111,15 +1111,27 @@ def _create_chat_result(
1111
1111
response_dict = (
1112
1112
response if isinstance (response , dict ) else response .model_dump ()
1113
1113
)
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).
1118
1117
if response_dict .get ("error" ):
1119
1118
raise ValueError (response_dict .get ("error" ))
1120
1119
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
+
1121
1132
token_usage = response_dict .get ("usage" )
1122
- for res in response_dict ["choices" ]:
1133
+
1134
+ for res in choices :
1123
1135
message = _convert_dict_to_message (res ["message" ])
1124
1136
if token_usage and isinstance (message , AIMessage ):
1125
1137
message .usage_metadata = _create_usage_metadata (token_usage )
You can’t perform that action at this time.
0 commit comments