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";
     });    
相关推荐
唐璜Taro11 小时前
AI Agent 智能体:从入门到实战的学习路线
学习·ai
@蔓蔓喜欢你11 小时前
CSS 变量:样式开发的新维度
人工智能·ai
创世宇图12 小时前
【AI入门知识点】Agent 是什么?为什么说它是 AI 的下一阶段?
ai·agent
雪度娃娃12 小时前
Asio异步读写——简单服务器和客户端异步通信
运维·服务器·网络·c++·php
Jurio.13 小时前
AI Daily Paper Reader(ADPR):零服务器搭建个人/团队通用大模型API驱动的论文阅读与推荐平台
论文阅读·人工智能·ai
searchforAI13 小时前
我用这款本土NotebookLM平替重构了知识库
人工智能·笔记·gpt·ai·音视频·知识图谱
不懂的浪漫13 小时前
01|从 Spring Boot 项目理解 RAG:ingest、query、rerank、trace 到 eval
java·人工智能·spring boot·后端·ai·rag
中科三方13 小时前
域名解析修改后,用户仍访问旧IP?原因排查与高效解决指南
网络协议·tcp/ip·php
TheRouter13 小时前
AI Agent 的Prompt Injection 防御实战:从EchoLeak 零点击外泄到6层防护栈(含可运行代码与对比表)
人工智能·ai·prompt
Artech13 小时前
[对比学习LangChain和MAF-02]基本编程模式的差异(下篇)
ai·langchain·agent·maf