@@ -225,6 +225,16 @@ function ($chunk) use (&$content, $listener) {
225225 $ payload ,
226226 );
227227 $ body = $ response ->getBody ();
228+
229+ if ($ response ->getStatusCode () >= 400 ) {
230+ $ json = is_string ($ body ) ? json_decode ($ body , true ) : null ;
231+ $ content = $ this ->formatErrorMessage ($ json );
232+ throw new \Exception (
233+ ucfirst ($ this ->getName ()).' API error: ' .$ content ,
234+ $ response ->getStatusCode ()
235+ );
236+ }
237+
228238 $ json = is_string ($ body ) ? json_decode ($ body , true ) : null ;
229239 if (is_array ($ json ) && isset ($ json ['choices ' ][0 ]['message ' ]['content ' ])) {
230240 $ content = $ json ['choices ' ][0 ]['message ' ]['content ' ];
@@ -253,11 +263,7 @@ protected function process(Chunk $chunk, ?callable $listener): string
253263
254264 $ json = json_decode ($ data , true );
255265 if (is_array ($ json ) && isset ($ json ['error ' ])) {
256- if (isset ($ json ['error ' ]['code ' ], $ json ['error ' ]['message ' ])) {
257- return '( ' .$ json ['error ' ]['code ' ].') ' .$ json ['error ' ]['message ' ];
258- }
259-
260- return is_array ($ json ['error ' ]) ? json_encode ($ json ['error ' ]) : $ json ['error ' ];
266+ return $ this ->formatErrorMessage ($ json );
261267 }
262268
263269 foreach ($ lines as $ line ) {
@@ -390,4 +396,22 @@ public function getName(): string
390396 {
391397 return 'openai ' ;
392398 }
399+
400+ /**
401+ * Extract and format error information from API response
402+ *
403+ * @param mixed $json
404+ * @return string
405+ */
406+ protected function formatErrorMessage ($ json ): string
407+ {
408+ if (! is_array ($ json )) {
409+ return '(unknown_error) Unknown error ' ;
410+ }
411+
412+ $ errorType = isset ($ json ['error ' ]['code ' ]) ? (string ) $ json ['error ' ]['code ' ] : 'unknown_error ' ;
413+ $ errorMessage = isset ($ json ['error ' ]['message ' ]) ? (string ) $ json ['error ' ]['message ' ] : 'Unknown error ' ;
414+
415+ return '( ' .$ errorType .') ' .$ errorMessage ;
416+ }
393417}
0 commit comments