Skip to content

Commit

Permalink
Handle HTTP errors in streaming requests
Browse files Browse the repository at this point in the history
  • Loading branch information
erdemkose committed Jan 5, 2024
1 parent d56e712 commit 055a60e
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@

use function curl_close;
use function curl_exec;
use function curl_getinfo;
use function curl_init;
use function curl_setopt;
use function extension_loaded;
use function json_decode;
use function sprintf;

class Client implements GeminiClientInterface
{
Expand Down Expand Up @@ -103,6 +105,21 @@ public function generateContentStream(
static fn (array $arr) => $callback(GenerateContentResponse::fromArray($arr)),
);

$writeFunction = static function (CurlHandle $ch, string $str) use ($request, $parser): int {
$responseCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

return $responseCode === 200
? $parser->consume($str)
: throw new RuntimeException(
sprintf(
'Gemini API operation failed: operation=%s, status_code=%d, response=%s',
$request->getOperation(),
$responseCode,
$str,
),
);
};

$ch = curl_init("{$this->baseUrl}/v1/{$request->getOperation()}");

if ($ch === false) {
Expand All @@ -115,11 +132,7 @@ public function generateContentStream(
'Content-type: application/json',
self::API_KEY_HEADER_NAME . ": {$this->apiKey}",
]);
curl_setopt(
$ch,
CURLOPT_WRITEFUNCTION,
static fn (CurlHandle $ch, string $str): int => $parser->consume($str),
);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $writeFunction);
curl_exec($ch);
curl_close($ch);
}
Expand Down

0 comments on commit 055a60e

Please sign in to comment.