用thinkphp6对接Openai实现ai聊天功能
把今天在对接openai得过程分享给大家希望对你有所帮助,后续会出整套代码开源
在controller目录下创建ChatController.php文件,处理聊天请求。
<?php
//技术QQ:1032904660
namespace appcontroller;
use thinkfacadeView;
use thinkfacadeConfig;
use thinkfacadeRequest;
use GuzzleHttpClient;
class ChatController
{
public function index()
{
return View::fetch('index');
}
public function chat()
{
// 获取用户输入的消息
$message = Request::post('message');
// 调用openai的API接口
$client = new Client();
$response = $client->request('POST', 'https://api.openai.com/v1/engines/davinci-codex/completions', [
'headers' => [
'Authorization' => 'Bearer ' . Config::get('openai.api_key'),
'Content-Type' => 'application/json'
],
'json' => [
'prompt' => $message,
'max_tokens' => 50,
'temperature' => 0.5,
'n' => 1,
'stop' => ['n']
]
]);
// 获取openai的响应
$data = json_decode($response->getBody(), true);
$answer = $data['choices'][0]['text'];
// 返回openai的响应
return json(['answer' => $answer]);
}
}
在view目录下创建index.html文件,创建聊天界面。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OpenAI Chat</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.0/css/bootstrap.min.css">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-header">
OpenAI Chat
</div>
<div class="card-body">
<ul class="list-group" id="chat-list">
<li class="list-group-item text-center">Start chatting...</li>
</ul>
<form id="chat-form">
<div class="input-group mt-3">
<input type="text" class="form-control" id="message" placeholder="Type your message here...">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
// 提交聊天请求
$('#chat-form').submit(function (event) {
event.preventDefault();
var message = $('#message').val();
$.post('/chat', {message: message}, function (data) {
// 显示openai的响应
var answer = data.answer;
$('#chat-list').append('<li class="list-group-item">' + message + '</li>');
$('#chat-list').append('<li class="list-group-item">' + answer + '</li>');
$('#message').val('');
});
});
});
</script>
</body>
</html>
这里斜杆没有了给大家补出来
use thinkfacadeView;
use thinkfacadeConfig;
use thinkfacadeRequest;
use GuzzleHttpClient;
是不是很简单呢,快动起来!!!!!!!嘀嘀嘀
转载得朋友请注明出处谢谢!
版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!