Happy halloween! Hello Ada

    Halloween today ! It is believed that this is the day when the souls of the dead travel freely around the world of the living. Today, hurry up to get acquainted with the spirit of Ada Lovelace - the first programmer in history, who, after centuries, found a new life in Telegram . This was made possible thanks to two of my colleagues who spent a sleepless night recreating the virtual image of Ada from quotes and historical texts. For those who want to similarly revive someone from other historical characters, we have prepared detailed instructions for creating a bot using the Microsoft Bot Framework and wit.ai , which you will find under the cat.


    Disclaimer: This bot is a demonstration of how to create bots using the Bot Framework and Wit.ai, and does not pretend to pass the Turing test or even the ability to maintain a complex conversation. Therefore, I propose not to scold the intelligence of the bot in the comments. In addition, the creation of this bot does not mean that we welcome and encourage various technologies of otherworldly communication.

    We already wrote about how to start developing your bot on the Microsoft Bot Framework. Since then, the Bot Framework version has been updated a bit, but the principles have remained the same. However, last time we left the main question outside the article - how to write an intelligent bot that can communicate in a natural language.

    To do this, we need to learn how to first recognize user phrases, i.e. what exactly does he want to achieve. This intention of the user, which he expresses with his phrase, is called intent . Special tools, such as LUIS (part of Microsoft Cognitive Services ) or wit.ai , are used to isolate intents from a natural language . About using LUISwe already wrote , now we decided to integrate the bot with wit.ai.

    We use wit.ai


    First you need to register on wit.ai and create an application there.



    Within the application, it is necessary to list all the intents that we want to recognize in the dialogue. Intents can have a complex nature, various parameters (for example, the “know the weather in a city” intent can have a location and date as parameters), etc. However, in our case, for simplicity, we restrict ourselves to simple intents.



    Next, you need to teach the logic of the bots, providing him with examples of phrases, and indicating to which intent a particular phrase corresponds. The more different phrases you give as examples, the better the bot will eventually understand your speech.

    Create a bot in the bot framework



    To create a bot you will need:

    1. Microsoft Visual Studio 2015 (with the latest updates).
    2. Bot Application Template (you need to download this file and copy it without unpacking to% USERPROFILE% \ Documents \ Visual Studio 2015 \ Templates \ ProjectTemplates \ Visual C #).
    3. Bot Framework Channel Emulator .

    Next, create a new bot in Visual Studio: Visual Studio → File → New → Project → Templates → Visual C # → Bot Application.



    Name: AdaBot → Ok.

    In the created project, the simplest version of the bot is already implemented, which repeats the entered phrase and prints their length. The contents of the Controllers folder are responsible for the bot logic.

    Run it in the emulator to make sure that everything works correctly:

    • Debug → Start Debugging (or the F5 key), as a result of which the web page opens in the browser.
    • We launch the Bot Framework Channel Emulator, if the Bot URL field is empty, copy the address of the previously opened web page into it and add “api / messages”.
    • We type the text and send it to the bot.
    • In response, we get the repetition of the sent phrase and the number of characters of which it consists.



    To write a bot, it remains only to change a couple of lines responsible for the formation of the answer. The lines are responsible for this:public async Task Post([FromBody]Activity activity)

    // calculate something for us to return
    int length = (activity.Text ?? string.Empty).Length;
    

    Instead, we need to recognize the user's intent and select one of the message options corresponding to this intent in response.

    To specify the answer options, add a file with Responses.xmlthe following content to the application :



    Здравствуй, мой собеседник!Приветствую вас!Добрый день.Рада с вами побеседовать.Какая встреча!Рада вас поприветствовать!Позвольте поприветствовать вас!Добрый день. Холодно сегодня.Кто вы?Зачем вы потревожили меня?Здравствуйте! Я живая!Что происходит?
    ...
    

    So you need to set several answer options for each intent, so that the bot will delight you with a variety.

    To use the wit.ai API in our project, we will connect the corresponding nuget Wit.ai.net package to it . In Solution Explorer, call the context menu for AdaBot -> Manage NuGet Packages -> Browse tab.



    Next, you need to implement the logic of the bot. In the MessagesController.cs project file, we connect the namespaces:

    using com.valgut.libs.bots.Wit;
    using System.Text;
    using System.Xml.Linq;
    


    To search for intent, use the following code:

    var wit = new WitClient("YOUR WIT SERVER ACCESS TOKEN");
    var msg = wit.Converse(activity.From.Id, activity.Text);
    var intent = string.Empty; double conf = 0;
    try
    {
        var a = msg.entities["intent"];
        if (a != null)
        {
            foreach (var z in msg.entities["intent"])
            {
                if (z.confidence > conf)
                {
                    conf = z.confidence;
                    intent = z.value.ToString();
                }
            }
        }
    }
    catch (System.Collections.Generic.KeyNotFoundException exc)
    {
    }
    

    We see that wit.ai returns to us several probable intents and their degree of reliability, so we go through them all and choose the most probable of all. By the way, there may not be any intents at all, then an empty string remains in the intent variable, and the answer is selected, which corresponds to an empty intent in our XML file.

    Then it remains only to choose one of the possible answers corresponding to the found intent. To do this, use LINQ:

    string res = "Я вас не понимаю...";
    var doc = XDocument.Load(System.Web.HttpContext.Current.Request.MapPath("~/Responses.xml"));
    var r = (from x in doc.Descendants("Response")
             where x.Attribute("intent").Value == intent
             select x).FirstOrDefault();
    if (r!=null)
    {
        var arr = (from x in r.Descendants("Text") select x.Value).ToArray();
        if (arr!=null && arr.Length>0)
        {
             var rnd = new Random();
            res = arr[rnd.Next(0, arr.Length)];
         }
    }
    

    Now, having received a new message, the bot will not be engaged in counting the number of characters in it, but in the classification of intentions and the choice of answer. In order for it to give the selected answer to incoming messages, we replace the lines:

    // return our reply to the user
    Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
    

    on the
    Activity reply = activity.CreateReply(res);
    

    Now the bot can talk! Of course, if you previously trained him to recognize a large number of phrases, and asked a lot of answers.

    You can find an example code here , however, without all the variety of phrases and without a training sample for wit.ai. Let it remain our know how.

    If, on the eve of Halloween, you want to talk with the Ada Lovelace bot itself, use @Ada_Lovelace_Bot in a telegram.

    Happy holiday!

    Also popular now: