2929
3030use function curl_close ;
3131use function curl_exec ;
32+ use function curl_getinfo ;
3233use function curl_init ;
3334use function curl_setopt ;
3435use function extension_loaded ;
3536use function json_decode ;
37+ use function sprintf ;
3638
3739class Client implements GeminiClientInterface
3840{
@@ -103,6 +105,21 @@ public function generateContentStream(
103105 static fn (array $ arr ) => $ callback (GenerateContentResponse::fromArray ($ arr )),
104106 );
105107
108+ $ writeFunction = static function (CurlHandle $ ch , string $ str ) use ($ request , $ parser ): int {
109+ $ responseCode = curl_getinfo ($ ch , CURLINFO_RESPONSE_CODE );
110+
111+ return $ responseCode === 200
112+ ? $ parser ->consume ($ str )
113+ : throw new RuntimeException (
114+ sprintf (
115+ 'Gemini API operation failed: operation=%s, status_code=%d, response=%s ' ,
116+ $ request ->getOperation (),
117+ $ responseCode ,
118+ $ str ,
119+ ),
120+ );
121+ };
122+
106123 $ ch = curl_init ("{$ this ->baseUrl }/v1/ {$ request ->getOperation ()}" );
107124
108125 if ($ ch === false ) {
@@ -115,11 +132,7 @@ public function generateContentStream(
115132 'Content-type: application/json ' ,
116133 self ::API_KEY_HEADER_NAME . ": {$ this ->apiKey }" ,
117134 ]);
118- curl_setopt (
119- $ ch ,
120- CURLOPT_WRITEFUNCTION ,
121- static fn (CurlHandle $ ch , string $ str ): int => $ parser ->consume ($ str ),
122- );
135+ curl_setopt ($ ch , CURLOPT_WRITEFUNCTION , $ writeFunction );
123136 curl_exec ($ ch );
124137 curl_close ($ ch );
125138 }
0 commit comments