Chatbots (II): How to make your phone read to you Hacker News (also contents)

Following the post series about Chatbots, I did an app to make Google Assistant allows you navigate using your voice throw Hacker News (Y Combinator‘s tech news forum) and listen to the body of the news in which you are more interested.

[En castellano]

If you are only interested in using it, you only have to talk to Google and say «Talk to Hacker News Reader«. However, if you want to know main points to be able to do something similar using few hours and few lines of code stay tuned: we are going to see the 6 human characteristics that are really easy to get using Dialogflow.

Dialogflow is a Google platform (formerly API.ia) that allows us to create chatbots in an easy way.

It is so powerful that allows us to do a lot of things without a single line of code.

For instance, it has integrated a natural language processing system. If you give it few training examples, it will know what our users are trying to say, driving them to different parts of our chatbot in order to give them the correct answer.

So, it will allow us to give human capacities to our chatbot in a really easy way.

1. Listening

Intents are the main component of a chatbot inside Dialogflow. It is something like a conversation unit, it is each part that our system can understand and give an answer.

Dialogflow allows us to set events and other parameters that will launch an intent. Especially, it allows writing different sentences in order to guide the chatbot. When it will detect those it will know that that is the intent it has to launch.

It also allows writing different responses that it will launch randomly avoiding you from writing code.

2. Understanding

A chatbot picking out actions based on sentences without a single line of code is great but not powerful enough. In the end, listening sentences is not the most important but understanding the concepts that are wrapped inside them.

When you are typing example phrases, you are allowed to select some words to say the platform that they are something important and that it should abstract them from single values.

At the moment in which the language understanding motor detects some of the entities that we had mapped to variables, it will extract them and send them to us as parameters in each request.

The system is ready to understand a lot of different things, but it allows us to define our own entities in order to model exactly what we want. For instance, I created an entity with different sections from Hacker News: top, new, best, ask, show and job. Then, the system can understand that a user wants that jobs uploaded to Hacker News to be read.

3. Intelligence

If intents’ answer options are not enough, we can create our very own web service to answer request understood by the system.

Google offers some libraries and using them, create a service in any language on any platform would be really easy. However, for small things like Hacker News Reader we can code right inside the platform using node.js. This code will be deployed to Firebase only with one click.

When you are thinking about things you can do you must think that coding a service (on Firebase or anywhere) you can do literally anything.

That is, you don’t need to only use APIs to access contents because you don’t have cross-origin restrictions. You have the whole Internet in your hands.

For instance, my action allows users listen to news linked from Hacker News. To do this, it downloads the web page (like a browser) and processes that to extract contents (I didn’t a hard work, it could be better).

4. Analysis

In order to use the inline editor, we have to attend some restrictions like the one that says that «dialogflowFirebaseFulfillment» must be the name of our function if we want an automated deployment.

However, thanks to Dialogflow listening and understanding, when we are giving it some intelligence we will have really easy to give analysis capacities of requests received for our chatbot.

Map each intent to functions developed by ourselves is really easy. Intents function is listening so they will say us what a user wants.

We could also access parameters understood by the system thanks to entities (understanding).

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({
        request,
        response
    });
    //...

    function read(agent) {
        var number = agent.parameters.number || 0;
        //...
    }

    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    intentMap.set('Repeat', repeat);
    intentMap.set('Back', repeat);
    intentMap.set('Read', read);
    //...
    var promise = null;
    try {
        promise = agent.handleRequest(intentMap).then(function() {
            log('all done');
        }).catch(manageError);
    } catch (e) {
        manageError(e);
    }
    return promise;
});

5. Answering

To give to our chatbot answering capacity we only have to use add method from WebhookClient. We can pass as params text, user answer suggestions or rich text cards where we can embed images, use emoticons, etc.

Keep in mind that some devices where your action may be executed could not own a display or a browser. It’s important if we want a strictly conversational interface, so we should avoid visual elements to help to our bot only with words.

6. Memory

The most disgusting thing in a conversation is having to repeat every time what we are saying so, it is really important that our bot remember what user said in previous interactions of our conversation.

For this, we will use contexts. Contexts are an element managed by Dialogflow to help to choose between intents in order to launch the correct one. They could be used to know if a client device has a display available, for instance.

Their use is not very well documented, but when you debug basic methods you see that it is trivial use them to save information between each conversation turn.

    //...
    var context = agent.getContext('vars');
    var vars = context ? context.parameters : {
        ts: (new Date()).getTime() % 10000,
        items: [],
        pointer: 0,
        list: 0,
        //...
    };
    //...
    agent.setContext({
        name: 'vars',
        lifespan: 1000,
        'parameters': vars
    });
    //...

