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";
     });    
相关推荐
皓月盈江2 小时前
Linux电脑本机使用小皮面板集成环境开发调试WEB项目
linux·php·web开发·phpstudy·小皮面板·集成环境·www.xp.cn
pumpkin845149 小时前
DeepSeek-R1-Distill-Qwen-1.5B代表什么含义?
ai
码观天工12 小时前
.NET 原生驾驭 AI 新基建实战系列(七):Weaviate ── 语义搜索的智能引擎创新者
ai·c#·.net·向量数据库·weaviate
向哆哆12 小时前
Netty在Java网络编程中的应用:实现高性能的异步通信
java·网络·php
带刺的坐椅14 小时前
jFinal 使用 SolonMCP 开发 MCP(拥抱新潮流)
java·ai·solon·jfinal·mcp
Rverdoser14 小时前
代理服务器运行速度慢是什么原因
开发语言·前端·php
探索云原生14 小时前
一文搞懂 GPU 共享方案: NVIDIA Time Slicing
ai·云原生·kubernetes·gpu
菜鸟分享录14 小时前
MCP 入门实战:用 C# 开启 AI 新篇章
ai·c#·semantic kernel·mcp
森叶15 小时前
从 JIT 即时编译一直讲到CGI|FastGGI|WSGI|ASGI四种协议的实现细节
python·php·web
wang_yb16 小时前
集成学习常用组合策略:让多个模型“合作”得更好
ai·databook