swoole搭建一个chatgpt api代理服务http流式接口示例代码

代码语言:phpcli

所属分类:其他

代码描述:swoole搭建一个chatgpt api代理服务http流式接口示例代码,通过搭建一个http服务来流式请求chatgpt的api,适合其他兼容openai协议的大模型api接口,例如通义千问。

代码标签: swoole chatgpt api 代理 服务 http 流式 接口 示例 代码

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

<?php
use Swoole\Coroutine\Http\Client;
use Swoole\Http\Server;

$server = new Server("0.0.0.0", 9501);

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

$server->on("request", function ($request, $response) {
    
     // 设置跨域请求头
    $response->header("Access-Control-Allow-Origin", "*");
    $response->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    $response->header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

    // 处理 OPTIONS 请求
    if ($request->server['request_method'] === 'OPTIONS') {
        $response->status(204);
        $response->end();
        return;
    }

    // 设置响应头
    $response->header("Content-Type", "text/event-stream;charset=utf-8");
    $response->header("Cache-Control", "no-cache");
    $response->header("Connection", "keep-alive");
    // 使用协程客户端发送HTTP请求
    go(function () use ($response) {
        
        //阿里通义千问填dashscope.aliyuncs.com
        $client = new Client('api.openai.com', 443, true);
        $client->setHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer APIKEY',
        ]);

        $messages = [
            ["role" => "system", "content" => "你是一个AI助手chatai"],
            ["role" => "user", "content" => "你好"]
        ];

        $postData = [
            "model" => "gpt-4",//阿里通义千问填qwen-plus
            &#.........完整代码请登录后点击上方下载按钮下载查看

网友评论0