PHP 调用 ChatGPT AI 网站源码示例
以下是一个简单的 PHP 源码示例,用于调用 ChatGPT AI 网站:
<?php
// 定义 ChatGPT AI 网站的 API 密钥和聊天内容
$apiKey = 'your_api_key';
$chatContent = 'Hi, how are you?';
// 创建一个包含 API 密钥和聊天内容的关联数组
$data = array(
'apiKey' => $apiKey,
'content' => $chatContent
);
// 将关联数组转换为 JSON 格式
$jsonData = json_encode($data);
// 创建一个 cURL 会话
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
// 执行 cURL 请求并获取响应
$response = curl_exec($ch);
// 关闭 cURL 会话
curl_close($ch);
// 解析 JSON 响应
$decodedResponse = json_decode($response, true);
// 提取聊天回复
$reply = $decodedResponse['choices'][0]['text'];
// 输出聊天回复
echo $reply;
?>
请注意,上述代码中的 'your_api_key' 需要替换为您自己的 ChatGPT AI 网站的 API 密钥。此外,您还可以根据需要进行其他自定义,例如处理响应、错误处理等。
原文地址: https://www.cveoy.top/t/topic/qqAy 著作权归作者所有。请勿转载和采集!