OpenAI API PHP Class for Chat Completions and Image Generation
{"title":"OpenAI API PHP Class for Chat Completions and Image Generation","description":"This PHP class provides a simple interface for interacting with the OpenAI API, allowing you to generate text with chat completions and create images using the image generation API. ","keywords":"OpenAI API, PHP, chat completions, image generation, GPT-3, API wrapper","content":"{"const ROOT_URL = "https://api.openai.com/",\n \n //构造函数,获取Access Token\n public function __construct($apikey = NULL)\n {\n $this->apikey = $apikey;\n }\n\n //文字完成 上下文\n public function chat_completions_context($messages)\n {\n $field = array(\n "model":"gpt-3.5-turbo",\n // "temperature" => 0,\n // "stream" => true,\n "messages":$messages,\n );\n $url = self::ROOT_URL."v1/chat/completions";\n \n $response = $this->http_request($url, json_encode($field));\n $result = json_decode($response, true);\n return trim($result["choices"][0]["message"] ["content"]);\n }\n\n\t//图片完成\n public function images_generations($prompt)\n {\n $field = array("prompt":$prompt,\n "n":1,\n "size":"256x256",\n );\n $url = self::ROOT_URL."v1/images/generations";\n $response = $this->http_request($url, json_encode($field));\n $result = json_decode($response, true);\n return trim($result["data"][0]["url"]);\n }\n\n\n //HTTP请求(支持HTTP/HTTPS,支持GET/POST)\n protected function http_request($url, $data = null)\n {\n $headers = array(\n "Content-Type: application/json",\n "Authorization: Bearer " . $this->apikey\n );\n var_dump($url);\n var_dump($headers);\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_TIMEOUT, 120);\n curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);\n // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);\n // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);\n if (!empty($data)){\n curl_setopt($ch, CURLOPT_POST, 1);\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n }\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n $output = curl_exec($ch);\n curl_close($ch);\n return $output;\n\n }\n\n}\n用上面这个接口写一段GPT问答PHP网页代码,主要作用是,第一个输入框内的值为key,第二个输入框内的值为提出的问题,提交后,第三个输入框显示返回生成的回答内容: \"system\", \"content\" => \"You are a helpful assistant.\"),\n array(\"role\" => \"user\", \"content\" => $question)\n );\n\n \/\/ Call the chat_completions_context method to get the answer\n $answer = $openai->chat_completions_context($messages);\n}\n?>\n\n\n\n
\n\n <label for="question">Question:\n <input type="text" id="question" name="question" required>
\n <input type="submit" name="submit" value="Submit">\n \n \n <label for="answer">Answer:\n <input type="text" id="answer" name="answer" value="" disabled>\n \n\n\n
原文地址: https://www.cveoy.top/t/topic/pUbW 著作权归作者所有。请勿转载和采集!