PHP简单ChatGPT API对接方法

Komisoft / 2023-08-20 / 原文

<?php
$chat = $_GET['chat'];

// 设置参数
$data = array(
    'model' => 'gpt-3.5-turbo',
    'messages' => array(
        array('role' => 'system', 'content' => 'Your_GPT_Tips'),
        array('role' => 'user', 'content' => $chat),
    ),
);

// 将数据转换为 JSON
$json = json_encode($data);

// 设置请求头
$headers = array(
    'Content-Type: application/json',
    'Authorization: Bearer Your_API_Key', // 替换为您的 OpenAI API 密钥
);

// 发送请求
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
curl_close($ch);

// 处理响应
$result = json_decode($response, true);
$reply = $result['choices'][0]['message']['content'];

echo $reply;

?>

使用了PHP的Curl,调用了GPT-3.5-Turbo模型来提问。