使用PHP请求ChatGPT聊天接口

Posted 黄聪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用PHP请求ChatGPT聊天接口相关的知识,希望对你有一定的参考价值。

<?php
(0);
// ChatGPT API endpoint
// $url = \'https://api.openai.com/v1/engines/davinci-codex/completions\';
$url = \'https://api.openai.com/v1/chat/completions\'; //聊天接口
// $url = \'https://api.openai.com/v1/completions\';
 
// Your API key
$api_key = \'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\';
 
// Request headers
$headers = array(
    \'Content-Type: application/json\',
    \'Authorization: Bearer \' . $api_key,
);
 
// Request data
$data = array(
    // \'model\' => \'text-davinci-003\',
    \'model\' => \'gpt-3.5-turbo\', //聊天模型
    // \'model\' => \'text-curie-001\',
    \'temperature\' => 0.8,
    // \'prompt\' => \'如何用php使用chatgpt的聊天接口\', //聊天不用
    \'max_tokens\' => 3000,
    \'messages\' => [
        ["role" => "user", "content" => "Hello!"],
        ["role"  =>  "assistant","content"  =>  "\\n\\n您好!有什么可以帮助您的今天?"],
        ["role" => "user", "content" => "历史上的今天发生过什么事情?"],
    ]
     
);
 
// Send request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
 
// Print response
echo $response;

 

以上是关于使用PHP请求ChatGPT聊天接口的主要内容,如果未能解决你的问题,请参考以下文章

基于小程序制作一个ChatGPT聊天机器人

基于ChatGPT+SpringBoot打造智能聊天AI机器人接口并上线至服务器

基于ChatGPT+SpringBoot打造智能聊天AI机器人接口并上线至服务器

java调用chatgpt接口,实现专属于自己的人工智能助手

我让API版的ChatGPT长了记性!

使用chatgpt实现微信聊天小程序(秒回复),github开源(附带链接)