一步步教你用 Laravel 对接 OpenAI 写一个在线智能聊天系统的 demo
那么废话多说直接上代码
先创建一个 Laravel 项目:
laravel new chatbot-demo
然后使用 Composer 安装 OpenAI 的官方 PHP SDK:
composer require openai/openai-api
在 .env 文件中存储 OpenAI API Key 和其他配置参数:
OPENAI_API_SECRET_KEY=your_api_secret_key_here
APP_NAME="Chatbot Demo"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000
...
在 routes/web.php 中定义路由映射:
use AppHttpControllersChatController;
Route::get('/', function () {
return view('chat');
});
Route::post('/chat', [ChatController::class, 'handle']);
在 app/Http/Controllers/ChatController.php 中编写逻辑代码:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use OpenAIApiClient as OpenAIClient;
class ChatController extends Controller
{
private $openai;
public function __construct()
{
$this->openai = new OpenAIClient(env('OPENAI_API_SECRET_KEY'));
}
public function handle(Request $request)
{
$sessionId = $request->session()->getId();
$userMessage = $request->input('message');
$conversation = Conversation::firstOrCreate(['session_id' => $sessionId]);
Message::create([
'conversation_id' => $conversation->id,
'text' => $userMessage,
'author' => 'user',
]);
$botMessage = $this->getBotMessage($conversation, $userMessage);
Message::create([
'conversation_id' => $conversation->id,
'text' => $botMessage,
'author' => 'bot',
]);
return response()->json(['message' => $botMessage]);
}
private function getBotMessage($conversation, $userMessage)
{
$prompt = "Conversation with {$conversation->id}: {$userMessage}nn";
$completions = $this->openai->completions->create([
'model' => 'davinci',
'prompt' => $prompt,
'temperature' => 0.5,
'max_tokens' => 80,
'n' => 1,
'stop' => 'n',
]);
return $completions->get()[0]->getText();
}
}
在 resources/views/chat.blade.php 中编写前端界面代码:
代码样式以及js请自行下载本地使用,远程可能国内网站某些反问不了
<!DOCTYPE html>
<html>
<head>
<title>Chatbot Demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$("#chat-form").submit(function(event){
event.preventDefault();
var userMessage = $("#chat-input").val().trim();
if (userMessage) {
$("#chat-input").val("");
$("#chat-box").append("<div class='row'><div class='col-md-6 offset-md-3 mb-2'><div class='card text-right'><div class='card-body'><p class='card-text'>" + userMessage + "</p></div></div></div></div>");
$.post("/chat", { message: userMessage }, function(data){
var botMessage = data.message;
$("#chat-box").append("<div class='row'><div class='col-md-6 offset-md-3 mb-2'><div class='card'><div class='card-body'><p class='card-text'>" + botMessage + "</p></div></div></div></div>");
});
}
});
});
</script>
</head>
<body>
<div class="container mt-5">
<h1 class="text-center">Chatbot Demo</h1>
<div id="chat-box"></div>
<form id="chat-form">
<div class="input-group">
<input type="text" class="form-control" id="chat-input" placeholder="Type your message here...">
<div class="input-group-append">
<button class="btn btn-primary" type="submit">Send</button>
</div>
</div>
</form>
</div>
</body>
</html>
代码仅供参考,实际开发中你要考虑的可能更多
版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!