PHP对接chatGPT代码,openai接口对接,php 实现chatGPT功能
前面已经说过了如何对接chatGPT的接口,下面是PHP的代码版本
<?php
define('OPENAI_API_KEY', '你的API KEY');
$prompt = $_GET['prompt'];
$response = sendPostRequest($prompt);
echo $response;
function sendPostRequest($prompt) {
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_URL => "https://api.openai.com/v1/completions", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode(
array( "prompt" => $prompt, "max_tokens" => 2048, "model" => "text-davinci-003" )
),
CURLOPT_HTTPHEADER =>
array( "Content-Type: application/json",
"Authorization: Bearer " . OPENAI_API_KEY ),
));
$response = curl_exec($curl); curl_close($curl); return $response; }
?>
测试使用
网址/chatgpt.php?prompt=你是谁
返回结果
网友评论