//需要代理才能使用 國內已經屏蔽該接口,請使用代理
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 '暫時無法回答你的問題';
}
}