很多小伙伴想对接自己的chatgpt机器人,租和香港服务器,然后对接到自己的APP或者软件里面,但是肯定需要一个后端的程序去处理,其实这个工具就足够用了,你提交信息它就会返回对应的内容,下面是代码
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// 检查是否有 GET 请求
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
// 获取 GET 请求参数
$userQuery = isset($_GET['query']) ? $_GET['query'] : '';
// 替换为你的实际 API 密钥
$apiKey = '您的key';
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
"model" => "gpt-3.5-turbo",
"messages" => [
["role" => "system", "content" => "你是 ChatGPT,一个友好、有帮助的 AI"],
["role" => "user", "content" => $userQuery],
],
]),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"Authorization: Bearer {$apiKey}",
],
]);
$response = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Request Error:' . curl_error($curl);
} else {
// 解码响应
$responseDecoded = json_decode($response, true);
// 只返回内容
if (isset($responseDecoded['choices'][0]['message']['content'])) {
echo $responseDecoded['choices'][0]['message']['content'];
} else {
echo 'Error: No response content.';
}
}
curl_close($curl);
} else {
echo 'Invalid request method.';
}
?>
比如我访问:http://www.xkrj5.com/xxx/ai.php?query=你在干嘛
然后它就会自动返回下图所示的内容
|