稳如老狗!非常稳定!!!!!(例子也是用这个地址)下面开始讲解用php如何开发流式的chatgpt流式输出,拥有像打字机一样逐行逐字的显示结果!体验非常好!
- https://www.openai-proxy.com
首先前端提交要建立接口需要的JSON,比如
那么后端的php怎么接收呢?参照下面的写法
- var data = {
- message: alytyqw,
- context: JSON.stringify(contextarray),
- };
- var jsondata=JSON.stringify(data);
上面的$data值就是把前端提交过来的JSON转换成我们需要的数组了,而后就是给予判断了,如果存在上下文的数组那就循环获取下,如果不存在就取数组message里面的值!最后 json_encode函数在把数组转换为curl需要的JSON对象!
- <?php
- header('Access-Control-Allow-Origin: *');
- header("Content-Type: text/event-stream");
- $apikey = 'sk-1oVG9dq1s6wjikoowkwKYVPJ34J58FgsBprSpYv4p';//到chatgpt申请
- $wenxinapiurl="https://api.openai-proxy.com/v1/chat/completions";//chatgpt接口地址有反向代理
- $data = json_decode(file_get_contents('php://input'), true);
- $postData = ["model"=>'gpt-3.5-turbo-0613',"stream"=>true,"max_tokens"=>3000];
- $context = json_decode($api->param('context',$data['context'],'RepPostStr')?: "[]", true) ?: [];//提出问题联系上下文需要传入参数context
- if (!empty($context)) {
- $context = array_slice($context, -5);
- foreach ($context as $message) {
- $postData['messages'][] = ['role' => 'user', 'content' => str_replace("n", "\n", $message[0])];
- $postData['messages'][] = ['role' => 'assistant', 'content' => str_replace("n", "\n", $message[1])];
- $wenxinyiyanask=RepPostStr($message[0]);
- }
- }else{
- $wenxinyiyanask=$api->param('message',$data['message'],'RepPostStr');
- }
- $postData['messages'][] = ['role' => 'user', 'content' =>$api->param('message',$data['message'],'RepPostStr')];
- $postData = json_encode($postData);
所有的准备工作已经就绪了!下面开始curl函数
这样就完成chatgpt流式输出数据了!接下来就是前端接收了!注:(sse原生不支持POST数据的,自己百度搜索下载一个SSE.JS的组件,用法与原生的SSE基本一样)
- $ch = curl_init();
- $headers= ['Content-Type: application/json','Authorization: Bearer ' . $apikey];
- $callback = function ($ch, $data) {
- $complete = json_decode($data);
- if (isset($complete->error)) {
- setcookie("errcode", $complete->error->type);
- setcookie("errmsg", $complete->error->message);
- echo "event: close".PHP_EOL;
- echo "data: Connection closed".PHP_EOL . PHP_EOL;
- ob_flush();
- flush();
- }
- echo $data;
- ob_flush();
- flush();
- return strlen($data);
- };
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_URL, $wenxinapiurl);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
- curl_exec($ch);
- curl_close($ch);