With these 6 human capacities, you own the keys to do something similar by your own and provide a lot of functionalities to Google Assistant.

I hope they may be useful for you, the action and the information provided in this post. If yes, please share and spread the word.

We will continue with other systems that allow us to do chatbots in an easy way and with how to integrate our chatbots into other channels.

Chatbots (II): Cómo lograr que tu móvil te lea Hacker News (los contenidos también)

Siguiendo con la serie sobre Chatbots, he preparado un programilla para que Google Assistant te permita navegar usando la voz por Hacker News (el foro de Y Combinator dedicado a noticias de tecnología) y escuchar el cuerpo de las noticias que más te interesen.

[In English]

Si sólo quieres usarla basta con que le digas a Google «Talk to Hacker News Reader«. Sin embargo, si quieres conocer los puntos clave para poder hacer algo similar en pocas horas y con muy poco código sigue leyendo, porque vamos a ver 6 características humanas muy fáciles de obtener gracias a Dialogflow.

Dialogflow es una plataforma de Google (antes conocida como API.ai), que nos permite diseñar chatbots de un modo sencillo.

Es tan potente, que se pueden hacer muchísimas cosas sin tirar una sóla línea de código.

Por ejemplo, tiene integrado un sistema de reconocimiento de lenguaje natural el que, dándole unos cuantos ejemplos para que entrene, será capaz de reconocer lo que quieren decir los usuarios de nuestra acción y conducirles por las partes de nuestro chatbot para que obtengan la respuesta adecuada.

Por tanto, nos permitirá dar a nuestro chatbot de capacidades «humanas» de un modo muy simple.

1. Escucha

Los intents son el componente principal de un chatbot en Dialogflow. Lo podemos ver como cada unidad de conversación, es cada parte que nuestro sistema va a ser capaz de comprender y dar una respuesta.

Dialogflow nos permite indicar eventos y otras cosas que lanzarán ese intent, y en especial, nos permite indicar distintas frases que le sirvan de guía al chatbot, para que cuando las detecte sepa qué es ese y no otro el que tiene que lanzar.

También permite indicar directamente respuestas ahí mismo, que se irán lanzando aleatoriamente sin que tú tengas que programar nada.

2. Entendimiento

Que el chatbot pueda, sin que programemos nada, distinguir unas frases de otras es genial, pero le falta algo de poder. Al final, no sólo es importante escuchar las frases si no que también hay que entender los conceptos que están encerrados en ellas.

Al introducir las frases de ejemplo, tenemos la posibilidad de seleccionar partes del texto para decirle que es algo importante que debería abstraer y entender más allá de la muestra concreta.

Cuando el motor de reconocimiento del lenguaje entienda alguna de las entidades que hayamos mapeado a variables, las extraerá y nos las pasará como parámetros en las peticiones que nos diga que tenemos que procesar.

El sistema viene ya preparado para entender muchas cosas por defecto, pero nos da la libertad de definir nuestras propias entidades que nos ayuden a modelar exactamente lo que queremos. Por ejemplo, yo me he creado una entidad con los distintos apartados de noticias de Hacker News que se pueden leer: top, new, best, ask, show y job. Así el sistema puede entender que un usuario quiere que le lean los trabajos subidos a la plataforma o las últimas noticias.

3. Inteligencia

Cuando las opciones de respuesta de los intents no son suficientes, podemos crear nuestro propio servicio web que conteste a las peticiones que haya entendido el sistema.

Con las librerías que ofrece Google es fácil montar un servicio en cualquier lenguaje y plataforma. Sin embargo, para cosas pequeñas como el Hacker News Reader, nos permite codificar directamente sobre la plataforma código en node.js que será desplegado de manera transparente para nosotros en Firebase.

Cuando penséis en las cosas que podéis hacer, daros cuenta de que tirando de un servicio (en Firebase o dónde queráis) no estaréis ejecutando código en cliente, por lo que podéis hacer literalmente todo.

Por ejemplo, no os tenéis que ceñir a usar APIs para acceder a contenidos, pues no hay restricciones de cross origin que se apliquen a vuestro código. Tenéis todo Internet a vuestro alcance de un modo sencillísimo.

Mi acción permite al usuario escuchar las noticias que están linkadas desde Hacker News. Para esto se descarga la web (como si fuese un navegador) y la procesa para extraer el contenido (no me he esmerado mucho y se podría hacer mucho mejor).

4. Análisis

