php调用chatgpt3.5简单示例demo
$text=$_GET["q"];
if($_GET['bm']=="g"){
$text = iconv('GB2312', 'UTF-8', $text);
}
if($_GET['bm']=="u"){
$text = iconv('GB2312', 'UTF-8', $text);
}
$z=intval($_GET["z"]);
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer sk-";//换成自己key
$url="https://api.openai.com/v1/chat/completions";
$data = array(
'model' => 'gpt-3.5-turbo',
"max_tokens"=> $z,
'messages' => array(
array('role' => 'user', 'content' => '改写标题:'.$text),
),
);
$result=curl($url,$data,$headers);
$jieguo = json_decode($result, true);
//print_r($jieguo);
if($jieguo["choices"][0]["message"]["content"]){
print_r($result);
}else{
echo $text;
}
//var_dump(json_decode($result,true));exit;
function curl($url,$data,$headers){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //停止验证证书(一般只需要设置此项为false即可)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
//print_r($response);
//echo $response["choices"]["message"]["content"];
return $response;