首页 > web前端 > js教程 > 正文

如何使用 TensorFlow 和 JavaScript 构建基本聊天机器人

PHPz
发布: 2024-09-03 21:06:02
原创
965 人浏览过

我们在访问各种网站时都会遇到聊天机器人,其中一些在真人交互的背后运行,另一些则由人工智能驱动。

在本文中,我们将逐步使用 TensorFlow 和 JavaScript 构建一个简单的人工智能聊天机器人。聊天机器人将识别用户命令并以预定义的答案进行响应。

分步指南

设置我们的项目
首先,我们为项目创建一个新目录并使用 npm 对其进行初始化,在开始此步骤之前确保您的系统上安装了 Node.js。

mkdir chatbot
cd chatbot
npm init -y
登录后复制

安装必要的软件包

我们将在我们的简单项目中使用以下 npm 包:

  • tensorflow/tfjs:用于机器学习的 TensorFlow.js 库。
  • tensorflow-models/universal-sentence-encoder:用于意图识别的预训练通用句子编码器模型。
   npm install @tensorflow/tfjs @tensorflow-models/universal sentence-encoder
登录后复制
  1. 创建意图

    创建一个名为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 }
    
    登录后复制
  2. 创建回复

    创建另一个名为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 };
    
    登录后复制
  3. 加载 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();
    });
    
    登录后复制
  4. 实现意图识别

    添加一个函数来识别用户输入的意图,我们使用通用编码器将用户输入嵌入到高维向量中,然后根据意图跟踪最高相似度得分。

    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;
    }
    
    登录后复制
  5. 生成响应

    添加一个函数以根据识别的意图生成响应:

    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?";
      }
    }
    
    登录后复制
  6. 实现聊天机器人交互

    最后,通过设置从命令行读取用户输入的接口来实现与聊天机器人的交互循环,提示用户输入并相应地生成响应:

    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();
      });
    }
    
    登录后复制
  7. 要运行聊天机器人,请执行 chatbot.js 文件:

    node chatbot.js
    
    登录后复制

瞧!我们的命令输出应该让聊天机器人运行:

How to Build a Basic Chatbot Using TensorFlow and JavaScript

结论

在本文中,我们使用 TensorFlow 和 JavaScript 构建了一个简单的客户服务聊天机器人。虽然此实现很基础,但它为构建更复杂的聊天机器人提供了坚实的基础。您可以通过使用 AXIOS 集成 API、添加更多意图和响应或将其部署在 Web 平台上来扩展此项目。

编码愉快!

?? 了解更多关于我

?? 在 LinkedIn 上联系

?? 订阅我的博客

以上是如何使用 TensorFlow 和 JavaScript 构建基本聊天机器人的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!