php利用swoole将chatgpt api接口请求换成websocket请求示例代码

代码语言:phpcli

所属分类:其他

代码描述:php利用swoole将chatgpt api接口请求换成websocket请求示例代码,chatgpt官方的请求是sse技术,对于移动端不是友好,那么将他转换成websocket实时推送就能兼容所有客户端了,毕竟websocket技术覆盖面广嘛。这个也适合国内所有兼容openai接口的大模型调用,包括千问、智谱ai等。

代码标签: php swoole chatgpt api 接口 请求 换成 websocket 请求 示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
use Swoole\WebSocket\Server;
use Swoole\Coroutine\Http\Client;
//适合所有国内兼容openai接口的大模型调用
$server
= new Server("0.0.0.0", 9501);

$server
->on("start", function ($server) {
    echo
"Swoole WebSocket server is started at ws://0.0.0.0:9501\n";
});

$server
->on("open", function ($server, $request) {
    echo
"Connection open: {$request->fd}\n";
});

$server
->on("message", function ($server, $frame) {
    echo
"Received message: {$frame->data}\n";

   
// 解析JSON数据
    $data
= json_decode($frame->data, true);
   
if (json_last_error() !== JSON_ERROR_NONE) {
        $server
->push($frame->fd, "Invalid JSON data");
       
return;
   
}

   
// 根据action执行不同操作
   
if (isset($data['action']) && $data['action'] === 'ask') {
        $content
= $data['content'];

       
// 使用协程客户端发送HTTP请求
        go
(function () use ($server, $frame, $content) {
         
.........完整代码请登录后点击上方下载按钮下载查看

网友评论0