Para usar el editor inline, tendremos que tener algunas restricciones como que por narices nuestra función deberá llamarse «dialogflowFirebaseFulfillment» si queremos que se despliegue automáticamente y funcione todo bien.

Sin embargo, gracias a que Dialogflow escucha y entiende, al dotar de inteligencia a nuestro chatbot lo tendremos muy fácil para que sea capaz de realizar los análisis pertinentes de cada petición del usuario.

En el código podremos de un modo sencillo mapear cada uno de los intents que hayamos creado con funciones nuestras. Como estos se encargaban de escuchar, nos indicarán lo que el usuario quiere.

También podremos acceder a los parámetros que el sistema haya entendido gracias a las entidades que hayamos creado (entender).

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({
        request,
        response
    });
    //...

    function read(agent) {
        var number = agent.parameters.number || 0;
        //...
    }

    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    intentMap.set('Repeat', repeat);
    intentMap.set('Back', repeat);
    intentMap.set('Read', read);
    //...
    var promise = null;
    try {
        promise = agent.handleRequest(intentMap).then(function() {
            log('all done');
        }).catch(manageError);
    } catch (e) {
        manageError(e);
    }
    return promise;
});

5. Respuesta

Para que nuestro chatbot conteste, tan solo tenemos que hacer uso del método add de nuestro WebhookClient. Podremos pasarle directamente texto, sugerencias de respuesta para guiar al usuario o fichas con texto enriquecido en dónde podremos embeber imágenes, poner emoticonos, etc.

Hay que tener en cuenta que algunos de los dispositivos en los que potencialmente correrá nuestra aplicación pueden que no tengan pantalla o navegador web por ejemplo. Por lo que hay que tener en cuenta que, si queremos algo puramente conversacional, deberíamos evitar los estímulos visuales y ayudar a nuestro bot a expresarse sólo con el uso de la palabra.

6. Recuerdo

Una de las cosas que más nos exasperan a todos es tener que repetir las cosas una y otra vez, por lo que es importante que nuestro bot recuerde lo que ya se le haya dicho.

Para esto usaremos los contextos. Los contextos es una estructura que maneja Dialogflow para ayudarnos a filtrar entre intents y permitir a la plataforma lanzar el adecuado. Se pueden usar, por ejemplo, para saber si el dispositivo del cliente tiene pantalla.

Su uso no está muy documentado, pero una vez que ves como funcionan los dos métodos básicos, es trivial su uso para guardar información entre cada frase de una conversación.

    //...
    var context = agent.getContext('vars');
    var vars = context ? context.parameters : {
        ts: (new Date()).getTime() % 10000,
        items: [],
        pointer: 0,
        list: 0,
        //...
    };
    //...
    agent.setContext({
        name: 'vars',
        lifespan: 1000,
        'parameters': vars
    });
    //...

Con estas 6 capacidades humanas ya tenéis las claves para poder hacer algo similar vosotros mismos y dar mucha más funcionalidad a Google Assistant.

Espero que os resulte útil, tanto la acción en sí como la información extra. Si es así compartidlo y difundid la palabra.

Seguiremos con algunos otros sistemas que nos permiten también hacer chatbots de un modo sencillo, y con cómo integrar nuestros bots en distintas plataformas.

Chatbots (I): Build an app to talk to your phone without coding

A posts series about chatbots starts today with a direction but without a clear destination.

Today we are going to see a really easy way to create an app that allows you (writing like in a chat or speaking) talk to your phone without coding, without a single line of code!

[En castellano]

A lot of you already would had used Google Assistant. It is the «Siri» from Google which you could access on Android phones saying «Ok, Google».

Nowadays it also works on iOS phones, on Google Home, on smartwatches, on cars, on TVs, …

By the way, Google (attending the developer community program I spoke about two months ago) mailed me about they are gifting me a Google Home thanks an app I built following this method, using only a few hours. Do you want do the same?

When you access the actions console («actions» is the name given to Google Assistant apps) you can add a new project and Google gives you some options. You can code everything using its API, you can use an advanced platform in which you can code but it gives you a lot of work done (it is named DialogFlow), or you can use templates Google provides.

As you see in the above image, there are 3 different templates:

  1. Trivia. This template allows you create a quiz. You can provide different answers and synonyms for this answers also for each question. It is ready to load contents in English, French, German and Japanese.
  2. Personality Quiz. This template is ready to create personality quizzes. For instance, you can create a quiz like the one used by Cambridge Analytics (the company that had problems with Facebook’s privacy) to get data about millions of Americans and to affect USA elections. For the time being, you can only use this to create English content.
  3. Flash Cards. This is a template that for the moment only allows you create English content. It drives you to build a teaching game to learn about things.

