Set Variable Inside Function PHP With Openai-php SDK

huangapple go评论54阅读模式
英文:

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

问题

To set a variable inside the openai-php SDK function for stream completion, you can use the use keyword to pass variables from the outer scope into the closure function. Here's an example of how you can modify your code:

$client->completion($configuration, function ($curl_info, $data) use (&$response) {	
    $cleanJson = str_replace("data: ", "", $data);						
    if ($data != "data: [DONE]\n\n") {
        $arrayData = json_decode($cleanJson, true);							
        $response = $response . $arrayData['choices'][0]['text'];
    } else {
        echo "ITS DONE";
    }

    ob_flush();
    flush();

    return strlen($data);
});

By using use (&$response), you can pass the $response variable from the outer scope into the closure function, allowing you to modify it within the function.

Remember to declare the $response variable before calling the completion function so that it's accessible in both scopes.

英文:

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 ?

答案1

得分: 0

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";
});
英文:

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";
	 });		

huangapple
  • 本文由 发表于 2023年5月7日 17:34:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定