Azure OpenAI 的接口和OpenAI有些不一样,大部分ChatGPT 客户端都是基于OpenAI的开发,以下是原生Azure OpenAI的实现方法。
class AzureOpenAI {
private $ApiKey;//Azure OpenAI Key
private $resourceName; // 自定义的域名
private $modelName; // 自定义的模型名称
private $apiVersion;//固定可不修改
public function __construct($ApiKey,$resourceName,$modelName,$apiVersion="2023-03-15-preview")
{
$this->ApiKey = $ApiKey;
$this->api = "https://$resourceName.openai.azure.com/openai/deployments/$modelName/chat/completions?api-version=$apiVersion";
}
private function response($data)
{
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$callback = json_decode($data);
if (isset($callback->choices[0]->message->content)){
$text = trim(str_replace("\n", "", $callback->choices[0]->message->content));
} elseif (isset($callback->error->message)) {
$text = "服务器返回错误信息:" . $callback->error->message;
} else {
$text = "服务器超时或返回异常消息。";
}
echo json_encode(["message" => $text,"data" => $text,"status" => "success",]);
}
private function curl($postData)
{
$ApiKey = $this->ApiKey;
$ch = curl_init();
$headers = [
'Content-Type: application/json',
'api-key:'.$ApiKey . ''
];
$postData = json_encode($postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL,$this->api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
return curl_exec($ch);
}
public function chat()
{
$context = json_decode($_POST['context'] ?: "[]" ) ?: [];
$post = [
"model" => "gpt-3.5-turbo",
"messages" => [],
];
if(!empty($context)){
$context = array_slice($context, -5);
foreach( $context as $message ){
$post['messages'][] = ['role' => 'user', 'content' => str_replace("\n", "\\n", $message[0])];
$post['messages'][] = ['role' => 'assistant', 'content' => str_replace("\n", "\\n", $message[1])];
}
}
$post['messages'][] = ['role' => 'user', 'content' => $_POST['message']];
$data = $this->curl($post);
return $this->response($data);
}
}
使用:
$AzureOpenAI = new AzureOpenAI($ApiKey,$resourceName,$modelName);
$data = $AzureOpenAI->chat();
echo $data;
转载原创文章请注明,转载自: LYLARES BLOG » PHP实现 Azure OpenAI ChatGPT 功能
忘了那个好友是你了……
下载插件最新版不能购买下载了吗?