- 75浏览
- 2022-10-21
首先,我们需要在config目录下创建一个新文件openai.php,这个文件用于存放我们的OpenAI API密钥和API URL。
<?php
// openai.php
return [
'api_key' => 'YOUR_API_KEY',
'api_url' => 'https://api.openai.com/v1/',
];
请将YOUR_API_KEY替换为你在OpenAI网站上获取的API密钥。接下来,我们可以创建一个ChatGPT类来处理调用OpenAI API。我们将这个类放在app\utils目录下。
<?php
// app\utils\ChatGPT.php
namespace app\utils;
use think\facade\Config;
use think\facade\Log;
use GuzzleHttp\Client;
class ChatGPT {
private $client;
private $api_key;
private $api_url;
public function __construct()
{
$this->client = new Client();
$this->api_key = Config::get('openai.api_key');
$this->api_url = Config::get('openai.api_url');
}
public function sendMessage($message)
{
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->api_key,
];
$params = [
'prompt' => $message,
'max_tokens' => 150,
'n' => 1,
'stop' => ['\n'],
];
try {
$response = $this->client->post($this->api_url . 'engines/davinci-codex/completions', [
'headers' => $headers,
'json' => $params,
]);
$data = json_decode($response->getBody(), true);
return $data['choices'][0]['text'];
} catch (\Exception $e) {
Log::error($e->getMessage());
}
return '';
}
}
这个类的主要作用是调用OpenAI API来发送消息并返回机器人的回复。在这里,我们使用了GuzzleHttp库来进行HTTP请求。我们还从Config中获取了我们之前定义的API密钥和API URL。
接下来,我们可以在Controller中使用这个ChatGPT类。以下是一个简单的例子,我们将ChatGPT类注入到index方法中,并将用户输入的消息传递给sendMessage()方法。
<?php
// app\controller\Index.php
namespace app\controller;
use think\facade\View;
use think\Request;
use app\utils\ChatGPT;
class Index
{
public function index()
{
return View::fetch();
}
public function chat(Request $request)
{
$message = $request->post('message');
$chatbot = new ChatGPT();
$response = $chatbot->sendMessage($message);
return json(['message' => $response]);
}
}
最后,我们需要在前端页面上调用chat()方法,并将用户输入的消息通过POST请求发送给chat()方法。以下是一个简单的例子。
<!DOCTYPE html>
<html>
<head>
<title>Chat GPT</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<style type="text/css">
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #f7f7f7;
}
.container {
width: 100%;
max-width: 600px;
margin: 0 auto;
padding: 20px;
box-sizing: border-box;
background-color: #fff;
border-radius: 5px;
box-shadow: 0px 0px 10px #ddd;
}
h1 {
margin: 0;
font-size: 24px;
font-weight: bold;
text-align: center;
}
.chatbox {
height: 400px;
overflow-y: scroll;
margin-bottom: 10px;
padding: 10px;
box-sizing: border-box;
background-color: #f7f7f7;
border-radius: 5px;
box-shadow: inset 0px 0px 10px #ddd;
}
.inputbox {
display: flex;
flex-wrap: wrap;
align-items: center;
margin-bottom: 10px;
}
.inputbox input[type="text"] {
flex-grow: 1;
padding: 10px;
box-sizing: border-box;
background-color: #fff;
border: none;
border-radius: 5px;
box-shadow: 0px 0px 10px #ddd;
font-size: 16px;
margin-right: 10px;
}
.inputbox button[type="submit"] {
padding: 10px;
box-sizing: border-box;
background-color: #007bff;
border: none;
border-radius: 5px;
color: #fff;
text-transform: uppercase;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s ease;
-webkit-transition: background-color 0.3s ease;
-moz-transition: background-color 0.3s ease;
-o-transition: background-color 0.3s ease;
}
.inputbox button[type="submit"]:hover {
background-color: #0062cc;
}
.message-wrapper {
display: flex;
justify-content: flex-start;
align-items: center;
margin-bottom: 10px;
}
.message-bubble {
padding: 10px;
box-sizing: border-box;
background-color: #007bff;
border-radius: 5px;
color: #fff;
max-width: 50%;
word-wrap: break-word;
}
.bot .message-wrapper {
justify-content: flex-end;
}
.bot .message-bubble {
background-color: #ddd;
}
</style>
</head>
<body>
<div class="container">
<h1>Chat GPT</h1>
<div class="chatbox" id="chatbox"></div>
<form id="chatForm">
<div class="inputbox">
<input type="text" name="message" id="message" placeholder="Type your message here...">
<button type="submit">Send</button>
</div>
</form>
</div>
<script type="text/javascript">
const chatForm = document.getElementById('chatForm');
const chatbox = document.getElementById('chatbox');
chatForm.addEventListener('submit', event => {
event.preventDefault();
const messageInput = document.getElementById('message');
const message = messageInput.value;
if (message != '') {
displayMessage(message, 'user');
messageInput.value = '';
axios.post('/index.php/Index/chat', {
message: message,
})
.then(response => {
const botMessage = response.data.message;
displayMessage(botMessage, 'bot');
})
.catch(error => console.log(error));
}
return false;
});
function displayMessage(message, userType) {
const messageWrapper = document.createElement('div');
const messageBubble = document.createElement('div');
messageBubble.textContent = message;
messageBubble.classList.add('message-bubble');
messageWrapper.classList.add('message-wrapper');
messageWrapper.classList.add(userType);
messageWrapper.appendChild(messageBubble);
chatbox.appendChild(messageWrapper);
chatbox.scrollTop = chatbox.scrollHeight;
}
</script>
</body>
</html>
在这个页面中,我们通过监听表单的submit事件来调用chat()方法,并使用Axios库将用户输入的消息发送到服务器端的chat()方法。我们还定义了一个displayMessage()函数来在聊天框中显示发送和接收的消息。注意:你需要在路由中定义/chat路由,并将其指向Index控制器的chat()方法。 
版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、本文由会员转载自互联网,如果您是文章原创作者,请联系本站注明您的版权信息。