我们在访问各种网站时都会遇到聊天机器人,其中一些在真人交互的背后运行,另一些则由人工智能驱动。
在本文中,我们将逐步使用 TensorFlow 和 JavaScript 构建一个简单的人工智能聊天机器人。聊天机器人将识别用户命令并以预定义的答案进行响应。
设置我们的项目
首先,我们为项目创建一个新目录并使用 npm 对其进行初始化,在开始此步骤之前确保您的系统上安装了 Node.js。
mkdir chatbot cd chatbot npm init -y
安装必要的软件包
我们将在我们的简单项目中使用以下 npm 包:
npm install @tensorflow/tfjs @tensorflow-models/universal sentence-encoder
创建意图
创建一个名为intents.js的文件来存储意图/命令,这些是聊天机器人将识别的用户输入类别(例如问候、产品查询、订单状态)。
// intents.js const intents = { greeting: ["hello", "hi", "hey", "good morning", "good evening", "howdy"], goodbye: ["bye", "goodbye", "see you later", "farewell", "catch you later"], thanks: ["thank you", "thanks", "much appreciated", "thank you very much"], product_inquiry: ["tell me about your products", "what do you sell?", "product information", "what can I buy?", "show me your products"], order_status: ["where is my order?", "order status", "track my order", "order tracking", "order update"], shipping_info: ["shipping information", "how do you ship?", "shipping methods", "delivery options", "how long does shipping take?"], return_policy: ["return policy", "how to return?", "return process", "can I return?", "returns"], payment_methods: ["payment options", "how can I pay?", "payment methods", "available payments"], support_contact: ["contact support", "how to contact support?", "customer support contact", "support info", "customer service contact"], business_hours: ["business hours", "working hours", "when are you open?", "opening hours", "store hours"] }; module.exports = { intents }
创建回复
创建另一个名为response.js的文件来存储预定义的响应,这些是聊天机器人根据识别的意图给出的预定义响应。
// responses.js const responses = { greeting: "Hello! How can I help you today?", goodbye: "Goodbye! Have a great day!", thanks: "You're welcome! If you have any other questions, feel free to ask.", product_inquiry: "We offer a variety of products including electronics, books, clothing, and more. How can I assist you further?", order_status: "Please provide your order ID, and I will check the status for you.", shipping_info: "We offer various shipping methods including standard, express, and next-day delivery. Shipping times depend on the method chosen and your location.", return_policy: "Our return policy allows you to return products within 30 days of purchase. Please visit our returns page for detailed instructions.", payment_methods: "We accept multiple payment methods including credit/debit cards, PayPal, and bank transfers. Please choose the method that suits you best at checkout.", support_contact: "You can contact our support team via email at support@example.com or call us at 1-800-123-4567.", business_hours: "Our business hours are Monday to Friday, 9 AM to 5 PM. We are closed on weekends and public holidays." }; module.exports = { responses };
加载 TensorFlow 和句子编码器
创建一个名为chatbot.js的主脚本文件并加载必要的库和模型,我们异步加载通用句子编码器模型,并在模型加载后启动聊天机器人。
// chatbot.js const tf = require('@tensorflow/tfjs'); const use = require('@tensorflow-models/universal-sentence-encoder'); const { intents } = require('./intents'); const { responses } = require('./responses'); const readline = require('readline'); // Load the Universal Sentence Encoder model let model; use.load().then((loadedModel) => { model = loadedModel; console.log("Model loaded"); startChatbot(); });
实现意图识别
添加一个函数来识别用户输入的意图,我们使用通用编码器将用户输入嵌入到高维向量中,然后根据意图跟踪最高相似度得分。
async function recognizeIntent(userInput) { const userInputEmb = await model.embed([userInput]); let maxScore = -1; let recognizedIntent = null; for (const [intent, examples] of Object.entries(intents)) { // Embedding the example phrases for each intent & Calculating similarity scores between the user input embedding and the example embeddings const examplesEmb = await model.embed(examples); const scores = await tf.matMul(userInputEmb, examplesEmb, false, true).data(); const maxExampleScore = Math.max(...scores); if (maxExampleScore > maxScore) { maxScore = maxExampleScore; recognizedIntent = intent; } } return recognizedIntent; }
生成响应
添加一个函数以根据识别的意图生成响应:
async function generateResponse(userInput) { const intent = await recognizeIntent(userInput); if (intent && responses[intent]) { return responses[intent]; } else { return "I'm sorry, I don't understand that. Can you please rephrase?"; } }
实现聊天机器人交互
最后,通过设置从命令行读取用户输入的接口来实现与聊天机器人的交互循环,提示用户输入并相应地生成响应:
function startChatbot() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log("Welcome to the customer service chatbot! Type 'quit' to exit."); rl.prompt(); rl.on('line', async (line) => { const userInput = line.trim(); if (userInput.toLowerCase() === 'quit') { console.log("Chatbot: Goodbye!"); rl.close(); return; } const response = await generateResponse(userInput); console.log(`Chatbot: ${response}`); rl.prompt(); }); }
这是 chatbot.js 的完整代码:
// chatbot.js const tf = require('@tensorflow/tfjs'); const use = require('@tensorflow-models/universal-sentence-encoder'); const { intents } = require('./intents'); const { responses } = require('./responses'); const readline = require('readline'); // Load the Universal Sentence Encoder model let model; use.load().then((loadedModel) => { model = loadedModel; console.log("Model loaded"); startChatbot(); }); async function recognizeIntent(userInput) { const userInputEmb = await model.embed([userInput]); let maxScore = -1; let recognizedIntent = null; for (const [intent, examples] of Object.entries(intents)) { const examplesEmb = await model.embed(examples); const scores = await tf.matMul(userInputEmb, examplesEmb, false, true).data(); const maxExampleScore = Math.max(...scores); if (maxExampleScore > maxScore) { maxScore = maxExampleScore; recognizedIntent = intent; } } return recognizedIntent; } async function generateResponse(userInput) { const intent = await recognizeIntent(userInput); if (intent && responses[intent]) { return responses[intent]; } else { return "I'm sorry, I don't understand that. Can you please rephrase?"; } } function startChatbot() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log("Welcome to the customer service chatbot! Type 'quit' to exit."); rl.prompt(); rl.on('line', async (line) => { const userInput = line.trim(); if (userInput.toLowerCase() === 'quit') { console.log("Chatbot: Goodbye!"); rl.close(); return; } const response = await generateResponse(userInput); console.log(`Chatbot: ${response}`); rl.prompt(); }); }
要运行聊天机器人,请执行 chatbot.js 文件:
node chatbot.js
瞧!我们的命令输出应该让聊天机器人运行:
在本文中,我们使用 TensorFlow 和 JavaScript 构建了一个简单的客户服务聊天机器人。虽然此实现很基础,但它为构建更复杂的聊天机器人提供了坚实的基础。您可以通过使用 AXIOS 集成 API、添加更多意图和响应或将其部署在 Web 平台上来扩展此项目。
编码愉快!
?? 了解更多关于我
?? 在 LinkedIn 上联系
?? 订阅我的博客
以上是如何使用 TensorFlow 和 JavaScript 构建基本聊天机器人的详细内容。更多信息请关注PHP中文网其他相关文章!