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";
     });    
相关推荐
MCP星球12 分钟前
我们离Agent终极形态又近了一步:全球首个支持谷歌A2A(Agent-to-Agent)协议的智能体注册网站上线Product Hunt,未来智能体协作网络
ai·agent·智能体·智能体协作·a2a·a2a协议·agent network·智能体网络·谷歌a2a·agent2agent
小研学术1 小时前
如何用AI辅助数据分析及工具推荐
论文阅读·人工智能·ai·数据挖掘·数据分析·deepseek
明天依旧下着大雨3 小时前
PHP8.2.9NTS版本使用composer报错,扩展找不到的问题处理
php·composer
取个好名称3 小时前
在线查看【免费】 txt, xml(渲染), md(渲染), java, php, py, js, css 文件格式网站
xml·javascript·php
Olivia9894 小时前
👩‍💻我为什么从 MAMP 转到 ServBay:一位高级工程师的工具箱革命
php
大数据AI人工智能培训专家培训讲师叶梓5 小时前
FramePack:让视频生成更高效、更实用
人工智能·ai·大模型·音视频·视频·视频生成·长视频
NowStudio5 小时前
你一定想不到, 2025年了, 我竟然开始写php了
后端·php
凌鲨6 小时前
Eteam 0.3版本开发规划
ai·语言模型
常年游走在bug的边缘6 小时前
基于spring boot 集成 deepseek 流式输出 的vue3使用指南
java·spring boot·后端·ai
ぃ灵彧が8 小时前
MCP协议在纳米材料领域的深度应用:从跨尺度协同到智能研发范式重构
人工智能·ai·科学计算·材料·mcp·纳米·纳米材料