文、意如

看完這篇文章你可以學到:
一、註冊Open AI 帳號
二、取得ChatGPT API 金鑰
三、使用POSTMAN測試API是否正常可使用
四、編寫互動式網頁與ChatGPT API進行互動
在當今數位化世界中,人工智慧(AI)的應用正以驚人的速度改變我們的生活方式和業務運營,
其中,自然語言處理模型 ChatGPT 提供了一個強大的工具,使我們能夠在網站上與用戶進行智能對話。
本文將介紹如何無痛上手,在自己的網站上使用 ChatGPT,讓您的用戶體驗到更加互動且個性化的網站體驗。
完成檔如下:可以在自己的網頁中與ChatGPT AI 進行對話互動。

一、註冊Open AI帳號
進入OpenAI,建立一個帳號,也可以使用Google帳號來登入


二、取得ChatGPT API 金鑰
登入後點擊右上角的頭像
下拉選單選擇View API Keys
點擊按鈕:Create new secret key

再跳出視窗中,點選綠色複製按鈕,複製此API Key

這組API-Key開通後可以免費使用3個月,到個人的計算費用區,可以看到過期日

三、使用POSTMAN測試API是否正常可使用
3.1 下載和安裝POSTMAN工具
POSTMAN官網,安裝後畫面如下:

3.2 設定POSTMAN請求標頭和參數
1. 選擇傳送方式:POST
2. 輸入請求網址:https://api.openai.com/v1/chat/completions
3. 設定標頭:選擇Header頁籤
4. 設定參數:Authorization
5. 設定值Value: Bearer 輸入你的API key

接下來設定Body中參數,選擇raw後,在下方的框中輸入
Model為GPT的模組
Messages中的user為你的角色,以及content你要說的內容
輸入範例如下:
{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "哈囉!你好嗎"}
]
}

3.3 發送API請求並驗證回應
接下來就可以按下Send發出請求,此時ChatGPT會根據你的內容來做相對應的回答。

確定ChatGPT回答您的問題後,就可以開始編寫網頁與ChatGPT來做互動囉!
四、編寫互動式網頁與ChatGPT API進行互動
開啟記事本或任何的程式編輯器,將以下程式碼貼上後把API Key 換成您的就完成了,最後儲存檔案為mychat1.html。
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT Demo</title>
</head>
<body>
<center>
<h1>ChatGPT Demo</h1>
<div id="chat-container">
<div id="chat-log"></div>
<input type="text" id="user-input" placeholder="請輸入您的訊息" />
<button id="send-button">送出</button>
</div>
</center>
<script>
// ChatGPT API 請求函數
async function sendChatMessage(message) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY ' // 請將 YOUR_API_KEY 替換為您的 API 密鑰
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{ role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: message }]
})
});
const data = await response.json();
const assistantReply = data.choices[0].message.content;
appendMessage('assistant', assistantReply);
}
// 將對話內容加到聊天日誌中
function appendMessage(role, content) {
const chatLog = document.getElementById('chat-log');
const messageElement = document.createElement('div');
messageElement.classList.add(role);
messageElement.innerText = `${role}: ${content}`; //角色:聊天內容
chatLog.appendChild(messageElement);
}
// 當使用者按下「送出」按鈕時觸發
document.getElementById('send-button').addEventListener('click', function() {
const userInput = document.getElementById('user-input');
const userMessage = userInput.value;
appendMessage('user', userMessage);
userInput.value = '';
// 使用 ChatGPT API 發送內容
sendChatMessage(userMessage);
});
</script>
</body>
</html>
雙擊兩下剛剛建立的mychat1.html檔案,檔案會由瀏覽器自動開啟,接下來輸入內容後按下送出,就可以跟ChatGPT開始互動囉!

完成後效果:

當然以上的畫面與排版都還可以再細部調整,讓畫面更好看。
我們可以透過整合 ChatGPT,為您的網站帶來一個嶄新的互動層面,不僅可以提供即時的問答和支援,
還可以增加用戶參與度和留存率,這個強大的工具使得在網站上建立一個智能的虛擬助手變得輕而易舉。
現在就開始實施這個引人注目的功能,讓您的網站脫穎而出,為用戶提供一個與眾不同的體驗吧!
Yiru@Studio - 關於我 - 意如