<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Anthony Noventa on Medium]]></title>
        <description><![CDATA[Stories by Daniel Anthony Noventa on Medium]]></description>
        <link>https://medium.com/@danoventa?source=rss-6610a00e1749------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ac8VLT4CRKXhVkik.jpg</url>
            <title>Stories by Daniel Anthony Noventa on Medium</title>
            <link>https://medium.com/@danoventa?source=rss-6610a00e1749------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 05:43:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danoventa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Empezando con Amazon Alexa Skills]]></title>
            <link>https://danoventa.medium.com/empezando-con-amazon-alexa-skills-32a2b6248b78?source=rss-6610a00e1749------2</link>
            <guid isPermaLink="false">https://medium.com/p/32a2b6248b78</guid>
            <category><![CDATA[alexa]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Daniel Anthony Noventa]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 09:01:00 GMT</pubDate>
            <atom:updated>2019-01-23T10:33:56.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXNP_7qP2XxosfOGjK79rw.jpeg" /><figcaption>Photo por <a href="https://unsplash.com/photos/WrPmNpKQUUY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Aaron Lee</a> en <a href="https://unsplash.com/search/photos/water?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Desde que vi los <a href="https://www.youtube.com/watch?v=FQn6aFQwBQU">tráilers </a><a href="https://www.youtube.com/channel/UCz2-0uvBJt-AwoiFSyMb_yQ/videos?view=0&amp;flow=grid&amp;sort=da">de Alexa</a> , he querido saber qué tipo de brujería pasaba en segundo plano para que funcionara. Me imaginé que sería una hazaña tan difícil; Llena de un serio jitsu de procesamiento de lenguaje natural y aprendizaje automático. Afortunadamente, como la mayoría de las tecnologías modernas, es relativamente intuitivo, está bien documentado y ¡tiene una curva de aprendizaje relativamente baja! Hay muchos recursos disponibles para aprender sobre las Skills de Alexa. Uno que encontré de gran valor fue el <a href="https://acloud.guru/learn/intro-alexa-free">curso de Cloud Guru</a> , ¡y es gratis! <a href="https://developer.amazon.com/alexa-skills-kit/learn">Amazon tiene un conjunto de recursos</a> que también te ayudarán a aumentar tu capacidad.</p><p>El proceso de desarollo de Alexa está basado en “skills<em>”, </em>al menos desde el punto de vista de un desarrollador externo, no estoy completamente seguro de cómo los equipos de desarrollo de Alexa le programan nuevas características, pero la tecnología central es probablemente similar a la que los outsiders usaremos.</p><p>Entonces, ¿qué es una <em>skill</em> ? Me referiré a la <a href="https://medium.com/scout-fm/what-are-alexa-skills-3f3234bbc5fb">publicación de </a><a href="https://medium.com/@joyc">Joy Chen </a><a href="https://medium.com/scout-fm/what-are-alexa-skills-3f3234bbc5fb">sobre las skills de Alexa</a> para obtener más detalles. Lo esencial aquí: una skill es una combinación de una interfaz con nuestra voz (o una interfaz de usuario de voz), y la lógica para manejar lo que se habló.</p><h4><strong>La interfaz de voz</strong></h4><p>Cuando comencé con el desarrollo de estas tecnologías, pensé que esta sería la parte más complicada del desarrollo de skills, pero fue bastante simple una vez que superé ese temor inicial de probar algo nuevo. La interfaz de usuario de voz (VUI) para una skill de Alexa es esencialmente un conjunto de frases clave y partes de frases de destino que maneja la lógica de Alexa (utilizando <a href="https://aws.amazon.com/lambda/features/">AWS Lambdas</a> ) para ofrecer el resultado deseado. En realidad, es un resultado muy estático y fijo de una experiencia de desarrollo. Insertarás un conjunto de frases, como las de abajo, y designarás una palabra o frase de destino para que tu Lambda lo procese. (Nota: no estás limitado a una sola palabra de destino por frase).</p><pre>ayúdame llegar a {localidad}, // &#39;la tienda&#39;,&#39;casa&#39;,&#39;Islandia&#39;, etc<br>déjame ir a {localidad}, <br>ayúdanos a llegar a {localidad},<br>como llego a {localidad},<br>puedo ir a {localidad},<br>volar a {localidad},<br>llévatelo a {localidad} por favor,<br>ella se va {localidad}</pre><p>Amazon espera que tengas un mínimo de <strong>50</strong> de estas frases, y la intención de agregarlas continuamente durante toda la vida de la aplicación, y eso es por una muy buena razón. Simplemente hay demasiadas formas para que un individuo diga lo mismo, y para todas las formas en que un individuo puede decir lo mismo, otro individuo encontrará otro conjunto de formas de decirlo.</p><p>Durante el desarrollo de una aplicación de una semana, las frases (también conocidas como <a href="https://developer.amazon.com/docs/custom-skills/best-practices-for-sample-utterances-and-custom-slot-type-values.html">expresiones</a>) para una sola <a href="https://developer.amazon.com/docs/custom-skills/create-the-interaction-model-for-your-skill.html">intención</a> crecieron exponencialmente. Terminé usando una <a href="http://www.makermusings.com/amazon-echo-utterance-expander/">herramienta en línea para generar frases basadas en permutaciones</a>. Me entusiasmó un poco el hecho de cubrir todas las entradas de voz potenciales para varios usuarios y para varios propósitos dentro de la aplicación. Sin embargo, esto me llevó a otra limitación, que aún no he encontrado en la documentación…</p><p>El esquema de intent de Alexa, también conocido como el archivo JSON que almacena todos los intents y slots, tiene una limitación aproximada de 10,000 líneas. Después de reducir las horas de permutaciones, pensé en las características que tenía mi conjunto de intenciones, y busqué una forma de reducir los múltiples duplicados de expresiones y también de limitar la cantidad de intenciones necesarias para cada skill.</p><h4><strong>Haz que la máquina trabaje para ti</strong></h4><p>Los intentos de Amazon se aplican a un algoritmo de aprendizaje automático que crea un modelo que la skill utiliza para alimentar la entrada de voz del usuario a nuestra lógica Lambda. Así que, en lugar de crear permutaciones de muchas frases con palabras específicas, decidí darle a cada <em>parte de la</em> oración un conjunto de palabras y a las palabras un conjunto de “ <a href="https://developer.amazon.com/docs/custom-skills/define-synonyms-and-ids-for-slot-type-values-entity-resolution.html">sinónimos</a>”. Idealmente, estos sinónimos se usarían para identificar elementos objetivo similares, como cachorros, perros, perritos, etc. Obtienes el punto, ¡pero también podría funcionar para identificar partes de la oración! O, al menos, esa era la teoría. Es lo que parece en la consola del desarrollador para una skill de Alexa (seguida de una oración de ejemplo para cada uno):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oB6cUlqL98WGo3r8CoLAZg.png" /><figcaption>Por favor, dime cómo es el camino a casa hoy.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLEBHXCXJ4sha7HeZyfwWA.png" /><figcaption>Ayúdame a llegar a casa</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0XKIuzbRgfX_08UsHuusw.png" /><figcaption>Vamos a ir a casa</figcaption></figure><p>La belleza de este enfoque es que realmente funciona! Además, ¡las partes de la oración, o las <a href="https://developer.amazon.com/docs/custom-skills/slot-type-reference.html">ranuras</a> , son fácilmente reutilizables! No hace falta decir que pude generar muchas más frases, o más bien, dejar que la máquina genere estas frases por y para mi, invirtiendo de este modo el mínimo esfuerzo. Si bien tuvimos que hacer este trabajo para agregar manualmente menos expresiones por intent (para encajar dentro de la limitación), ¡Alexa fue finalmente capaz de manejar un número considerable de respuestas con este enfoque! Por supuesto, no soy lingüista, por lo que muchas de las oraciones que está generando la máquina son probablemente demasiado repetitivas. Me arriesgué y asumí que el algoritmo mapea expresiones duplicadas, y lo llamé un día. Profundizar en la deduplicación es un problema que podría abordarse en otro post.</p><p>Si te estás preguntando cómo es mi modelo de interacción, aquí hay una versión severamente truncada:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4ed0ea748f292b8352cd16efa33f7df/href">https://medium.com/media/b4ed0ea748f292b8352cd16efa33f7df/href</a></iframe><p>En el ejemplo anterior, la solicitud de raíz será mi palabra de destino. Esto es lo que se usa en Lambda para decidir lo que Alexa le dirá al usuario. Los tipos aquí solo muestran el pronombre, pero usan tu imaginación y pretenden que verbo, determinador y solicitud de raíz tienen una estructura similar a la del tipo de pronombre. ¡No solo puedo usar esta estructura para reutilizar tipos dentro de esta Skill, sino que también puedo transferir los tipos a cualquiera de mis aplicaciones futuras! ¿Genial, verdad? ¡Un ejemplo de un modelo de interacción completamente funcional se puede encontrar <a href="https://gist.github.com/danoventa/a144f11b80397443bd8b1081b708169a"><strong>AQUÍ</strong></a>!</p><h4><strong>Script rápido para formatear la entrada</strong></h4><p>Para encontrar sinónimos y estructurarlos de una manera que se adjunte fácilmente al modelo JSON de intención, este pequeño script de Python también me ahorró algo de tiempo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c446fb242f7d9257a18fb3e1f6a2ee6b/href">https://medium.com/media/c446fb242f7d9257a18fb3e1f6a2ee6b/href</a></iframe><h4><strong>Ahora, la lógica que hace hablar a Alexa</strong></h4><p>Ahora que estamos más avanzados sobre cómo definimos nuestras muchas expresiones, volvamos a manejar esos intents que mostré anteriormente. Lo que pasa con estas solicitudes de destino <em>y sinónimos</em> , es que están anidadas en la solicitud entrante desde la interfaz de voz. Por ejemplo, supongamos que tiene una palabra de destino, “gato”, pero tu usuario dice “gatito”; Tendrá que encontrar el nombre de la palabra de destino, no solo la palabra de sinónimo que se pronunció. Si solo usas el slot.namevalor, todavía obtendrás el sinónimo “gatito”. Ciertamente, puedes manejar esto en Lambda, pero en lugar de eso elegí recuperar la palabra clave de la slot(ese nombre anidado) en lugar de manejar el sinónimo para cada caso. No me crees ¡Dale una oportunidad, y también echa un vistazo a los <a href="https://developer.amazon.com/docs/custom-skills/request-types-reference.html">documentos</a> !</p><p>Este pequeño fragmento hará que tu vida sea un poco más fácil. De nuevo, menos código, más skills!</p><h4><strong>Ahora, para algunos conocimientos de skills de Alexa SDK</strong></h4><p>Antes de implementar tu Lambda, asegúrate de haber importado el SDK de Alexa. Si estás utilizando Nodo, como yo, ejecuta: npm install alexa-sdk. Aquí está el archivo root index.js, y una manera dogmática de manejar múltiples manejadores. Puedes usar los controladores para dividir funcionalidades separadas de tu skill. Por ejemplo, un manejador maneja gatos, el otro maneja perros.</p><p>También puedes manejar a tus gatos y perros en el mismo archivo, pero … ya sabes … podría causar problemas.</p><h4><strong>¿Código duplicado?</strong></h4><p>Algunos de los intents podrían compartir algo de la misma lógica. En un proyecto anterior, <a href="https://medium.com/@shaun.husain">Shaun Husain</a> solía Object.assign()eliminar el código genérico de varios manejadores. De nuevo, menos código y una base de código más manejable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe0292dfc1dbff082c5031ec32552250/href">https://medium.com/media/fe0292dfc1dbff082c5031ec32552250/href</a></iframe><p>A continuación se muestra un caso de uso más común. Los intents integrados de Amazon tienen la misma salida y la misma entrada, por lo que no necesitamos duplicarlo en todos los demás controladores. Todo lo que tienes que hacer es importar el controlador genérico a tus controladores específicos, y extender el controlador específico con tus intentos genéricos de controlador, ¡y listo! Mostraré este truco en acción en el siguiente fragmento de código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/794d766ff76401d278758e059e2a63bf/href">https://medium.com/media/794d766ff76401d278758e059e2a63bf/href</a></iframe><h4><strong>Extras para los más entusiastas</strong></h4><p>Aparte de la estructura básica y el dogma del SDK de Alexa, quería profundizar un poco más. Asumí que Alexa podía manejar cualquier cosa que una aplicación estándar y moderna debería — lo que significa que puede integrarse con API externas para recuperar información y también enviar información a API externas. ¿Crees que estoy loco? ¡te estás equivocando!</p><p>Comencé a usar node-fetch para recuperar algunos datos falsos para un blog <a href="https://jsonplaceholder.typicode.com/">ficticio de un marcador de posición JSON</a>, y luego hice que Alexa pronunciara el título de la publicación del blog falso. Aquí está mi manejador para la solicitud, y Alexa afortunadamente cooperó:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46abf632cd663a12e93e86bedc2c3138/href">https://medium.com/media/46abf632cd663a12e93e86bedc2c3138/href</a></iframe><p>¿Qué sigue? A ver si podemos conseguir que me envíe un mensaje de texto. Si nunca has usado <a href="https://www.twilio.com/">Twilio</a> , es una API bien refinada para comunicarse a través de mensajes de texto SMS o manejar la entrada de voz, y es divertido. Primero, configura tu <a href="https://www.twilio.com/docs/sms/quickstart/node">cuenta de Twilio.</a> Luego configura un intent y el Lambda para enviar tu mensaje. Sólo un aviso, mi número no es 5555555555; ¡Modifícalo con tu propio número y comienza a recibir mensajes de texto de Alexa! Ten en cuenta que Twilio te emitirá su propio número; solo asegúrate de agregarlo como el from número.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/157ce7234a2eadf1e328a013fa691d61/href">https://medium.com/media/157ce7234a2eadf1e328a013fa691d61/href</a></iframe><h4><strong>Un poco aburrido, pero imprescindible</strong></h4><p>Una estructura de proyecto predecible te dará un poco de tranquilidad, especialmente cuando trabajas con otros miembros del equipo, pero también para tu propia cordura. Me inspiré en la “ <a href="https://marmelab.com/blog/2015/12/17/react-directory-structure.html">estructura de directorio de reacción</a>” para este proyecto. Proporcionó una estructura simple a seguir, y mantuvo la distancia del directorio de dependencias agradable y corta (por lo que no hay largas declaraciones de “requerimiento”).</p><pre>. <br>├── index.js <br>├── handlers <br>|   ├── root_handler<br>|   |   └── constants.js<br>|   |   └── handler.js<br>|   |   └── index.js<br>|   |   └── prompts.js<br>|   └── other_handler<br>|       └── constants.js<br>|       └── handler.js<br>|       └── index.js<br>|       └── prompts.js<br>├── utilities <br>|   ├── text_parsing.js<br>|   └── api_utils.js<br>└── constants <br>    └── app_constants.js</pre><p>El código hacía uso intensivo de texto estático, e hice lo que pude para reducir la cantidad de texto estático dentro del código. Aquí, las indicaciones contendrían todas las respuestas que Alexa emitiría al usuario. Esto mantuvo la lógica del manejador bastante limpia.</p><h4><strong>Para concluir</strong></h4><p>Una Skill es una aplicación que utiliza la voz humana como la interfaz de usuario elegida. Puedes ser creativo con la lógica en tu Lambda y en la VUI por igual, más o menos igual que con cualquier otra aplicación. La mayor diferencia es la cantidad de libertad que debes proporcionar al usuario para permitirle interactuar a la perfección con su skill. En lugar de tener un solo botón para hacer una cosa en una IU gráfica, tendráa un conjunto potencialmente grande de frases, todas para poder llevar a cabo un único objetivo.</p><p>Los asistentes de voz aún son una nueva frontera en tecnología, pero Amazon está impulsando un aumento en el desarrollo de skills, así que echa un vistazo a sus incentivos. La curva de aprendizaje es superficial, aproximadamente una semana sólida antes de sentirse cómodo con ella, y tiene un SDK pequeño y bien documentado. ¡Dale una oportunidad y adéntrate en el desarrollo de esta tecnología.</p><p><em>Puedes ver la publicación original en el blog de </em><a href="https://medium.com/slalom-engineering/testing-the-waters-with-amazons-alexa-5aab474142bc"><em>Slalom Build aquí</em></a><em>!</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F68bc97%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F68bc97%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8021540cbf50434828deb5439e1cf04/href">https://medium.com/media/d8021540cbf50434828deb5439e1cf04/href</a></iframe><figure><a href="http://bit.ly/2BDa2xQ"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Axmr4bMScpjBU_WcOm263A.png" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*u6pz8xzjblHCXLMQUQGF3Q.gif" /></figure><figure><a href="https://twitter.com/planetaChatbot"><img alt="" src="https://cdn-images-1.medium.com/max/788/1*qQxzn3vV9Xu4lYMpuc5OOw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a2b6248b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Amazon Alexa Skills]]></title>
            <link>https://medium.com/slalom-build/testing-the-waters-with-amazons-alexa-5aab474142bc?source=rss-6610a00e1749------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aab474142bc</guid>
            <category><![CDATA[alexa-skills]]></category>
            <category><![CDATA[alexa]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[amazon-echo]]></category>
            <dc:creator><![CDATA[Daniel Anthony Noventa]]></dc:creator>
            <pubDate>Fri, 21 Dec 2018 16:24:53 GMT</pubDate>
            <atom:updated>2018-12-21T16:26:08.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXNP_7qP2XxosfOGjK79rw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/WrPmNpKQUUY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Aaron Lee</a> on <a href="https://unsplash.com/search/photos/water?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Ever since I saw the <a href="https://www.youtube.com/watch?v=FQn6aFQwBQU">trailers</a> <a href="https://www.youtube.com/channel/UCz2-0uvBJt-AwoiFSyMb_yQ/videos?view=0&amp;flow=grid&amp;sort=da">for Alexa</a>, I’ve wanted to know what sort of sorcery went on in the background to make it work. I imagined it would be such a difficult feat; filled with some serious natural language processing and machine learning jitsu. Thankfully, like most modern day technologies, it’s relatively intuitive, well documented, and has a relatively low learning curve! There are plenty of resources out there for learning about Alexa skills. One that I found invaluable was the <a href="https://acloud.guru/learn/intro-alexa-free">Cloud Guru course</a>, and it’s free! <a href="https://developer.amazon.com/alexa-skills-kit/learn">Amazon has a set of resources</a> that will also get you ramped up.</p><p>The long and short of the process is that Alexa has “<em>skills” — </em>at least from a third party developer stand point — I’m not entirely sure how Alexa dev teams program new features into her, but the core technology is likely similar to what us outsiders will be using.</p><p>So what’s a <em>skill</em>? I’ll defer to <a href="https://medium.com/u/5b996003ea89">Joy Chen</a>’s <a href="https://medium.com/scout-fm/what-are-alexa-skills-3f3234bbc5fb">post on Alexa skills</a> for more details. The relevant gist here: A skill is a combination of an interface with our voice (or a voice user interface), and logic to handle what was spoken.</p><p><strong>The voice interface</strong></p><p>I imagined this would be the most complicated part of the skill development, but it was quite simple once I got past that initial fear of trying something new. The voice user interface (VUI) for an Alexa skill is essentially a set of key phrases and target phrase parts that Alexa’s logic handles (using <a href="https://aws.amazon.com/lambda/features/">AWS Lambdas</a>) to deliver your desired output. In reality, it’s a very static and fixed outcome from a development experience. You’ll insert a set of phrases, such as those below, and designate a target word or phrase for your Lambda to process. (Note: You’re not limited to a single target word per phrase).</p><pre>help me get {location}, // &#39;to the store&#39;, &#39;home&#39;, &#39;to Iceland&#39;, etc<br>let me go {location}, <br>help us getting {location},<br>how do I get {location},<br>can I get {location},<br>fly me {location},<br>take him {location} please,<br>she is going {location}</pre><p>Amazon expects you to have a minimum of <strong>50</strong> of these phrases, and an intention to add-on continuously for the lifetime of the application, and that’s for a very good reason. There are simply too many ways for an individual to say the same thing, and for all the ways an individual can say the same thing, another individual will find another set of ways to say it.</p><p>During the one week development of my application, the phrases (aka <a href="https://developer.amazon.com/docs/custom-skills/best-practices-for-sample-utterances-and-custom-slot-type-values.html">utterances</a>) for a single <a href="https://developer.amazon.com/docs/custom-skills/create-the-interaction-model-for-your-skill.html">intention</a> were growing exponentially. I ended up using an <a href="http://www.makermusings.com/amazon-echo-utterance-expander/">online tool to generate phrases based on permutations</a>. I got a bit fanatical about covering all the potential voice inputs for various users, and for various intents within the application. This however led me to another limitation, which I have yet to find in the documentation…</p><p>Alexa’s intent schema, aka the JSON file that stores all of the intents and slots, has a rough limitation of 10,000 lines. After chopping down hours of permutations, I thought through what features my set of intents had, and sought a way to reduce the multiple duplicates of utterances and also to limit the amount of intents needed for each skill.</p><p><strong>Make the machine work for you</strong></p><p>Amazon’s intents are fed to a machine learning algorithm which creates a model that’s used by the skill to feed the user’s voice input to our Lambda logic! Aha! So, instead of creating permutations of many phrases with target words, I decided to give each sentence <em>part</em> a set of words, and give the words a set of “<a href="https://developer.amazon.com/docs/custom-skills/define-synonyms-and-ids-for-slot-type-values-entity-resolution.html">synonyms</a>”. Ideally, these synonyms would be used to identify similar target items, like puppy, dog, doggy, doge, etc. You get the point, but it could also work to identify sentence parts! Or, at least that was the theory. He’s what this looks like in the developer console for an Alexa skill (followed by an example sentence for each):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oB6cUlqL98WGo3r8CoLAZg.png" /><figcaption>Please tell me what the road home is like today.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLEBHXCXJ4sha7HeZyfwWA.png" /><figcaption>Help me get to home</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0XKIuzbRgfX_08UsHuusw.png" /><figcaption>We’re going to go home</figcaption></figure><p>The beauty of this approach is that it really works! What’s more, the sentence parts, or <a href="https://developer.amazon.com/docs/custom-skills/slot-type-reference.html">slots</a>, are readily reusable! Needless to say, I was able to generate tons more phrases, or rather, let the machine generate these phrases for me, with minimal work on my part. While we had to do this work to manually add fewer utterances per intent (to fit within the limitation), Alexa was ultimately able to handle a hefty number of replies with this approach! Granted, I’m no linguist, so many of the sentences the machine is generating are likely overly repetitive. I went out on a limb and assumed the algorithm maps duplicate utterances, and called it a day. Digging deeper into de-duplication is a problem for another post.</p><p>If you’re wondering what my interaction model looks like, here’s a a severely truncated version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4ed0ea748f292b8352cd16efa33f7df/href">https://medium.com/media/b4ed0ea748f292b8352cd16efa33f7df/href</a></iframe><p>In the example above, the root request is going to be my target word. This is what is used in the Lambda to decide what Alexa will say to the user. The types here only show the pronoun, but use your imagination and pretend that verb, determiner, and root_request have a similar structure as the pronoun type. Not only can I use this structure to reuse types within this skill, but I can also port the types to any of my future apps! Ahh, beautiful. An example of a fully functional interaction model can be found <a href="https://gist.github.com/danoventa/a144f11b80397443bd8b1081b708169a"><strong>HERE</strong></a>!</p><p><strong>Quick Script to format input</strong></p><p>For finding synonyms and structuring them in a way that’s easily appended to the intention model JSON file, this tiny python script saved me some time as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c446fb242f7d9257a18fb3e1f6a2ee6b/href">https://medium.com/media/c446fb242f7d9257a18fb3e1f6a2ee6b/href</a></iframe><p><strong>Now, the logic that makes Alexa speak</strong></p><p>Now that you’re ramped up on how we defined our many utterances, let’s get back to handling those intents I showed you earlier. The thing about these target requests <em>and synonyms</em>, is that they’re nested nice and deep within the incoming request from the voice interface. For example, let’s say you have a target word, “cat”, but your user says “kitty”; you’ll have to find the name of the target word, not just the synonym word that was spoken. If you just use the slot.name value, you’re still gonna get the synonym “kitty”. You can certainly handle this in the Lambda, but instead I chose to retrieve the slot’s keyword (that nested name) instead of handling the synonym for each case. Don’t believe me? Give it a shot, and also check out the <a href="https://developer.amazon.com/docs/custom-skills/request-types-reference.html">docs</a>!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63e9dd30aa666e498c3daed46c4c65d4/href">https://medium.com/media/63e9dd30aa666e498c3daed46c4c65d4/href</a></iframe><p>This little snippet will make your life a good bit easier. Again, less code, more skills!</p><p><strong>Now, for some Alexa skill SDK knowledge</strong></p><p>Before you deploy your Lambda, make sure you’ve imported the Alexa SDK. If you’re using Node, as I am, run: npm install alexa-sdk. Here’s the root index.js file, and a dogmatic way of handling multiple handlers. You can use the handlers to divide separate functionalities of your skill. For example, one handler handles cats, the other handles dogs!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c94c85c31ce59c176bf9374dc26b10f1/href">https://medium.com/media/c94c85c31ce59c176bf9374dc26b10f1/href</a></iframe><p>You could also handle your cats and dogs in the same file, but… you know… it could get messy.</p><p><strong>Duplicate code?</strong></p><p>Some of the intents might share some of the same logic. In a previous project, <a href="https://medium.com/u/a14b323fd6e8">Shaun Husain</a> used Object.assign() to remove generic code from multiple handlers. Again, less code, and a more manageable code base:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe0292dfc1dbff082c5031ec32552250/href">https://medium.com/media/fe0292dfc1dbff082c5031ec32552250/href</a></iframe><p>Below is a more common use case. Amazon’s built-in intents have the same output and the same input, so we wont need to duplicate it in all other handlers. All you have to do is import the generic handler to your specific handlers, and extend the specific handler with your generic handler intents — And voila! I’ll show this trick in action in the next code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/794d766ff76401d278758e059e2a63bf/href">https://medium.com/media/794d766ff76401d278758e059e2a63bf/href</a></iframe><p><strong>Extras for the inquisitive mind</strong></p><p>Aside from the basic structure and dogma of the Alexa SDK, I wanted to delve a little deeper. I assumed that Alexa was able to handle anything that a standard, modern day application should — Meaning it can integrate with external APIs to retrieve information, and also send information to external APIs. Think I’m crazy? You’d be wrong!</p><p>I started by using node-fetch to retrieve some fake data for a pretend blog from <a href="https://jsonplaceholder.typicode.com/">JSON placeholder</a>, and then had Alexa speak the title of the fake blog post. Here’s my handler for the request, and Alexa was thankfully cooperative:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46abf632cd663a12e93e86bedc2c3138/href">https://medium.com/media/46abf632cd663a12e93e86bedc2c3138/href</a></iframe><p>What next? Let’s see if we can get her to send me a text message. If you’ve never used <a href="https://www.twilio.com/">Twilio</a>, it’s a well refined API to communicate via SMS texts or handle voice input, and it’s fun. First, set up your T<a href="https://www.twilio.com/docs/sms/quickstart/node">wilio account</a>. Then set up an intent and the Lambda to send your message. Just a heads-up, my number is not 5555555555; switch it with your own number and start getting text massages from Alexa! Note, Twilio will issue you your own number — just make sure to add that as the from number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/157ce7234a2eadf1e328a013fa691d61/href">https://medium.com/media/157ce7234a2eadf1e328a013fa691d61/href</a></iframe><p><strong>A bit boring, but essential</strong></p><p>A predictable project structure is gonna give you piece-of-mind, especially when you’re working with other team members, but also just for your own sanity. I was inspired by the “<a href="https://marmelab.com/blog/2015/12/17/react-directory-structure.html">react directory structure</a>” for this project. It provided a simple structure to follow, and kept the dependencies directory distance nice and short (so no long “require” statements).</p><pre>. <br>├── index.js <br>├── handlers <br>|   ├── root_handler<br>|   |   └── constants.js<br>|   |   └── handler.js<br>|   |   └── index.js<br>|   |   └── prompts.js<br>|   └── other_handler<br>|       └── constants.js<br>|       └── handler.js<br>|       └── index.js<br>|       └── prompts.js<br>├── utilities <br>|   ├── text_parsing.js<br>|   └── api_utils.js<br>└── constants <br>    └── app_constants.js</pre><p>The code was static text intensive, and I did what I could to reduce the amount of static text within the code. Here, the prompts would hold all of the responses that Alexa would be uttering to the user. This kept the handler logic fairly clean.</p><p><strong>In closing</strong></p><p>A skill is an app that uses the human voice as the user interface of choice. You can get creative with the logic in your Lambda and the VUI alike, pretty much the same as you would with any other app. The biggest difference is how much freedom you need to provide to the user to allow them to interact seamlessly with your skill. Instead of just having one button to do one thing in a graphical UI, you’ll have a potentially large set of phrases, all to handle one thing.</p><p>Voice assistants are still a bit of a newer frontier in tech, but Amazon is pushing for an increase in skills developers, so check out their <a href="https://developer.amazon.com/alexa-skills-kit/alexa-developer-skill-promotion">incentives</a>. The learning curve is shallow, about a solid week before feeling comfortable with it, and it has a small and decently documented SDK. Give it a shot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aab474142bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slalom-build/testing-the-waters-with-amazons-alexa-5aab474142bc">Getting Started with Amazon Alexa Skills</a> was originally published in <a href="https://medium.com/slalom-build">Slalom Build</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>