
了解 Rest API 開發(fā)中的 HTTP 方法
exports.handler = async (event) => {
const userMessage = JSON.parse(event.body).message;
const response = await getChatbotResponse(userMessage);
return {
statusCode: 200,
body: JSON.stringify({ response }),
};
};
const getChatbotResponse = async (message) => {
const apiUrl = 'https://api.example.com/chatbot'; // Replace with your AI model endpoint
const apiKey = 'your-api-key'; // Replace with your API key
try {
const response = await axios.post(apiUrl, { message }, {
headers: { 'Authorization': Bearer ${apiKey}
},
});
return response.data.reply;
} catch (error) {
console.error('Error fetching response:', error);
return 'Sorry, there was an error processing your request.';
}
};
創(chuàng)建一個新的 HTML 文件,例如index.html
,使用以下代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot</title>
<style>
#chat {
max-width: 600px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
}
#messages {
height: 300px;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 10px;
}
#input {
width: calc(100% - 22px);
padding: 10px;
margin: 10px 0;
}
</style>
</head>
<body>
<div id="chat">
<div id="messages"></div>
<input type="text" id="input" placeholder="Type a message" />
</div>
<script>
const input = document.getElementById('input');
const messages = document.getElementById('messages');
input.addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
const message = input.value;
input.value = '';
appendMessage('You', message);
const response = await fetch('https://your-api-endpoint.com', { // Replace with your API Gateway endpoint
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
const data = await response.json();
appendMessage('Chatbot', data.response);
}
});
function appendMessage(sender, text) {
const messageElem = document.createElement('div');
messageElem.textContent = ${sender}: ${text}
;
messages.appendChild(messageElem);
}
</script>
</body>
</html>
測試前端
index.html
在 Web 瀏覽器中打開該文件。您可以index.html
在任何網(wǎng)絡(luò)托管服務(wù)上托管該文件,甚至可以使用 GitHub Pages 進(jìn)行快速部署。
通過本教程,您已經(jīng)構(gòu)建了一個實時 AI 聊天機器人并使用無服務(wù)器架構(gòu)進(jìn)行了部署。這種方法為部署 AI 驅(qū)動的服務(wù)提供了一種可擴展且經(jīng)濟高效的解決方案,而 AWS Lambda 和簡單前端的組合則展示了如何將現(xiàn)代技術(shù)用于實際應(yīng)用。
通過集成更高級的 AI 模型或增強用戶界面,您可以進(jìn)一步自定義聊天機器人。祝您編碼愉快!
原文鏈接:https://dzone.com/articles/real-time-ai-powered-chatbot-with-serverless-architecture