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";
     });    
相关推荐
张铁牛19 分钟前
1. LangChain4j 初识,想使用Java开发AI应用?
ai·langchain4j
无声旅者2 小时前
n8n:解锁自动化工作流的无限可能
ai·自动化·oneapi·ai大模型·n8n
在荒野的梦想5 小时前
DeepSeek+SpringAI实现流式对话
java·ai
程序员鱼皮6 小时前
刚刚,Cursor 1.0炸裂发布!4大亮点实战
计算机·ai·程序员·互联网·软件开发
链上Sniper6 小时前
Python 区块链开发实战:从零到一构建智能合约
开发语言·网络·python·架构·区块链·php·智能合约
链上Sniper12 小时前
智能合约安全漏洞解析:从 Reentrancy 到 Integer Overflow
开发语言·网络·架构·区块链·php·智能合约
程序员鱼皮13 小时前
全球首个无限执行的 AI 出现!给我玩爽了
计算机·ai·互联网·agent·代码
链上Sniper14 小时前
高并发区块链系统实战:从架构设计到性能优化
开发语言·网络·python·性能优化·架构·区块链·php
链上Sniper15 小时前
NFT 市场开发:基于 Ethereum 和 IPFS 构建去中心化平台
开发语言·网络·架构·去中心化·区块链·php
链上Sniper15 小时前
区块链跨链通信:使用 Cosmos SDK 实现链间互操作
开发语言·网络·架构·区块链·php