Skip to content

Commit f8e57e2

Browse files
committed
fix(OpenAI): no early bail out on content-type text/plain
1 parent 1356bdf commit f8e57e2

2 files changed

Lines changed: 9 additions & 8 deletions

File tree

src/Transporters/HttpTransporter.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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
}

tests/Transporters/HttpTransporter.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@
115115
test('request object mismatched project error', function (string $requestMethod) {
116116
$payload = Payload::list('models');
117117

118-
$response = new Response(401, ['Content-Type' => 'application/json; charset=utf-8'], json_encode([
118+
$response = new Response(401, ['Content-Type' => 'text/plain; charset=utf-8'], json_encode([
119119
'error' => [
120120
'message' => 'OpenAI-Project header should match project for API key',
121121
'type' => 'invalid_request_error',

0 commit comments

Comments
 (0)