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";
     });    
相关推荐
Archie_IT3 小时前
DeepSeek R1/V3满血版——在线体验与API调用
人工智能·深度学习·ai·自然语言处理
sp42a5 小时前
Windows 上源码安装 FastGPT
ai·fastgpt·rag
Watermelo6176 小时前
从DeepSeek大爆发看AI革命困局:大模型如何突破算力囚笼与信任危机?
人工智能·深度学习·神经网络·机器学习·ai·语言模型·自然语言处理
AL.千灯学长8 小时前
DeepSeek接入Siri(已升级支持苹果手表)完整版硅基流动DeepSeek-R1部署
人工智能·gpt·ios·ai·苹果vision pro
豌豆花下猫9 小时前
Python 潮流周刊#90:uv 一周岁了,优缺点分析(摘要)
后端·python·ai
♡喜欢做梦9 小时前
Deepseek 与 ChatGPT:AI 浪潮中的双子星较量
ai·chatgpt·deepseek
roamingcode12 小时前
实验 Figma MCP + Cursor 联合工作流
ai·ai编程·figma·mcp·mcp server·design to code
狂野小青年13 小时前
在PHP Web开发中,实现异步处理有几种常见方式的优缺点,以及最佳实践推荐方法
消息队列·php·最佳实践·异步任务
宇努力学习15 小时前
如何本地部署seepseek
python·ai·ollama·deepseek
Java知识技术分享16 小时前
使用LangChain构建第一个ReAct Agent
python·react.js·ai·语言模型·langchain