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";
     });    
相关推荐
0xR3lativ1ty18 分钟前
每周AI新工具速览:Kiln与OpenRA-RL登场
人工智能·ai
赵康21 分钟前
智人曾经这样灭绝猛犸象:AI入侵与行业灭绝
ai·llm
nbwenren29 分钟前
办公AI实测:Gemini3、GPT-4o、Claude3.5谁更强?
服务器·数据库·php
Agent产品评测局40 分钟前
离散制造业生产流程优化,AI落地实操步骤详解:从传统自动化到企业级智能体的技术范式跃迁
运维·人工智能·ai·自动化
还是转转41 分钟前
深入认识 Agent —— 实现你自己的 Agent
ai·agent
小羊Yveesss42 分钟前
2026年前端开发新趋势:智能协同、工具革新与场景深耕
前端·ai
YXWik61 小时前
Linux内网搭建FastGpt+配置ollama私有化的deepseek-r1:7b模型
ai
hopetomorrow1 小时前
学习路之PHP --PHP 常用扩展及作用表
开发语言·学习·php
子游i1 小时前
HappyHorse 1.0 创作指南
人工智能·ai·happyhorse
GJGCY2 小时前
从技术路径看金融AI智能体规模化落地:三大风险与可靠架构选择
ai·金融·智能体