Skip to content

Commit 023bd6b

Browse files
authored
fix: correct content retrieval in HttpTransport by reading full stream. (#343)
getContent does not return the content of the body but the remaining content of the body. If you were to OpenAI::factory withHttpClient and i.e. a logging middlewere getContent would return an empty string since the content was already read by the log middleware. See: https://www.php-fig.org/psr/psr-7/ https://stackoverflow.com/questions/30549226/guzzlehttp-how-get-the-body-of-a-response-from-guzzle-6
1 parent 5740fce commit 023bd6b

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/Transporters/HttpTransporter.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public function requestObject(Payload $payload): Response
4848

4949
$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
5050

51-
$contents = $response->getBody()->getContents();
51+
$contents = (string) $response->getBody();
5252

5353
if (str_contains($response->getHeaderLine('Content-Type'), ContentType::TEXT_PLAIN->value)) {
5454
return Response::from($contents, $response->getHeaders());
@@ -75,7 +75,7 @@ public function requestContent(Payload $payload): string
7575

7676
$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
7777

78-
$contents = $response->getBody()->getContents();
78+
$contents = (string) $response->getBody();
7979

8080
$this->throwIfJsonError($response, $contents);
8181

@@ -102,7 +102,7 @@ private function sendRequest(Closure $callable): ResponseInterface
102102
return $callable();
103103
} catch (ClientExceptionInterface $clientException) {
104104
if ($clientException instanceof ClientException) {
105-
$this->throwIfJsonError($clientException->getResponse(), $clientException->getResponse()->getBody()->getContents());
105+
$this->throwIfJsonError($clientException->getResponse(), (string) $clientException->getResponse()->getBody());
106106
}
107107

108108
throw new TransporterException($clientException);
@@ -122,7 +122,7 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn
122122
$statusCode = $response->getStatusCode();
123123

124124
if ($contents instanceof ResponseInterface) {
125-
$contents = $contents->getBody()->getContents();
125+
$contents = (string) $contents->getBody();
126126
}
127127

128128
try {

0 commit comments

Comments
 (0)