環境 : laravel + php8.1
第一步 : 註冊openai
第二步 : 登入後選擇API 最右邊這個按進去
第三步 : 新增金鑰
- 從右上方你的頭像按進去
- 新增一個API Keys
第四步 : 將API Keys 放進laravel 專案中
第五步 : 設定chat聊天頁面與controller的route
第六步 : 設定聊天頁面
- 在resources底下的views 中開一個chat.blade.php
- 以下為chat.blade.php 內容
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>聊天</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
#chat-container {
width: 70%; /* Updated the width */
}
#chatbox {
width: 100%;
height: 600px; /* Increased the height */
border: 1px solid #ccc;
padding: 10px;
overflow-y: scroll;
margin-bottom: 15px;
background-color: #fff;
}
.message {
margin-bottom: 10px;
}
.assistant {
color: blue;
}
.you {
color: green;
}
.input-group {
width: 100%;
}
#loading {
display: none;
}
</style>
</head>
<body>
<div id="chat-container">
<h1>聊天</h1>
<div id="chatbox">
<p class="message assistant">助理:你好,需要什麼幫忙呢?</p>
</div>
<div class="input-group">
<input type="text" id="message" class="form-control">
<div class="input-group-append">
<button id="send" class="btn btn-outline-secondary" type="button" disabled>
<i id="send-icon" class="fas fa-paper-plane"></i>
<span id="loading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#message').on('input', function() {
// Enable the button if input is not empty
$('#send').prop('disabled', !$(this).val());
});
$('#send').click(function(){
// disable the button while processing
$(this).prop('disabled', true);
$('#send-icon').hide();
$('#loading').show();
var message = $('#message').val();
$.ajax({
type: "POST",
url: "{{ route('chat.process') }}",
data: JSON.stringify({
message: message,
_token: '{{ csrf_token() }}',
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#chatbox').append('<p class="message you">你:' + message + '</p>');
$('#chatbox').append('<p class="message assistant">AI' + data.reply + '</p>');
$('#message').val('');
$('#chatbox').scrollTop($('#chatbox')[0].scrollHeight); // Scroll to bottom after new message is added
},
complete: function() {
// re-enable the button when request is complete
$('#send').prop('disabled', false);
$('#send-icon').show();
$('#loading').hide();
}
});
});
});
</script>
</body>
</html>
第七步 : 設定controller
- 在controller中新增一個chatController.php的檔案
- 以下是chatController.php的內容
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class ChatController extends Controller
{
public function index()
{
return view('chat');
}
public function process_request(Request $request)
{
// 從請求或session中獲取先前的訊息
$messages = $request->session()->get('messages', [
[
'role' => 'system',
'content' => 'You are a helpful assistant.',
]
]);
$user_question = $request->input('message');
// 新增使用者的訊息到訊息列表
$messages[] = [
'role' => 'user',
'content' => $user_question,
];
// 發送請求給OpenAI API
$result = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . env('OPENAI_API_KEY')
])->post('https://api.openai.com/v1/chat/completions', [
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
]);
// 取出AI助手的回答
$response_data = $result->json();
$assistant_message = end($response_data['choices'])['message']['content'];
// 新增助手的訊息到訊息列表
$messages[] = [
'role' => 'assistant',
'content' => $assistant_message,
];
// 將訊息列表存回session
$request->session()->put('messages', $messages);
// 將答案回傳
return response()->json([
'reply' => $assistant_message,
]);
}
}
第八步 : 打開http://127.0.0.1:8000/chat
- 以下為簡易chat聊天頁面
接著就可以開始跟助理聊天了 👏
以上為個人實際經驗分享,若有不同的情況發生,可以以下留言討論
搶先發佈留言