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

题意:使用 OpenAI 的 PHP SDK(例如 openai-php)来在函数内部设置和完成一个流(stream)相关的变量

问题背景:

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

如何使用 openai-php SDK 在流完成(stream completion)的函数内部设置变量?我正在使用这个 open-ai 库。

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

This is the code :

php 复制代码
$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.

我无法在 $client->completion 函数之外定义变量,因为该变量在 $client->completion 函数内部不会被检测到。

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

我想要的是我能将变量从外部传递到 $client->completion 函数中。

example : 示例

php 复制代码
 $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 ?

如何将 $response$other 变量传递给 $client->Completion

问题解决:

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

找到了正确的方法。这是传递变量的正确方式:

php 复制代码
$Response = "";     
                        
        $client->completion($configuration, function ($curl_info, $data) use (&$Response) {             
        $Response = "something here";
     });    
相关推荐
wrangler_csdn34 分钟前
如何一键将 PDF 转为 Word?
人工智能·安全·ai
hj104339 分钟前
php上传企业微信附件的方法
开发语言·php·企业微信
哥布林学者1 小时前
吴恩达深度学习课程二: 改善深层神经网络 第二周:优化算法(一)Mini-batch 梯度下降
深度学习·ai
游九尘1 小时前
在 PHP 中打印数据(调试、输出内容)
php
深圳市恒讯科技3 小时前
使用站群服务器做SEO,如何避免被搜索引擎判定为“站群作弊”?
服务器·搜索引擎·php
百锦再3 小时前
第8章 模块系统
android·java·开发语言·python·ai·rust·go
励志成为糕手4 小时前
VSCode+Cline部署本地爬虫fetch-mcp实战
ide·vscode·爬虫·ai·mcp
APIshop4 小时前
代码实战:PHP爬虫抓取信息及反爬虫API接口
开发语言·爬虫·php
CoderJia程序员甲5 小时前
GitHub 热榜项目 - 日榜(2025-11-06)
ai·开源·大模型·github·ai教程
MaybeAI5 小时前
Skill 与 Workflow:让自动化更“聪明”的系统架构
人工智能·ai·自动化·workflow·工作流