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";
     });    
相关推荐
装不满的克莱因瓶18 小时前
【Coze智能体实战二】一键生成儿歌背单词视频
人工智能·ai·实战·agent·工作流·智能体·coze
lskblog19 小时前
PHP中正确处理HTTP响应:从原始响应到JSON数组的完整指南
http·json·php·laravel
万岳软件开发小城21 小时前
2026 在线教育新趋势:网校系统源码正在重塑教育培训平台开发模式
人工智能·php·在线教育系统源码·教育平台搭建·教育app开发·教育软件开发
菠菠萝宝1 天前
从传统后端到AI智能驱动:Java + AI 生态深度实战技术总结
java·人工智能·ai·llm·知识图谱·ai编程·rag
iCxhust1 天前
linux /etc 目录 etc是什么缩写
linux·运维·服务器·php
豌豆学姐1 天前
Sora2 能做什么?25 秒视频生成 API 的一次接入实践
大数据·人工智能·小程序·aigc·php·开源软件
zhengfei6111 天前
从小白入门到专家入狱——400+ 精选实战渗透路径
ai
loong_XL1 天前
elastic kibana可视化数据统计案例
运维·ai·智能体
21991 天前
SenseVoice专有名词识别微调完整教程
ai·开源
小白跃升坊1 天前
基于AI+企微的智能报销系统
ai·企业微信·agent·智能体·效率提升·日常报销·报销流程