');mask-image:url('data:image/svg+xml;charset=utf-8,');width:16px}.markdown-body details,.markdown-body figcaption,.markdown-body figure{display:block}.markdown-body summary{display:list-item}.markdown-body [hidden]{display:none!important}.markdown-body a{background-color:transparent;color:#fed304;text-decoration:none}.markdown-body a:active,.markdown-body a:hover{outline-width:0}.markdown-body abbr[title]{border-bottom:none;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.markdown-body b,.markdown-body strong{font-weight:600}.markdown-body dfn{font-style:italic}.markdown-body h1{border-bottom:1px solid var(--color-border-muted);font-size:2em;font-weight:600;margin:.67em 0;padding-bottom:.3em}.markdown-body mark{background-color:var(--color-attention-subtle);color:var(--color-text-primary)}.markdown-body small{font-size:90%}.markdown-body sub,.markdown-body sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}.markdown-body sub{bottom:-.25em}.markdown-body sup{top:-.5em}.markdown-body img{background-color:var(--color-canvas-default);border-style:none;box-sizing:content-box;max-width:100%}.markdown-body code,.markdown-body kbd,.markdown-body pre,.markdown-body samp{font-family:monospace,monospace;font-size:1em}.markdown-body figure{margin:1em 40px}.markdown-body hr{background:transparent;background-color:var(--color-border-default);border:0;box-sizing:content-box;height:.25em;margin:24px 0;overflow:hidden;padding:0}.markdown-body input{font:inherit;font-family:inherit;font-size:inherit;line-height:inherit;margin:0;overflow:visible}.markdown-body [type=button],.markdown-body [type=reset],.markdown-body [type=submit]{-webkit-appearance:button}.markdown-body [type=button]::-moz-focus-inner,.markdown-body [type=reset]::-moz-focus-inner,.markdown-body [type=submit]::-moz-focus-inner{border-style:none;padding:0}.markdown-body [type=button]:-moz-focusring,.markdown-body [type=reset]:-moz-focusring,.markdown-body [type=submit]:-moz-focusring{outline:1px dotted ButtonText}.markdown-body [type=checkbox],.markdown-body [type=radio]{box-sizing:border-box;padding:0}.markdown-body [type=number]::-webkit-inner-spin-button,.markdown-body [type=number]::-webkit-outer-spin-button{height:auto}.markdown-body [type=search]{-webkit-appearance:textfield;outline-offset:-2px}.markdown-body [type=search]::-webkit-search-cancel-button,.markdown-body [type=search]::-webkit-search-decoration{-webkit-appearance:none}.markdown-body ::-webkit-input-placeholder{color:inherit;opacity:.54}.markdown-body ::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}.markdown-body a:hover{text-decoration:underline}.markdown-body hr:after,.markdown-body hr:before{content:"";display:table}.markdown-body hr:after{clear:both}.markdown-body table{border-collapse:collapse;border-spacing:0;display:block;max-width:100%;overflow:auto;width:-webkit-max-content;width:max-content}.markdown-body td,.markdown-body th{padding:0}.markdown-body details summary{cursor:pointer}.markdown-body details:not([open])>:not(summary){display:none!important}.markdown-body kbd{background-color:var(--color-canvas-subtle);border-bottom-color:var(--color-neutral-muted);border:1px solid var(--color-neutral-muted);border-radius:6px;box-shadow:inset 0 -1px 0 var(--color-neutral-muted);color:var(--color-fg-default);display:inline-block;font:11px ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;line-height:10px;padding:3px 5px;vertical-align:middle}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{font-weight:600;line-height:1.25;margin-bottom:16px;margin-top:24px}.markdown-body h2{border-bottom:1px solid var(--color-border-muted);font-size:1.5em;font-weight:600;padding-bottom:.3em}.markdown-body h3{font-size:1.25em;font-weight:600}.markdown-body h4{font-size:1em;font-weight:600}.markdown-body h5{font-size:.875em;font-weight:600}.markdown-body h6{color:var(--color-fg-muted);font-size:.85em;font-weight:600}.markdown-body p{margin-bottom:10px;margin-top:0}.markdown-body blockquote{background:hsla(215,8%,47%,.4);border-left:.25em solid var(--color-border-default);border-radius:10px;color:#fff;margin:0;padding:0 1em}.markdown-body ol,.markdown-body ul{margin-bottom:0;margin-top:0;padding-left:2em}.markdown-body ol ol,.markdown-body ul ol{list-style-type:lower-roman}.markdown-body ol ol ol,.markdown-body ol ul ol,.markdown-body ul ol ol,.markdown-body ul ul ol{list-style-type:lower-alpha}.markdown-body dd{margin-left:0}.markdown-body code,.markdown-body pre,.markdown-body tt{font-family:ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;font-size:12px}.markdown-body pre{word-wrap:normal;margin-bottom:0;margin-top:0}.markdown-body .octicon{fill:currentColor;display:inline-block;overflow:visible!important;vertical-align:text-bottom}.markdown-body ::-webkit-input-placeholder{color:var(--color-fg-subtle);opacity:1}.markdown-body ::placeholder{color:var(--color-fg-subtle);opacity:1}.markdown-body input::-webkit-inner-spin-button,.markdown-body input::-webkit-outer-spin-button{-webkit-appearance:none;appearance:none;margin:0}.markdown-body .pl-c{color:var(--color-prettylights-syntax-comment)}.markdown-body .pl-c1,.markdown-body .pl-s .pl-v{color:var(--color-prettylights-syntax-constant)}.markdown-body .pl-e,.markdown-body .pl-en{color:var(--color-prettylights-syntax-entity)}.markdown-body .pl-s .pl-s1,.markdown-body .pl-smi{color:var(--color-prettylights-syntax-storage-modifier-import)}.markdown-body .pl-ent{color:var(--color-prettylights-syntax-entity-tag)}.markdown-body .pl-k{color:var(--color-prettylights-syntax-keyword)}.markdown-body .pl-pds,.markdown-body .pl-s,.markdown-body .pl-s .pl-pse .pl-s1,.markdown-body .pl-sr,.markdown-body .pl-sr .pl-cce,.markdown-body .pl-sr .pl-sra,.markdown-body .pl-sr .pl-sre{color:var(--color-prettylights-syntax-string)}.markdown-body .pl-smw,.markdown-body .pl-v{color:var(--color-prettylights-syntax-variable)}.markdown-body .pl-bu{color:var(--color-prettylights-syntax-brackethighlighter-unmatched)}.markdown-body .pl-ii{background-color:var(--color-prettylights-syntax-invalid-illegal-bg);color:var(--color-prettylights-syntax-invalid-illegal-text)}.markdown-body .pl-c2{background-color:var(--color-prettylights-syntax-carriage-return-bg);color:var(--color-prettylights-syntax-carriage-return-text)}.markdown-body .pl-sr .pl-cce{color:var(--color-prettylights-syntax-string-regexp);font-weight:700}.markdown-body .pl-ml{color:var(--color-prettylights-syntax-markup-list)}.markdown-body .pl-mh,.markdown-body .pl-mh .pl-en,.markdown-body .pl-ms{color:var(--color-prettylights-syntax-markup-heading);font-weight:700}.markdown-body .pl-mi{color:var(--color-prettylights-syntax-markup-italic);font-style:italic}.markdown-body .pl-mb{color:var(--color-prettylights-syntax-markup-bold);font-weight:700}.markdown-body .pl-md{background-color:var(--color-prettylights-syntax-markup-deleted-bg);color:var(--color-prettylights-syntax-markup-deleted-text)}.markdown-body .pl-mi1{background-color:var(--color-prettylights-syntax-markup-inserted-bg);color:var(--color-prettylights-syntax-markup-inserted-text)}.markdown-body .pl-mc{background-color:var(--color-prettylights-syntax-markup-changed-bg);color:var(--color-prettylights-syntax-markup-changed-text)}.markdown-body .pl-mi2{background-color:var(--color-prettylights-syntax-markup-ignored-bg);color:var(--color-prettylights-syntax-markup-ignored-text)}.markdown-body .pl-mdr{color:var(--color-prettylights-syntax-meta-diff-range);font-weight:700}.markdown-body .pl-ba{color:var(--color-prettylights-syntax-brackethighlighter-angle)}.markdown-body .pl-sg{color:var(--color-prettylights-syntax-sublimelinter-gutter-mark)}.markdown-body .pl-corl{color:var(--color-prettylights-syntax-constant-other-reference-link);text-decoration:underline}.markdown-body [data-catalyst]{display:block}.markdown-body g-emoji{font-family:Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;font-size:1em;font-style:normal!important;font-weight:400;line-height:1;vertical-align:-.075em}.markdown-body g-emoji img{height:1em;width:1em}.markdown-body:after,.markdown-body:before{content:"";display:table}.markdown-body:after{clear:both}.markdown-body>:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a:not([href]){color:inherit;text-decoration:none}.markdown-body .absent{color:var(--color-danger-fg)}.markdown-body .anchor{float:left;line-height:1;margin-left:-20px;padding-right:4px}.markdown-body .anchor:focus{outline:none}.markdown-body blockquote,.markdown-body details,.markdown-body dl,.markdown-body ol,.markdown-body p,.markdown-body pre,.markdown-body table,.markdown-body ul{margin-bottom:16px;margin-top:0}.markdown-body blockquote>:first-child{margin-top:0}.markdown-body blockquote>:last-child{margin-bottom:0}.markdown-body sup>a:before{content:"["}.markdown-body sup>a:after{content:"]"}.markdown-body h1 .octicon-link,.markdown-body h2 .octicon-link,.markdown-body h3 .octicon-link,.markdown-body h4 .octicon-link,.markdown-body h5 .octicon-link,.markdown-body h6 .octicon-link{color:var(--color-fg-default);vertical-align:middle;visibility:hidden}.markdown-body h1:hover .anchor,.markdown-body h2:hover .anchor,.markdown-body h3:hover .anchor,.markdown-body h4:hover .anchor,.markdown-body h5:hover .anchor,.markdown-body h6:hover .anchor{text-decoration:none}.markdown-body h1:hover .anchor .octicon-link,.markdown-body h2:hover .anchor .octicon-link,.markdown-body h3:hover .anchor .octicon-link,.markdown-body h4:hover .anchor .octicon-link,.markdown-body h5:hover .anchor .octicon-link,.markdown-body h6:hover .anchor .octicon-link{visibility:visible}.markdown-body h1 code,.markdown-body h1 tt,.markdown-body h2 code,.markdown-body h2 tt,.markdown-body h3 code,.markdown-body h3 tt,.markdown-body h4 code,.markdown-body h4 tt,.markdown-body h5 code,.markdown-body h5 tt,.markdown-body h6 code,.markdown-body h6 tt{font-size:inherit;padding:0 .2em}.markdown-body ol.no-list,.markdown-body ul.no-list{list-style-type:none;padding:0}.markdown-body ol[type="1"]{list-style-type:decimal}.markdown-body ol[type=a]{list-style-type:lower-alpha}.markdown-body ol[type=i]{list-style-type:lower-roman}.markdown-body div>ol:not([type]){list-style-type:decimal}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-bottom:0;margin-top:0}.markdown-body li>p{margin-top:16px}.markdown-body li+li{margin-top:.25em}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:1em;font-style:italic;font-weight:600;margin-top:16px;padding:0}.markdown-body dl dd{margin-bottom:16px;padding:0 16px}.markdown-body table th{font-weight:600}.markdown-body table td,.markdown-body table th{border:1px solid var(--color-border-default);padding:6px 13px}.markdown-body table tr{background-color:var(--color-canvas-default);border-top:1px solid var(--color-border-muted)}.markdown-body table tr:nth-child(2n){background-color:var(--color-canvas-subtle)}.markdown-body table img{background-color:transparent}.markdown-body img[align=right]{padding-left:20px}.markdown-body img[align=left]{padding-right:20px}.markdown-body .emoji{background-color:transparent;max-width:none;vertical-align:text-top}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{border:1px solid var(--color-border-default);display:block;float:left;margin:13px 0 0;overflow:hidden;padding:7px;width:auto}.markdown-body span.frame span img{display:block;float:left}.markdown-body span.frame span span{clear:both;color:var(--color-fg-default);display:block;padding:5px 0 0}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}.markdown-body span.align-center span img{margin:0 auto;text-align:center}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}.markdown-body span.align-right span img{margin:0;text-align:right}.markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}.markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}.markdown-body code,.markdown-body tt{background-color:var(--color-neutral-muted);border-radius:6px;font-size:85%;margin:0;padding:.2em .4em}.markdown-body code br,.markdown-body tt br{display:none}.markdown-body del code{text-decoration:inherit}.markdown-body pre code{font-size:100%}.markdown-body pre>code{background:transparent;border:0;margin:0;padding:0;white-space:pre;word-break:normal}.markdown-body .highlight{margin-bottom:16px}.markdown-body .highlight pre{margin-bottom:0;word-break:normal}.markdown-body .highlight pre,.markdown-body pre{background-color:var(--color-canvas-subtle);border-radius:6px;font-size:85%;line-height:1.45;overflow:auto;padding:16px}.markdown-body pre code,.markdown-body pre tt{word-wrap:normal;background-color:transparent;border:0;display:inline;line-height:inherit;margin:0;max-width:auto;overflow:visible;padding:0}.markdown-body .csv-data td,.markdown-body .csv-data th{font-size:12px;line-height:1;overflow:hidden;padding:5px;text-align:left;white-space:nowrap}.markdown-body .csv-data .blob-num{background:var(--color-canvas-default);border:0;padding:10px 8px 9px;text-align:right}.markdown-body .csv-data tr{border-top:0}.markdown-body .csv-data th{background:var(--color-canvas-subtle);border-top:0;font-weight:600}.markdown-body .footnotes{border-top:1px solid var(--color-border-default);color:var(--color-fg-muted);font-size:12px}.markdown-body .footnotes ol{padding-left:16px}.markdown-body .footnotes li{position:relative}.markdown-body .footnotes li:target:before{border:2px solid var(--color-accent-emphasis);border-radius:6px;bottom:-8px;content:"";left:-24px;pointer-events:none;position:absolute;right:-8px;top:-8px}.markdown-body .footnotes li:target{color:var(--color-fg-default)}.markdown-body .footnotes .data-footnote-backref g-emoji{font-family:monospace}.markdown-body .task-list-item{list-style-type:none}.markdown-body .task-list-item label{font-weight:400}.markdown-body .task-list-item.enabled label{cursor:pointer}.markdown-body .task-list-item+.task-list-item{margin-top:3px}.markdown-body .task-list-item .handle{display:none}.markdown-body .task-list-item-checkbox{margin:0 .2em .25em -1.6em;vertical-align:middle}.markdown-body .contains-task-list:dir(rtl) .task-list-item-checkbox{margin:0 -1.6em .25em .2em}.markdown-body ::-webkit-calendar-picker-indicator{-webkit-filter:invert(50%);filter:invert(50%)}.prism :root{--code-bg:rgba(13,11,7,.51)}.prism code[class*=language-],.prism pre[class*=language-]{color:#d6deeb;direction:ltr;font-family:SF Mono,Menlo,Monaco,Consolas,Courier New,Courier,monospace;font-size:14px;-webkit-hyphens:none;hyphens:none;line-height:1.5;-o-tab-size:4;tab-size:4;text-align:left;text-shadow:none;white-space:pre;word-break:normal;word-spacing:normal}.prism code[class*=language-] ::selection,.prism code[class*=language-]::selection,.prism pre[class*=language-] ::selection,.prism pre[class*=language-]::selection{background:rgba(29,59,83,.99);text-shadow:none}.prism pre[class*=language-]{-ms-overflow-style:none;background:#1e1e1e;border-radius:1em;margin:2.4em 0;overflow:auto;padding:1em;scrollbar-width:none}.prism pre[class*=language-]::-webkit-scrollbar{display:none}.prism .rehype-code-title{background:var(--code-bg);border-bottom:1px solid var(--chakra-colors-whiteAlpha-200);border-radius:1em 1em 0 0;margin-top:2.4em;padding:.5rem 1.25rem}.prism :not(pre)>code[class*=language-],.prism pre[class*=language-]{background:var(--code-bg);color:#fff}.prism :not(pre)>code[class*=language-]{background:#1e1e1e;border-radius:.3em;color:#db4c69;padding:.1em .3em}.prism .rehype-code-title+pre[class*=language-]{border-top-left-radius:0;border-top-right-radius:0;margin-top:0}.prism .code-highlight{float:left;min-width:100%}.prism .code-line{border-left-color:transparent;display:block;padding-left:1rem;padding-right:1rem}.prism .code-line,.prism .highlight-line{border-left-width:4px;margin-left:-1rem;margin-right:-1rem}.prism .highlight-line{background-color:rgba(34,40,50,.5);border-left-color:#feea9a}.prism .line-number:before{color:#9ca3af;content:attr(line);display:inline-block;margin-left:-.5rem;margin-right:1rem;text-align:right;width:1rem}.prism .code-line.inserted{background-color:rgba(16,185,129,.2)}.prism .code-line.deleted{background-color:rgba(239,68,68,.2)}.prism .token.cdata,.prism .token.comment,.prism .token.prolog{color:#637777}.prism .token.punctuation{color:#c792ea}.prism .namespace{color:#b2ccd6}.prism .token.deleted{color:rgba(239,83,80,.56)}.prism .token.property,.prism .token.symbol{color:#80cbc4}.prism .token.keyword,.prism .token.operator,.prism .token.tag{color:#7fdbca}.prism .token.boolean{color:#ff5874}.prism .token.number{color:#f78c6c}.prism .token.builtin,.prism .token.char,.prism .token.constant,.prism .token.function{color:#82aaff}.prism .token.doctype,.prism .token.selector{color:#c792ea}.prism .language-css .token.string,.prism .style .token.string,.prism .token.attr-name,.prism .token.entity,.prism .token.inserted,.prism .token.string,.prism .token.url{color:#addb67}.prism .token.atrule,.prism .token.attr-value,.prism .token.class-name{color:#ffcb8b}.prism .token.important,.prism .token.regex,.prism .token.variable{color:#d6deeb}.prism .token.bold,.prism .token.important{font-weight:700}.prism .token.italic{font-style:italic}.prism code[class*=language-javascript],.prism code[class*=language-jsx],.prism code[class*=language-tsx],.prism code[class*=language-typescript],.prism pre[class*=language-javascript],.prism pre[class*=language-jsx],.prism pre[class*=language-tsx],.prism pre[class*=language-typescript]{color:#9cdcfe}.prism code[class*=language-css],.prism pre[class*=language-css]{color:#ce9178}.prism code[class*=language-html],.prism pre[class*=language-html]{color:#d4d4d4}.prism .language-regex .token.anchor{color:#dcdcaa}.prism .language-html .token.punctuation{color:gray}.prism input[type=search]::-webkit-search-cancel-button,.prism input[type=search]::-webkit-search-decoration,.prism input[type=search]::-webkit-search-results-button,.prism input[type=search]::-webkit-search-results-decoration{-webkit-appearance:none}.picture-deck .flex{align-items:center;display:flex}.picture-deck .flex.fill{height:100%}.picture-deck .deck,.picture-deck .flex.center{justify-content:center}.picture-deck .deck{align-items:center;display:flex;height:200px;position:absolute;width:300px;will-change:transform}.picture-deck .deck>div{background-color:#feea9a;background-position:50%;background-repeat:no-repeat;background-size:auto 85%;border-radius:10px;box-shadow:0 12.5px 100px -10px rgba(50,50,73,.4),0 10px 10px -10px rgba(50,50,73,.3);height:85vh;max-height:570px;max-width:300px;touch-action:none;width:45vh;will-change:transform}::-webkit-scrollbar{width:1px}::-webkit-scrollbar-thumb,::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb:hover{background:transparent}.hide-display{display:none;visibility:hidden}.straight-face{height:100px;width:100px}@media(max-width:768px){.straight-face{display:none}}.straight-face-hidden{display:none}@media(max-width:768px){.straight-face-hidden{display:inline;height:80px;width:80px}}
We all come across chatbots when visiting various sites, while some of them operate behind real-human interaction, others are powered by AI....
We all come across chatbots when visiting various sites, while some of them operate behind real-human interaction, others are powered by AI.
In this article, we'll walk through building a simple AI-powered chatbot using TensorFlow and JavaScript. The chatbot will recognize user commands and respond with predefined answers.
Setting Up Our Project
First, we create a new directory for our project and initialize it with npm, ensure you have Node.js installed on your system before starting this step.
mkdir chatbotcd chatbotnpm init -y
Install necessary packages
We would be using the following npm packages for our simple project:
@tensorflow/tfjs
: TensorFlow.js library for machine learning.
@tensorflow-models/universal-sentence-encoder
: Pre-trained Universal Sentence Encoder model for intent recognition.
npm install @tensorflow/tfjs @tensorflow-models/universal-sentence-encoder
Create intents
Create a file named intents.js
to store intents/commands. These are categories of user inputs that the chatbot will recognize (e.g., greetings, product inquiries, order status).
// intents.jsconst 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 };
Create responses
Create another file named responses.js
to store predefined responses. These are the predefined responses the chatbot will give based on the recognized intent.
// responses.jsconst 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 };
Loading TensorFlow and the Sentence Encoder
Create a main script file named chatbot.js
and load the necessary libraries and models, we load the universal sentence encoder model asynchronously and start the chatbot once the model is loaded.
// chatbot.jsconst 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 modellet model;use.load().then((loadedModel) => {model = loadedModel;console.log('Model loaded');startChatbot();});
Implementing Intent Recognition
Add a function to recognize the intent of the user's input, we embed the user input into a high-dimensional vector using the universal encoder and then track the highest similarity score based on the intent.
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 embeddingsconst 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;}
Generating Responses
Add a function to generate responses based on the recognized intent:
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?";}}
Implementing Chatbot Interaction
Finally, implement the interaction loop with the chatbot by setting up the interface for reading user input from the command line, prompting the user for input and generating responses accordingly:
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();});}
Here is the completed code for chatbot.js
:
// chatbot.jsconst 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 modellet 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();});}
To run the chatbot, execute thechatbot.js
file:
node chatbot.js
Voila! Our command output should have the chatbot running:
In this article, we've built a simple customer service chatbot using TensorFlow and JavaScript. The model used in this article is basic and doesn't have the ability to generate complex responses, in a real-world scenario an extensive dataset would be used to handle generating user queries. Likewise, you can expand this project by integrating APIs using AXIOS, adding more intents and responses, or deploying it on a web platform.
Happy coding!
I'm Jide, a Full-Stack Software Engineer with penchant for Web/App development. I like scratching my own itch and writing about Web Technologies, UI/UX case studies, and Tech-bits thereof. During my spare time, I'm an autodidact polymath acquiring knowledge from various resources online.
© 2025 Jide Abdul-Qudus. All rights reserved.