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";
     });    
相关推荐
L-影3 分钟前
为什么你的数据里藏着“隐形圈子”?聊聊AI中的聚类
人工智能·ai·数据挖掘·聚类
我叫张小白。19 分钟前
Dify系列(一):平台安装部署+界面操作
docker·ai·语言模型·大模型·dify·智能体
GISer_Jing1 小时前
AI Agent操作系统架构师:Harness Engineer解析
前端·人工智能·ai·aigc
roman_日积跬步-终至千里1 小时前
【大模型语言基础(2)】文本如何变成数字 — 分词与嵌入
ai
极客老王说Agent2 小时前
别被OpenClaw的30万Star晃了眼!AI产业逻辑重写后,打工人更该看清谁在“真干活”
人工智能·ai·chatgpt
AAI机器之心2 小时前
这个RAG框架绝了:无论多少跳,LLM只调用两次,成本暴降
人工智能·python·ai·llm·agent·产品经理·rag
xixixi777772 小时前
安全嵌入全链路:从模型训练到智能体交互,通信网络是AI安全的“地基”
人工智能·安全·ai·多模态·数据·通信·合规
Agent产品评测局3 小时前
企业 AI Agent 落地,如何保障数据安全与合规?——企业级智能体安全架构与合规路径深度盘点
人工智能·安全·ai·chatgpt·安全架构
VIP_CQCRE3 小时前
零成本 AI 副业:使用链接赚取你的第一桶金,手把手教程
ai
x-cmd3 小时前
[x-cmd] 终端里的飞书:lark-cli,让 AI Agent 拥有“实体办公”能力
java·人工智能·ai·飞书·agent·x-cmd