PHP 请求 chatgpt 对话接口 示例代码

PHP 请求chatgpt的chat/completions接口示例代码。将以下代码放到可执行的地方,在能正常上网情况下,将$apiKey变量替换成你自己的api_key,请求后即可返回结果

 

public function chat()
    {
        $apiKey = 'YOUR_OPENAI_API_KEY';

        $endpoint  = 'https://api.openai.com/v1/chat/completions';

        // 构建请求的数据
        $data = array(
            "messages" => array(
                array("role" => "system", "content" => "你是一个智能助手"),
                array("role" => "user", "content" => "给我讲一个笑话")
            ),
            "model" => "gpt-3.5-turbo" // 添加模型参数
        );

        // 设置请求头
        $headers = array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        );

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);

        curl_close($ch);

        // 处理响应数据
        if ($response) {
            $decodedResponse = json_decode($response, true);
            // 输出生成的回复
            echo "Generated reply: " . $decodedResponse['choices'][0]['message']['content'];
        } else {
            echo "请求失败。";
        }

    }

 

posted @ 2023-08-30 15:43  大雄呀  阅读(232)  评论(0编辑  收藏  举报