Safety Guest'T blog

  • 首页
  • 归档
  • 软件开发
  • 网络安全
  • 逆向破解
  • 人工智能
  • 资源分享
  • 区 块 链
  • 隐私政策
  • 友情链接

搭建Chat GPT[3.5] AI聊天机器人带记忆

  • Tz
  • 2023-03-08
  • 0

1.申请Key点击去申请.
2.复制下面代码到服务器(注意因为我使用的Tp6 所以有用到框架函数的自行替换)

php代码:

        header('Access-Control-Allow-Origin: *');
        $post = Request::post();
        $prompt = base_check_post_data($post, 'prompt');
        $ch = curl_init();
        $url = 'https://api.openai.com/v1/chat/completions';
        $api_key = '这里替换为自己的OPENAI KEY';

        $prompt = ["role" => "user", "content" => $prompt];

        if (session('?history')) {
            $history = session('history');
            array_push($history, $prompt);
            $promptsub = $history;

            //判断是否超过限制
            $strlen = strlen(json_encode($promptsub));
            if ($strlen > 4000) {
                array_splice($promptsub, 0, 2); //删除前两个
            }
            
            //低于1字节
            if($strlen < 1){
                $promptsub = [$prompt];
            }
            
        } else {
            $promptsub = [$prompt];
        }

        $post_fields = [
            "model" => "gpt-3.5-turbo",
            "messages" => $promptsub,
            "max_tokens" => 700, //限制返回字节 最高2048
            'stop' => ['\n'], //截止符
            'temperature' => 0.5, //温度(0-1 越低越保守)
        ];
        $header  = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $api_key
        ];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error: ' . curl_error($ch);
        }
        curl_close($ch);
        $response = json_decode($result, true);

        if (!isset($response['choices'])) {
            $result = [
                'code' => 500,
                'msg' => '获取失败',
                'end' =>json_encode($response),
            ];
            return json_encode($result);
        }

        $content = ["role" => "system", "content" => $response['choices'][0]['message']['content']];

        if (session('?history') && isset($history[5])) {
            array_splice($promptsub, 0, 2); //删除前两个
        }

        array_push($promptsub, $content);
        session('history', $promptsub);

        $result = [
            'code' => 200,
            'msg' => '成功',
            'history' => session('history'),
            'data' => $response['choices'],
        ];
        return json_encode($result);
© 2025 Safety Guest'T blog
Theme by Wing
渝ICP备 2021011909号 渝公网安备 50019002502382号
  • {{ item.name }}
  • {{ item.name }}