//需要代理才能使用 国内已经屏蔽该接口,请使用代理
public function chat($q){
// 设置chatGPT的接口URL
$api_url = 'https://api.openai.com/v1/chat/completions';
// 设置访问令牌
$access_token ="";
// 设置请求的参数
$data = array(
//'prompt' => '写一段php调用chatGPT', // 要向chatGPT发送的问题
'messages' =>[['role'=>"user",'content'=>$q]],
// 要向chatGPT发送的问题
'model' => 'gpt-3.5-turbo',
// 使用的模型名称
'max_tokens' => 1000, // chatGPT返回的最大文本长度
);
// 使用curl发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Authorization: Bearer ' . $access_token,
)
);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
file_put_contents("dd.log",$response,FILE_APPEND);
$response_data = json_decode($response, true);
if (isset($response_data['id'])) {
// 获取chatGPT返回的答案
$answer = $response_data['choices'][0]['message']['content'];
return $answer;
// 处理答案
} else {
// 处理错误
// ...
return '暂时无法回答你的问题';
}
}