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";
     });    
相关推荐
绵绵细雨中的乡音6 小时前
深入理解 ET 与 LT 模式及其在 Reactor 模型中的应用
服务器·网络·php
念风零壹9 小时前
AI 时代的前端技术:从系统编程到 JavaScript/TypeScript
前端·ai
懒虫虫~10 小时前
利用自定义Agent-Skill实现项目JDK17升级
ai·skill
AI架构全栈开发实战笔记11 小时前
Eureka 在大数据环境中的性能优化技巧
大数据·ai·eureka·性能优化
大厂资深架构师11 小时前
Spring Cloud Eureka在后端系统中的服务剔除策略
spring·spring cloud·ai·eureka
AI架构全栈开发实战笔记11 小时前
Eureka 对大数据领域服务依赖关系的梳理
大数据·ai·云原生·eureka
ServBay11 小时前
一个下午,一台电脑,终结你 90% 的 Symfony 重复劳动
后端·php·symfony
阿杰学AI12 小时前
AI核心知识91——大语言模型之 Transformer 架构(简洁且通俗易懂版)
人工智能·深度学习·ai·语言模型·自然语言处理·aigc·transformer
shengnan_wsn14 小时前
【一】【ai基础】【大模型和智能体初识】
ai
nimadan1214 小时前
**AI仿真人剧制作工具2025推荐,解锁沉浸式内容创作新范
ai