写一个对接chatgpt api的php完成程序
以下是一个使用PHP完成对接ChatGPT API的示例程序:
<?php
// ChatGPT API的Endpoint和API密钥
$endpoint = 'https://api.openai.com/v1/chat/completions';
$api_key = 'YOUR_API_KEY';
// ChatGPT API请求参数
$data = [
'prompt' => 'What is the meaning of life?',
'temperature' => 0.7,
'max_tokens' => 50
];
// 将请求参数转为JSON格式
$json_data = json_encode($data);
// 发起API请求
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行API请求
$response = curl_exec($ch);
curl_close($ch);
// 解析API响应
if ($response === false) {
die('API request failed');
}
$response_data = json_decode($response, true);
// 提取生成的回复
$choices = $response_data['choices'];
if (!empty($choices)) {
$reply = $choices[0]['text'];
echo $reply;
} else {
echo 'No reply from ChatGPT';
}
请确保将上述代码中的YOUR_API_KEY替换为您的ChatGPT API密钥。此外,您还可以根据需要自定义请求参数,如prompt(对话的开始语句)、temperature(生成文本的随机性)和max_tokens(生成的最大令牌数)。
这是一个简单的示例,您可以根据您的具体需求进行扩展和优化
原文地址: http://www.cveoy.top/t/topic/iFaU 著作权归作者所有。请勿转载和采集!