$openai_api_key = 'your_openai_api_key_here';
$engine = 'davinci'; // ChatGPT 中的 AI 模型名称
$prompt = 'Hello, can you help me?'; // ChatGPT 中的提示信息
// 构造请求数据
$data = array(
'model' => $engine,
'prompt' => $prompt,
'temperature' => 0.7,
'max_tokens' => 60,
'echo' => true,
);
// 将请求数据转换为 JSON 格式
$json_data = json_encode($data);
// 构造 HTTP 请求头,包含 API Key
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $openai_api_key,
);
// 使用 cURL 发送 HTTP POST 请求
$ch = curl_init('https://api.openai.com/v1/engines/davinci/completions');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 打印响应结果
echo $response;