- 65浏览
- 2023-03-29
一、SDK实现
OpenAI的PHP SDK实现如下,其中ChatGPT使用的模型为gpt-3.5-turbo,如果已经有ChatGPT Plus,并申请到GPT-4的API权限,可以改为GPT-4的模型。
class class_openai
{
const ROOT_URL = "https://api.openai.com/";
//构造函数,获取Access Token
public function __construct($apikey = NULL)
{
$this->apikey = $apikey;
}
//文字完成 上下文
public function chat_completions_context($messages)
{
$field = array(
"model"=>"gpt-3.5-turbo",
// "temperature" => 0,
// "stream" => true,
"messages"=>$messages,
);
$url = self::ROOT_URL."v1/chat/completions";
$response = $this->http_request($url, json_encode($field));
$result = json_decode($response, true);
return trim($result["choices"][0]["message"]["content"]);
}
//图片完成
public function images_generations($prompt)
{
$field = array("prompt"=>$prompt,
"n"=>1,
"size"=>"256x256",
);
$url = self::ROOT_URL."v1/images/generations";
$response = $this->http_request($url, json_encode($field));
$result = json_decode($response, true);
return trim($result["data"][0]["url"]);
}
//HTTP请求(支持HTTP/HTTPS,支持GET/POST)
protected function http_request($url, $data = null)
{
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $this->apikey
);
var_dump($url);
var_dump($headers);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
上述两个接口中详细的参数说明,可以参考 https://platform.openai.com/docs/api-reference/chat 和 https://platform.openai.com/docs/api-reference/images二、调用方法
文本完成模型ChatGPT的调用方法如下:
$chat = new class_openai($apikey = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$prompt = "人生很痛苦,怎么办";
$messages = array(array('role' => "system", 'content' =>"你是专业的心理师"),
array('role' => "user", 'content' =>$prompt));
$result = $chat->chat_completions_context($messages);
图片生成模型DALL·E的调用方式如下
$chat = new class_openai($apikey = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$prompt = "美女";
$result1 = $chat->images_generations($prompt);
OpenAI API key的获取方法,可参考文章 OpenAI的API key获取方法版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、本文由会员转载自互联网,如果您是文章原创作者,请联系本站注明您的版权信息。