TensorFlow と JavaScript を使用して基本的なチャットボットを構築する方法

PHPz
リリース: 2024-09-03 21:06:02
オリジナル
877 人が閲覧しました

私たちはさまざまなサイトにアクセスするとチャットボットに遭遇しますが、その中には実際の人間とのやり取りの背後で動作するものもあれば、AI を利用しているものもあります。

この記事では、TensorFlow と JavaScript を使用して、AI を活用したシンプルなチャットボットを構築する手順を説明します。チャットボットはユーザーのコマンドを認識し、事前定義された回答で応答します。

ステップバイステップガイド

プロジェクトのセットアップ
まず、プロジェクト用に新しいディレクトリを作成し、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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!