Search code examples
phpserverserver-sent-eventsopenai-api

Open AI Stream Completion Set Variable Inside Function PHP With Openai-php SDK


How to set variable inside this openai-php sdk function in stream completion ? I am using this open-ai library

https://github.com/orhanerday/open-ai

This is the code :

 $client->completion($configuration, function ($curl_info, $data) { 
            $response = ""; // This Variable Keep Init Because it is looping in this function                                       
            $cleanJson = str_replace("data: ", "", $data);                      
            if ($data != "data: [DONE]\n\n") {
                $arrayData = json_decode($cleanJson, true);                         
                $response = $response . $arrayData['choices'][0]['text']; // <= I cannot save all the content data to variable $response because it's keep replaced             
            } else {
                echo "ITS DONE";            
            }

            ob_flush();
            flush();            
            return strlen($data);               
         });    

I cannot define variable outside $client->completion function. Because it will not detect inside $client->completion function.

What I want is I can pass the variable outside to $client->completion function.

example :

 $client->completion($configuration, function ($curl_info, $data, $response, $other) { 

});

That example give an error.

How do I pass the $response or $other variable in the $client->Completion ?


Solution

  • Found the correct way. This is the correct one to pass the variable :

    $Response = "";     
                            
            $client->completion($configuration, function ($curl_info, $data) use (&$Response) {             
            $Response = "something here";
         });