英文:
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";
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论