The first step (but with the second that doesn’t allow this option) you have to choose the kind of personality. It means that you are choosing a voice from a woman, a man or a robot. Your election is also affecting to accent, expressions and sound effects that your application is going to use.

It is really important that you copy the Google Sheets template in the second step, the one about content. If you build your sheet from a clear one, it is difficult to achieve all restrictions checked by validations coming.

Using the template you are allowed to change whatever you want to adapt it to your content, but it is really important that in the second sheet (that is ready to set different configuration params) you change the title of your application, in order to avoid conflicts with other apps created before.

Whenever you are done following this wizard (the form that takes you throw a step by step process, for the ones that are not inside the apps design and development world), you only have to follow the Overview one to set how your apps are going to be called, set descriptions, icons, etc. etc.

Done this, you are ready to send your draft to the validation process and whenever it was approved your users will be able to say to their phones «Talk to…» and magic will start.

Chatbots (I): Crea una app para hablar con tu móvil sin programar nada

Comienza hoy una serie de posts relacionados con los chatbots, con una dirección y sentido pero sin saber muy bien a dónde llegaremos.

En el de hoy vamos a ver un modo supersencillo de crear una aplicación que te permita hablar (en plan chat o usando la voz) con tu móvil sin programar nada, ¡ni una sóla línea de código!

[In English]

Muchos, habréis usado ya Google Assistant. El «Siri» de Google al que accedías en terminales Android diciendo «Ok, Google».

Ahora ya no está sólo en teléfonos Android, se puede disfrutar de su ayuda en los terminales con iOS, en los Google Home, smart watches, en coches, televisores, etc.

Por cierto, decir que Google  (por el programa de recompensas del que os hablé hace un par de meses) me mandó un mail indicándome que me va a regalar un Google Home por una aplicación que hice siguiendo este método, empleando tan solo unas pocas horas. ¿Queréis hacer lo mismo?

Cuando vais a la consola de actions (que así se llaman las aplicaciones para el asistente), al añadir un nuevo proyecto, Google te da varias opciones. Puedes programártelo todo contra una API, puedes usar una plataforma avanzada en la que puedes programar pero que te da muchas cosas hechas (se llama DialogFlow), o puedes usar una de las tres plantillas que tiene.

Como veis en la imagen previa hay 3 plantillas distintas:

  1. Trivia. Es una plantilla que te permite crear un juego de preguntas y respuestas. Por cada pregunta te permite aportar distintas respuestas e incluso sinónimos a las respuestas. Esta plantilla está preparada para cargar contenidos en Inglés, Francés, Alemán y Japonés.
  2. Personality Quiz. Es una plantilla preparada para crear tests de personalidad. Por ejemplo, podríais crear uno como el que usó Cambridge Analítica (la del follón con Facebook) para captar datos de millones de estadounidenses e influir en sus elecciones. Esta, por el momento, sólo se puede usar para crear contenido en inglés.
  3. Flash Cards. Es una plantilla que por el momento sólo permite crear apps en inglés, y que busca que se cree un juego educativo para aprender sobre cosas.

En el primer paso (salvo en la segunda que no dispones por el momento de esta opción), has de elegir el tipo de personalidad. Esto es principalmente elegir si quieres una voz de mujer, hombre o robot. La elección también influirá en el acento, expresiones y efectos de sonido que empleará tu aplicación.

En el segundo paso, el de contenido, es importante que os copieis la plantilla de Google Sheet que os ofrece, ya que si creais una vosotros desde cero, es muy fácil que no cumpláis con todas las validaciones que se realizarán después.

En la plantilla podéis cambiar cuanto queráis para adaptarla a vuestro contenido, pero es muy importante que en la segunda hoja (que está pensada para que introduzcáis varios parámetros de configuración) cambieis el título de vuestra aplicación, para no entrar en conflicto con otras aplicaciones que se hayan creado antes.

Una vez que hayáis seguido este wizard (el formulario que te guía paso a paso por un proceso, para los ajenos al mundo del diseño y desarrollo de aplicaciones), tan sólo tendréis que seguir el de Overview para indicar cómo se debe invocar a vuestra aplicación, poner descripciones e iconos, etc. etc.

Con esto hecho, ya estaréis preparados para mandar vuestra aplicación a validación y que una vez que sea aprobada, vuestros usuarios puedan decirle a su móvil «Talk to …» y que empiece la magia.