How we created a chatbot in a week and made friends with a web application

    Chatbots are a trendy trend with promising prospects: in most situations, artificial intelligence is more effective than traditional web applications. However, when integrating new technologies, one should not forget about users who do not want - or are not able to - abandon the usual forms of interaction. Today we will talk about how to create a chatbot serving the conference within a week and make friends with a classic web application.

    image
    Photo chatbotsmagazine.com

    The first order for a bank chat bot


    So, artificial intelligence has come to the banking sector and clearly intends to settle here. Technology is far from perfect, chat bots are not yet able to completely replace a person. But already today they can be safely entrusted with most of the routine tasks of interacting with clients. At least, here they have much more prospects than traditional web applications: 75% of the bank employees surveyed by Accenture consulting agency called artificial intelligence the main development vector for this area.

    If Microsoft's Bot Framework technology is truly capable of improving customer service, our bank simply has no moral right to stay away. Using our chatbot using the Bot Framework solution, we decided to optimize the voting process. The fact is that we regularly hold presentations and other events at which we introduce people to our latest achievements and innovations. The audience can vote on the sessions that they liked, leave comments and make suggestions.

    So far, we have offered participants after the event to fill out a kind of questionnaire on our website. However, it is obvious that this form of interaction is not active: quite often the user simply closed the web page. Another thing is adding ChatBot to your contact list. Our robot not only involves the client in the discussion process, but also stays in touch with him after the event. Subsequently, through the chat bot, you can send announcements, announcements and other information.

    image
    Photo nonworkplace.com

    The chatbot created by us with the support of Microsoft and OpenDev is able to support many channels - various devices and platforms that users bring to the event. Unlike a web form, our virtual assistant remains active throughout the event. He monitors participants' questions about sessions and speakers, and can conduct a survey or vote.

    Fundamental issues and primary architecture


    Assessment of the boundaries and volumes of the project took place in several stages. The task seems simple only at first glance. Digging a little deeper, our team was faced with a number of issues that required serious brainstorming.

    • Should all users connected to the chatbot via one channel — for example, Telegram — be in the same group? Or is it better to organize a private interaction for each client in order to maintain the secrecy of communications with ChatBot? Maybe you should use both options?
    • To organize group communication (the first and third options from the previous paragraph), you need to manage the context and sessions. But are Bot Framework and Telegram effective enough to solve this problem?
    • Can we use the internal storage mechanisms that are supported in the Bot Framework?
    • What about the web voting form? If we continue to support it - what to do in cases when the client uses both Web Form and ChatBot at the same time?

    image
    Photo chatbotsmagazine.com

    Note that we eventually abandoned the idea of ​​organizing group communication. The Bot Framework for Node.js, the platform on which we developed the chatbot, does not allow you to effectively manage multiple contexts. Therefore, communication support was implemented through a private channel.

    We did not doubt the need to use the web form as an additional tool for voting: it would be wrong to leave Telegram as the only communication channel. But for the correct interaction it is necessary to achieve the maximum identity of both channels. Of course, the dynamics of the process are different: the chat bot simulates a conversation, offering to start the voting process. In addition, he introduces the user to the new report and provides him with additional information.

    As mentioned above, the chat bot was developed in Node.js. As for the web form, it is a website written in Java. Both components use the MySQL database located in the OpenDev infrastructure. The choice of a database system was based on its simplicity and low requirements for server resources. Initially, the architecture was implemented on a single MySQL server. The first version, shown in the figure below, looks extremely simple. It remains to improve this model, adding scalability and reliability.

    image


    Stress resistant chatbot


    First, a little terminology. By scalability, we mean the stress resistance of software, its ability to cope with increased load. Thus, in all situations, all simultaneous users should have the same experience - in terms of latency, boot time, etc.

    Reliability is determined by the time during which the system works without failures. In addition, messaging needs to provide the application with high availability. In other words, users must send and receive messages at appropriate time intervals.

    A robust and easily scalable architecture has been helped by some of the best practices.

    • Loose coupling ( https://en.wikipedia.org/wiki/Loose_coupling ) is a method of assembling a system of elements that are as independent as possible from each other. Each of the components of the architectural solution can be easily and painlessly replaced, updated or removed. That is, the system remains operational if one or more components fail.

    Note that most architectural decisions have already been made in the Bot Framework and the Azure team. We only need to test the methodology in the process.

    • Separation of concerns ( https://en.wikipedia.org/wiki/Separation_of_concerns ) is a best practice ideal for developing messaging systems. In our situation, the “separation of interests” is as follows: data storage is external, the logic is inside ChatBot, everything else is processed in the Bot Framework.


    The second and final version of the architecture is shown in the figure below.

    image

    Authentication with options and other system features


    The interaction of the chatbot and the web form is required from the very first step - authentication. Consider first a classic authorization through the site. We tried to simplify the process as much as possible: the user enters his e-mail into the web form - and receives an email with two options for entering the system:

    • by special link;
    • using the code.

    The second method is universal: the code is entered either in web form or in chat. Chatbot content and web forms are synchronized using any of the authentication methods. True, a user authorized in a web form must still enter the code in the chat. In this case, the chatbot welcomes the user by the name under which he registered on the site.

    image

    Why do I need re-authentication by code? For added security: in fact, after user authorization, the code serves as a token.

    Now consider the “clean” chatbot authentication. The sequence is as follows:

    1. Type / start.
    2. Enter Email.
    3. Get the code and enter it.

    Authentication using a data source in the MySQL database allowed us to make the process simple and convenient, while making it possible to partially synchronize the context. Full context synchronization would require the introduction of multi-factor authentication. And this is an unjustified complication of logic, plus an increase in the load on the backend. In our case, when the life cycle of user interaction with applications is limited to several days, this approach does not make practical sense.

    image

    Below is the code used to implement the verification procedure. As you can see, the code is first checked by a regular expression that is confirmed to the backend. He then replaces the set of constants with user data and ends the process by greeting the user by name.

    ``js
    promptCode() {
        	return [
            (session, args) => {
                	if (!_.isEmpty(args) && args.code) {
                    return session.replaceDialog('/promptName', session.userData);
                	}
                	if (!_.isEmpty(args) && args.reprompt) {
                    return Prompts.text(session, 'Введите код из **4-х** цифр:');
                	}
                	return Prompts.text(session, 'Введите код, присланный вам по email: ');
          	},
            (session, result) => {
                	if (/^[0-9]{4}$/.test(result.response)) {
                    return auth.makeUnauthRequest({
                    url: '/login',
                    method: 'POST',
                    body: {
                            	password: result.response,
                            	login: session.userData.email
                    }
                    }, (err, res, body) => {
                    if (err) {
                                    console.error(err);
                            	return session.replaceDialog('/error');
                    }
                     if (body.status >= 300 || res.statusCode >= 300) {
                        console.error(body);
                     	return session.replaceDialog('/promptName', session.userData);
                      }
                      session.userData.code = result.response;
                      session.userData.id = body.id;
                      session.userData.permissions = body.permissions;
                         session.userData.authToken = body.authToken;
                            session.userData.allowToVote = !_.isEmpty(body.permissions)
                            	&& (body.permissions.indexOf("PERM_VOTE") !== -1
                            	|| body.permissions.indexOf("PERM_ALL") !== -1);
                        	return auth.makeAuthRequest({
                            	url: '/login',
                            	method: 'GET',
                            	authToken: body.authToken
                        	}, (err, res, body) => {
                            	if (err) {
                                  console.error(err);
                                	return session.beginDialog('/error');
                     	}
                            	if (!_.isEmpty(body) && !_.isEmpty(body.name)) {
                                  session.userData.name = body.name;
                                	return session.endDialogWithResult(session.userData);
                	                }
                                    return session.replaceDialog('/promptName', session.userData);
                        	});
                    	});
                	        }
                	         return session.replaceDialog('/promptCode', {reprompt: true});
            }
        	];
    	}
    ``

    When interacting with a chat or web form, you can get information about reports without authorization in the system. Chatbot offers to evaluate the report and write a comment to all customers. But only authenticated users can do this. Otherwise, the bot sends an authentication request, as shown in the following code fragment.

    ``js
    rate() {
        	return [
            (session) => {
                	if (_.isEmpty(session.userData.authToken) && !_.isEmpty(this.socket.actualPoll)) {
                    session.send('Чтобы оценить выступление, вам следует войти в свой аккаунт.\n\n' +
                    'Просто напишите `/start` и начнём! ');
                    return session.endDialog();
              }
                	if (!session.userData.allowToVote) {
                    session.send('У вас не хватает привилегий для оценивания выступлений');
                    return session.endDialog();
                	   }
                    Prompts.choice(session, ' Оцените выступление', RATES);
            },
            (session, res) => {
                	if (res.response) {
                    let result = parseInt(res.response.entity, 10) || res.response.entity;
                    if (!_.isNumber(result)) {
                    result = RATES[result.toLowerCase()];
                    }
                    return auth.makeAuthRequest({
                    url: `/polls/${this.socket.actualPoll.id}/vote`,
                    method: 'POST',
                          body: {
                            	myRating: result
                    },
                    authToken: session.userData.authToken
                    }, (err, response, body) => {
                    if (err) {
                         console.log(err);
                            	return session.beginDialog('/error');
                     } else if (body.status === 403) {
                          session.send('У вас недостаточно прав на выполнение данной операции, простите ');
                     } else {
                          console.log(body);
                          session.send('Выступление успешно оценено ');
                     }
                     return session.endDialog();
                     })
                	}
                	session.endDialog();
            }
        	];
    	}
    ``

    Among other things, the chat bot can tell you the next steps. This is especially important for customers using the bot as the main way to communicate with the system.

    ``js
    	help() {
        	return [
            (session) => {
                	const keys = _.keys(commands);
                	const result = _.map(keys, (v) => (`**/${v}** - ${commands[v]}`));
                    session.send(result.join('\n\n'));
                	session.endDialog();
            }
            ];
    	}
    ``

    To be continued?


    It can be stated that our experiment with the Bot Framework from Microsoft on the introduction of artificial intelligence in the banking sector was successful. It is worth adding that the project is fully implemented by one developer within a week. During this time, a full-fledged chat bot was created with a bot panel hosted in Azure, as well as support for Application Insights and some useful user settings in the Bot logic.

    image
    Photo by letzgro.net

    However, it is better to see once. An experimental chat bot has already entered the service in our bank. So we suggest you, if possible, attend one of our conferences in order to test and evaluate the work of this little virtual assistant in practice.

    Mikhail Brant, Director of the Testing and Quality Control Department of Otkritie Bank

    Also popular now: