@@ -86,13 +86,13 @@ public function requestStringOrObject(Payload $payload): AdaptableResponse
8686
8787 $ contents = (string ) $ response ->getBody ();
8888
89+ $ this ->throwIfRateLimit ($ response );
90+ $ this ->throwIfJsonError ($ response , $ contents );
91+
8992 if (str_contains ($ response ->getHeaderLine ('Content-Type ' ), ContentType::TEXT_PLAIN ->value )) {
9093 return AdaptableResponse::from ($ contents , $ response ->getHeaders ());
9194 }
9295
93- $ this ->throwIfRateLimit ($ response );
94- $ this ->throwIfJsonError ($ response , $ contents );
95-
9696 try {
9797 /** @var array{error?: array{message: string, type: string, code: string}} $data */
9898 $ data = json_decode ($ contents , true , flags: JSON_THROW_ON_ERROR );
@@ -163,10 +163,6 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn
163163 return ;
164164 }
165165
166- if (! str_contains ($ response ->getHeaderLine ('Content-Type ' ), ContentType::JSON ->value )) {
167- return ;
168- }
169-
170166 if ($ contents instanceof ResponseInterface) {
171167 $ contents = (string ) $ contents ->getBody ();
172168 }
@@ -179,6 +175,11 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn
179175 throw new ErrorException ($ data ['error ' ], $ response );
180176 }
181177 } catch (JsonException $ jsonException ) {
178+ // Due to some JSON coming back from OpenAI as text/plain, we need to avoid an early return from purely content-type checks.
179+ if (! str_contains ($ response ->getHeaderLine ('Content-Type ' ), ContentType::JSON ->value )) {
180+ return ;
181+ }
182+
182183 throw new UnserializableResponse ($ jsonException , $ response );
183184 }
184185 }
0 commit comments