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 "请求失败。";
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值