Friday, March 3, 2017

Searching Blob Documents with the Azure Search Service

One of the core services in the Microsoft Azure cloud platform is the Storage Service, which includes Blobs, Queues, and Table storage. Blobs are great for anything you would use a file system for, such as avatars, data files, XML/JSON files, ...and documents. But until recently, documents in blob storage had one big shortcoming: they weren't searchable. That is no longer the case. In this post, we'll examine how to search documents in blob storage using the Azure Search Service.

Azure Blob Basics

Let's quickly cover the basic of Azure blobs: 

  • Storage Accounts. To work with storage, you need to allocate a storage account in the Azure Management Portal. A storage account can be used for any or all of the following: blob storage, queue storage, table storage. We're focusing on blob storage in this article. To access a storage account you need its name and a key.
  • Containers. In your storage account, you can create one or more named containers. A container is kind of like a file folder--but without subfolders. Fortunately, there's a way to mimic subfolders (you may include slashes in blob names). Containers can be publicly accessible over the Internet, or have restricted access that requires an access key.
  • Blobs. A blob is a piece of data with a name, content, and some properties. For all intents and purposes, you can think of a blob as a file. There are actually several kinds of blobs (block blobs, append blobs, and page blobs). For our purposes here, whenever we mention blob we mean block blob, which is the type that most resembles a sequential file.

Uploading Documents to Azure Blob Storage

Let's say you had the chapters of a book you were writing in Microsoft Word that you save as pdf files--ch01.pdf, ch02.pdf, ... up to ch10.pdf, along with toc.pdf and preface.pdf--which you would like to store in blob storage and be able to search. Here's an example of what a page of this book chapter content looks like:

In your Azure storage account you can create a container (folder) for documents. In my case, I created a container named book-docs to hold my book chapter documents. In the book-docs container, you can upload your documents. If you upload the 12 pdf documents described above, you'll end up with 12 blobs (files) in your container. 

Structure of Azure Storage showing a Container and Blobs

To upload documents and get at your storage account, you'll need a storage explorer tool. You can either use my original Azure Storage Explorer or Microsoft's Azure Storage Explorer. We'll use Microsoft's explorer in this article because it has better support for one of the features we need, custom metadata properties. After downloading and launching the Storage Explorer, and configuring it to know about our storage account, this is what it looks like after creating a container and uploading 12 blobs.

12 pdf documents uploaded as blobs


Setting Document Properties

It would be nice to search these documents not only based on content, but also based on metadata. We can add metadata properties (name-value pairs) to each of these blobs. In the Microsoft Azure Storage Explorer, right-click a blob and select Properties. In the Properties dialog, click Add Metadata to add a property and enter a name and value. We'll later be able to search these properties. In my example, we've added a property named DocType and a property named Title to each document, with values like "pdf" and "Chapter 1: Cloud Computing Explained".

Blob with several metadata properties

Azure Search Basics

The Azure Search Service is able to search a variety of cloud data sources that include SQL Databases, DocumentDB, Table Storage, and Blob Storage (which is what we're interested in here). Azure Search is powered by Lucene, an open-source indexing and search technology. 

Azure Search can index both the content of blob documents and metadata properties of blobs. However, content is only indexable/searchable for supported file types: pdf, Microsoft Office (doc/docx, xls/xlsx, ppt/pttx), msg (Outlook), html, xml, zip, eml, txt, json, and csv. 

To utilize Azure Search, it will be necessary to create three entities: a Data Source, an Index, and an Indexer (don't confuse these last two). These three entities work together to make searches possible.

  • Data Source: defines the data source to be accessed. In our case, a blob container in an Azure storage account.
  • Index: the structure of an index that will be filled by scanning the data source, and queried in order to perform searches.
  • Indexer: a definition for an indexing agent, configured with a data source to scan and an index to populate.

These entities can be created and managed in the Azure Management Portal, or in code using the Azure Search REST API, or in code using the Azure Search .NET API. We'll be showing how to do it in C# code with the .NET API.


Installing the Azure Search API Package

Our code requires the Azure Search package, which is added using nuget. In Visual Studio, right-click your project and select Manage Nuget Packages. Then find and install the Microsoft Azure Search Library.You'll also need the Windows Azure Storage Library, also installed with nuget.

At the top of our code, we'll need using statements for a number of Microsoft.Azure.Search and Microsoft.WindowsAzure namespaces, and some related .NET namespaces:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
using Microsoft.Azure.Search.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

Creating a Search Service

The first step in working with Azure Search is to create a search service using the Azure Management Portal. There are several service tiers you can choose from, including a free service tier which will let you play around with 3 data sources and indexes. To work with your search service in code, you'll need its name and an API admin key, both of which you can get from the management portal. We'll be showing a fake name and key in this article, which you should replace with your actual search service name and key.

Creating a Service Client

To interact with Azure Search in our code, we need to first instantiate a service client, specifying the name and key for our search service:

string searchServiceName = "mysearchservice";
string searchServiceKey = "A65C5028BD889FA0DD2E29D0A8122F46";

SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceKey));

Creating a Data Source

To create a data source, we use the service client to add a new DataSource object to its DataSources collection. You'll need your storage account name and key (note this is a different credential from the search service name and key in the previous section). The following parameters are defined in the code below:

  • Name: name for the data source.
  • Type: the type of data source (AzureBlob).
  • Credentials: storage account connection string.
  • Container: identifies which container in blob storage to access.
  • DataDeletionDetectionPolicy: defines a deletion policy (soft delete), and identifies a property (Deleted) and value (1) which will be recognized as a deletion. Blobs with property Deleted:1 will be removed from the index. We'll explain more about this later.
String datasourceName = "book-docs";
if (!serviceClient.DataSources.Exists(datasourceName))
{
  serviceClient.DataSources.Create(new DataSource()
  {
    Name = datasourceName,
    Type = Microsoft.Azure.Search.Models.DataSourceType.AzureBlob,
    Credentials = new DataSourceCredentials("DefaultEndpointsProtocol=https;AccountName=mystorageaccount;AccountKey=GL3AAN0Xyy/8nvgBJcVr9lIMgCTtBeIcKuL46o/TTCpEGrReILC5z9k4m4Z/yZyYNfOeEYHEHdqxuQZmPsjoeQ=="),
    Container = new Microsoft.Azure.Search.Models.DataContainer(datasourceName),
DataDeletionDetectionPolicy = new Microsoft.Azure.Search.Models.SoftDeleteColumnDeletionDetectionPolicy() {  SoftDeleteColumnName="Deleted", SoftDeleteMarkerValue="1" }
});
}

With our data source defined, we can move on to creating our index and indexer.

Creating an Index

Next, we need to create the index that Azure Search will maintain for searches. The code below creates an index named book. It populates the Fields collection with the fields we are interested in tracking for searches. This includes:

  • content: the blob's content.
  • native metadata fields that come from accessing blob storage (such as metadata_storage_name, metadata_storage_path, metadata_storage_last_modified,  ...). 
  • custom metadata properties we've decided to add: DocType, Title, and Deleted.
Once the object is set up, it is added to the service client's Indexes collection, which creates the index.

String indexName = "book";
Index index = new Index()
{
    Name = indexName,
    Fields = new List<Field>()
};

index.Fields.Add(new Field() { Name = "content", Type = Microsoft.Azure.Search.Models.DataType.String, IsSearchable = true });
index.Fields.Add(new Field() { Name = "metadata_storage_content_type", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_storage_size", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_storage_last_modified", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_storage_content_md5", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_storage_name", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_storage_path", Type = Microsoft.Azure.Search.Models.DataType.String, IsKey = true, IsRetrievable = true , IsSearchable = true});
index.Fields.Add(new Field() { Name = "metadata_author", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_language", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "metadata_title", Type = Microsoft.Azure.Search.Models.DataType.String });
index.Fields.Add(new Field() { Name = "DocType", Type = Microsoft.Azure.Search.Models.DataType.String, IsSearchable = true });
index.Fields.Add(new Field() { Name = "Title", Type = Microsoft.Azure.Search.Models.DataType.String, IsSearchable = true });

if (serviceClient.Indexers.Exists(indexName))
{
    serviceClient.Indexers.Delete(indexName);
}
serviceClient.Indexes.Create(indexName)

Let's take note of some things about the index we're creating:
  • Some of the fields are built-in from what Azure Search intrinsically knows about blobs. This includes content and all the properties beginning with "metadata_". Especially take note of metadata_storage_path, which is the full URL of the blob. This is marked as the key of the index. This will ensure we do not receive duplicate documents in our search results.
  • Some of the fields are custom properties we've chosen to add to our blobs. This includes DocType and Title.

Creating an Indexer

And now, we can create an indexer (not to be confused with index). The indexer is the entity that will regularly scan the data source and keep the index up to date. The Indexer object identifies the data source to be scanned and the index to be updated. It also contains a schedule. In this case, the indexer will run every 30 minutes. Once the indexer object is set up, it is added to the service client's Indexers collection, which creates the indexer. In the background, the indexer will start running to scan the data source and populate the index. It's progress can be monitored using the Azure Management Portal.

String indexName = "book";
String indexerName = "book-docs";
Indexer indexer = new Indexer()
{
    Name = indexerName,
    DataSourceName = indexerName,
    TargetIndexName = indexName,
    Schedule = new IndexingSchedule()
    {
        Interval = System.TimeSpan.FromMinutes(30)
    }
};
indexer.FieldMappings = new List();
indexer.FieldMappings.Add(new Microsoft.Azure.Search.Models.FieldMapping()
{
    SourceFieldName = "metadata_storage_path",
    MappingFunction = Microsoft.Azure.Search.Models.FieldMappingFunction.Base64Encode()

});

if (serviceClient.Indexers.Exists(indexerName ))
{
    serviceClient.Indexers.Delete(indexerName );
}
serviceClient.Indexers.Create(indexer);

Let's point out some things about the indexer we're creating:

  • The indexer has a schedule, which determines how often it scans blob storage to update the index. The code above sets a schedule of every 30 minutes.
  • There is a field mapping function defined for the metadata_storage_path field, which is the document path and our unique key. Why do we need this? Well, it's possible this path value might contain characters that are invalid for an index column; to avoid failures, it is necessary to Base64-encode the value. We'll have to decode this value whenever we retrieve search results.
Putting this all together, when we run the sample included with this article it takes around half a minute to create the data source, index, and indexer. The index is initially empty, but the indexer is already running in the background and will be ready for searching in about a minute.


Creating data source, index, and indexer

Searching Blob Documents

With all of this set up underway, we're finally ready to do searches.

BlobDocument Class

As we perform searches, we're going to need a class to represent a blob document. This class needs to be aligned with how we defined our index. Our sample uses the BlobDocument class below.

[SerializePropertyNamesAsCamelCase]
public class BlobDocument
{
    [IsSearchable]
    public String content { get; set; }

    [IsSearchable]
    public String metadata_storage_name { get; set; }

    [Key]
    [IsSearchable]
    public String metadata_storage_path { get; set; }

    public String metadata_storage_last_modified { get; set; }

    public String metadata_storage_content_md5 { get; set; }

    public String metadata_author { get; set; }

    public String metadata_content_type { get; set; }

    public String metadata_language { get; set; }

    public String metadata_title { get; set; }

    [IsSearchable]
    public String DocType { get; set; }

    public String Deleted { get; set; } // A value of 1 is a soft delete

    [IsSearchable]
    public String Title { get; set; }
}

Simple Searching

A simple search simply specifies some search text, such as "cloud". 

Up until now we've been using a Service Client to set up search entities. To perform searches, we'll instead use an Index Client, which is created this way:

String indexName = "book";
ISearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);

To perform a search, we first define what it is we want to return in our results. We'd like to know the blob document URL, its content, as well as the two custom metadata properties we defined for our blob documents, DocType and Title.

parameters = new SearchParameters()
{
    Select = new[] { "content", "DocType", "Title", "metadata_storage_path" }

};

We call the index client's Documents.Search method to perform a search for "cloud" and return results.

String searchText = "cloud";
DocumentSearchResult<BlobDocument> searchResults = indexClient.Documents.Search(searchText, parameters);

Search Results

The result of our search is a DocumentSearchResult<BlobDocument> object. We can iterate through the results using a loop. When we defined our index earlier, we had to give Azure Search instructions to Base64-encode the metadata storage path field when necessary. As a result, we now need to decode the path.

foreach (SearchResult<BlobDocument> result in searchResults.Results)
{
    Console.WriteLine("---- result ----");
  
    String path = result.Document.metadata_storage_path;
    if (!String.IsNullOrEmpty(path) && !path.Contains("/"))
    {
        path = Base64IUrlDecode(result.Document.metadata_storage_path);
    }
    Console.WriteLine("metadata_storage_path: " + path);
    Console.WriteLine("DocType: " + result.Document.DocType);
    Console.WriteLine("Title: " + result.Document.Title);
}

The path is part of the result that matters the most, because if a user is interested in a particular search result this lets them download/view the document itself. Note this is only true if your blob container is configured to permit public access.

Now that we have enough code to perform a search and view the results, let's try some simple searches. For starters, we search on "pdf". That is not a term that appears in the content of any of the documents, but it is a value in the metadata: specifically, the property Title that we added to each blob earlier. As a result, all 12 documents match:

Search for "pdf" - 12 matches to document metadata

Now, let's try a search term that should match some of the content within these documents. A search for "safe" matches 3 documents:

Search for "safe" - 3 matches to document content


More Complex Searches

We can use some special syntax in our search query to do more complex queries.

To perform an AND between two search terms, use the + operator. The query storage+security will only match documents that contain both "storage" and "security".


AND query

To perform an OR between two search terms, use the | operator. The query dangerous|roi will match documents containing "dangerous" or "ROI".


OR query

In a future post, we'll explore how to perform advanced searches. 

Deleting Documents

Normally, deleting a blob involves nothing more than selecting it in a storage explorer and clicking Delete (or doing the equivalent in code). However, with an Azure Search index it is a little more complicated: if you just summarily delete a blob that was previously in the index, it will remain in the index: the indexer will not realize the blob is now gone. This can lead to search results being returned about documents that no longer exist.

We can get around this unpleasantness by utilizing a soft delete strategy. We will define a property that means "deleted", which we will tell Azure Search about. In our case, we'll call our property Deleted. A "soft delete" will cause the blob to be removed from the index when Deleted:1 is encountered by the indexer--after which it is safe to actually delete the blob. You might consider having an overnight activity scheduled that deletes all blobs marked as deleted.

Summary

With Azure Search, documents in Azure Blob Storage are finally searchable. Using Azure Search gives you the power of Lucene without requiring you to set up and maintain it yourself, and it has the built-in capability to work with blob storage. Although there are a few areas of Azure Search that are cumbersome (notably, Base64 encoding of document URLs and handling of deleted documents), for the most part it is a joy to use: it's fast and powerful. 

You can download the full sample (VS2013 solution) here.

Monday, January 9, 2017

Developing for Google Home: Building a Knowledge Base in API.AI

In my previous post, I described how to get started developing for Google Home. We looked at the walk-through sample Google provides and created the not-terribly-useful Silly Name Maker agent. In this post, I'll describe my first solo project in API.AI, a knowledge base that provides Bible facts.

When you create projects for Google Home in API.AI, you have the option of also furnishing a back end. The API.AI project can interact with your back end using webhooks. But we won't be using a back-end today: for my first solo project, I wanted to see what I could do just in API.AI by itself. Accordingly, my knowledge base project will be based solely on intents (an intent is a mapping between what a user says and what action the agent takes in response). Rather than use a database, the intents will contain both the questions asked and the responses returned.

API.AI also has some other goodies we won't be using in this first simple project: entities let you extract parameter values from input; contexts are like properties that help you tailor intents to the context of a conversation. Although today's project doesn't require entities or contexts, you can be sure they'll come into play when we move on to more complex projects.

Knowledge Base Design


Since this knowledge base is about Bible facts, the place to start is the first chapter of Genesis -- which describes the creation account. The approach I'm using is to distill each piece of information I want to provide--such as what God created on Day 1--and create an intent for it.


My first intent, then, is called creation_day_1 and looks like this:

creation_day_1 intent

Similar intents follow for the rest of the creation week:


creation_day_2 intent

creation_day_3 intent
creation_day_4 intent

creation_day_5 intent

creation_day_6 intent

creation_day_7 intent

Since this is a knowledge base agent, the scope is simply providing answers to questions. Accordingly, there's no attempt to guide the user from one intent to another. However, the answers to some questions may naturally cause the user to ask follow-up questions.

Anticipating Multiple Phrasings


The idea is that a user can ask "What did God create on the first day?" and hear back "On the first day, God created the heavens and the earth." However, there are many ways a user might make this inquiry, and the knowledge base won't be very useful unless it anticipates more than one way of asking the question. In my intent, I've got the following inquiries listed, all of which trigger the same intent and the same information:

What did God create on the first day?
What did God create first?
When were the heavens created?
When was the earth created?
What was created first?
What was created on the first day?
What was created on day 1?

By the way, you can also include multiple variations in an intent's response. When there's more than one possible response, API.AI will randomly select one of the possible responses. Doing this makes your agent seem more conversational and less predictably--in other words, more alive.

After defining intents for the first couple of chapters of Genesis, I'm able to conduct a dialog like the following:

"Hey Google, go to Bible Answers."
"Welcome to Bible Answers. Ask me a question about Genesis."
"What did God create on the first day?"
"On the first day, God created the heavens and the earth, and also light and darkness."
"What did God create second?"
"On the second day God created the sky, and separated the waters above from the waters below."
"When were the animals created?"
"On the sixth day, God created land animals. He also created Man in His image, and declared it good."
"Who was the first child?"
"Adam and Eve's first child was Cain. Cain was a tiller of the ground."
"Who was the second child?"
"Adam and Eve's second child was Abel. Abel was a keeper of sheep."

Well, after all that I've only covered a tiny portion of the Bible--and there are 1,189 chapters in total! I can see I'll be incrementally adding more and more intents to this project for quite some time.

This simple project, while not yet complete, demonstrates how easy is to write agents for Google Home that conversationally answer questions.


Monday, January 2, 2017

The Geek's Guide to Dieting, Part 4: Surviving the Holidays

This is Part 4 in my series on dieting for geeks. This time we're talking about surviving the holidays, the biggest challenge a dieter faces.


The holidays are a wonderful time of year: they bring together celebration, fellowship, and food. Unfortunately, the holidays also seek, relentlessly, to undermine your diet. Everywhere you look, there's an excuse to over-indulge. All if takes is a few days of over-eating and old habits quickly return.

For me, the holiday season starts with an annual chili cook-off with longtime friends in late October or early November. As we near the Thanksgiving season, all sorts of special foods arrive, many of them pumpkin-spice flavored. Holiday pies are on sale. Thanksgiving itself, of course, is the super bowl of eating. A month later we're eating again for Christmas, and just a week after that there's the all-night eat-a-thon of New Year's Eve.

This year, I entered the holiday season four months into my diet having shed 40 pounds. I had gotten into a routine where I was keeping my calories to 1200 a day, and losing 10 pounds a month. I was justifiably nervous as Fall approached: I certainly had every intention of enjoying the Holiday festivities, but I also didn't want to throw away all of my weight loss progress. I decided I would indulge, but not recklessly. If I could make it to end of year and continue to lose weight at half the usual rate, I would be satisfied; then I could go back to my normal routine in January.

Initially, this worked out fine. We attended the chili cook off and of course over-ate. But that was only one day, and since I otherwise stayed on my diet plan everything was okay. By the time Thanksgiving arrived, I was feeling confident. By now I'd now lost 45 pounds since July, so my plan to continue losing weight but a bit more slowly seemed like it was working. In fact, I'd upped my daily calories from 1200 to 1300. Of course Thanksgiving and the next few days involved a lot of eating, but I again reverted back to form without too much difficulty afterward and only gained a couple of pounds from all that Turkey, mashed potatoes, and stuffing.

By the time Christmas arrived, however, I was starting to crack. Food was being offered to me left and right! There were parties and candy and treats seemingly every day. I did my best, but knew I was slipping into some bad habits and eating more than I should far too often. My wife and I sing in our church choir, and Christmas Eve means singing for three services, with a pot-luck in-between each service to keep our energy up. I lost track of how many meatballs I ate.

Finally, New Years Eve. We were hosting a party for 20 people, and that involved having a lot of food available (such as homemade pretzels and pizza and chips and guacamole) and staying up past midnight eating it. I ate, and ate, and ate. In the morning I weighed myself, and found my 45-pound weight loss had reverted to only a 40-pound weight loss: I'd gained 5 pounds over the course of December.

On January 1st, I knew I had to reset things and work to get back to where I had been. I got a lot more strict about staying on my diet plan and stopped making exceptions. Now that the holidays are over, the constant temptations are gone.

Looking back, I survived the holidays but could have done better. I give myself a B instead of an A. I did gain a bit more weight than I'd wanted to (5 pounds), but I didn't completely unravel things. My plan for next year is to have less in the way of left-overs: left-overs can turn a day of over-eating into several.



Tuesday, December 27, 2016

Developing for Google Home: Getting Started

I recently blogged about the new Google Home I received for Christmas. In this blog, I'll talk about how developers can extend Google Home and teach it new conversational skills. Please note I am only 3 days in here, so this is just an introduction.

I'm a career software developer, so naturally I'm interested in extending Home further by developing new abilities for it. Amazon Echo is known to have an extensive developer and partner program with over 5,000 skills available; so what about Home? Google Home also has a developer program, which you can find out about at Actions on Google. Note, when you are developing for Home you are really developing for the Google Assistant, something that potentially can be used in additional ways (such as on Google Pixel phones).

There are several ways to develop conversation actions for Google Home and its Conversation API. One is with the Actions SDK, which includes a NodeJS client library and a web simulator. The other is API.AI, a web-based interface. API.AI is where I'm starting, and that's what I'm writing about today.


I've just started on learning, but I've already gone through the first tutorial and added a new conversation action that I can test in the web simulator or with my actual Google Home device. I can already tell this is going to be a great deal of fun.

Getting Started Sample: Silly Name Maker


Defining an Agent in API.AI

The API.AI site has a walk-through that gives you the steps to build a simple app named Silly Name Maker - and it's really simple - all it does is ask you for a number and a color, and constructs a silly name from that information. But, it does the job of getting you on your way. If you faithfully go to the API.AI site and enter the instructions, you will soon have an agent that looks like this:


Silly Name Maker tutorial sample in API.AI

and interacts like this:
User: Hey Google, Talk to Silly Name Maker.
Silly Name Maker: Hi! Welcome to Silly Name Maker!
Let's get started. What is your lucky number?
User: 22
Silly Name Maker: What is your favorite color?
User: Blue
Silly Name Maker: Alright, your silly name is Blue 22.
I hope you like it! See you next time.
Yes, it's not terribly useful but it does show you the ropes of defining an agent and running it. 

Intents

So what goes into making this agent? It consists of a number of intents. The first intent is named start_name_maker, and it's the first thing that happens after you invoke Silly Name Maker by asking Home to "Talk to Silly Name Maker". That's because it's tagged as a Welcome intent. All this intent does is welcome you to the agent, and prompt the user to select a number (and when the user does that, they'll be triggering the second intent). It's important for Google Home agents to clearly identify themselves to the user so they understand they're now interacting with an agent (app) and not Google.

start_name_maker intent

The second intent is called make_name, and it gets triggered when the user says a number or says "My lucky number is number". The intent can recognize several patterns of input, any of which will trigger it. Note how easy it is in API.AI to define user input - you simply provide samples of what someone would say, and then you can mark parts of that as parameter values. Parameter values have types; for example, @sys.color is a color and @sys.number is a number. 

Some of those "user says" patterns may provide parameter data - in this case, both patterns define the parameter $number. The intent has another parameter, named $color. Since $color is marked as a required parameter, and none of the defined "user says" patterns provide $color, Home will automatically prompt for it when this intent is triggered. That's why the example dialog above asks "What is your favorite color?" The make_name intent incorporates the parameters in its response: "Alright, your silly name is $color $number. I hope you really like it! See you next time!". Although it's not done in this case, it's possible to list multiple text responses for an intent (if more than one is present, one will be selected at random for the response).

name_maker intent

Now let's revisit the earlier sample dialog, with an understanding of what is happening behind the scenes:
User: Hey Google, Talk to Silly Name Maker.
[Silly Name Maker agent is launched. start_make_name intent runs,
and provides its response]
Silly Name Maker: Hi! Welcome to Silly Name Maker!
Let's get started. What is your lucky number?
[start_make_name intent ends]
User: 22
[make_name intent matches user input of number, and executes]
[$number parameter is from the user input]
[$color parameter value has not been provided yet, 
so API.AI prompts for it automatically]
Silly Name Maker: What is your favorite color?
User: Blue
[make_name intent provides its response]
Silly Name Maker: Alright, your silly name is Blue 22.
I hope you like it! See you next time.
[make_name intent ends]

Testing and Deploying your Agent

You can run the agent in a couple of ways. There's a web simulator on the right-hand side of the API.AI site you can interact with: just click the microphone icon and say something. You'll see how that was interpreted and what the response is. Click the Play link to have the response spoken to you.

Test Console built into API.API

Even better, you can test this on your own Google Home device. If you're logged into API.AI with the same Google account that your Google Home device uses, you can deploy it and go over and talk to the Home. Click Integrations on the left-side menu. On the list of One-click Integrations, click Actions on Google.

Integrations

On the Actions on Google dialog that appears, review the options (you can for example change the voice Home will use), then click Authorize at bottom right.

Actions on Google dialog with Authorize option

Now there is a Preview option available at bottom right. Click it. Preview is a temporary deployment (to do a permanent deployment, you'll need to first formally register your agent).

Actions on Google dialog with Preview option

Once you click Preview, you'll soon see confirmation that your agent has been published. Now you can walk over to your Home device and try it out. Begin with "Hey Google, Talk to Silly Name Maker."

Preview published confirmation

In my next post, I'll develop my first solo agent for Google Home.

Saturday, December 24, 2016

At Home with Google Home

I just became the proud owner of a Google Home. This review will cover the initial experience of setting up and using Google Home.

Why Google Home?

First off, how did I end up with a Google Home, and not an Amazon Echo? The simple answer is, I received it for Christmas as a gift from my family. This year we celebrated Christmas a couple of days early so that our college-aged daughter Susan could join us. I'd overheard a few whispers here and there that "we got Dad something cool," so I knew there was some kind of special gift awaiting me - could it possibly be one of these home assistants? It turns out my family had purchased a Google Home for me. I've now had the Google Home for 36 hours, and in this post, I'll share what the initial experience has been like.

In November 2014, Amazon released Amazon Echo, their home smart speaker. It has been enormously successful for Amazon. Several former colleagues of mine who now work for Amazon have been regularly tweeting about the ever-expanding skills available for Alexa, the Amazon Echo assistant. Much more recently, in November 2016 Google released their competitor, Google Home. If I'd made the purchase myself, I admit I would have been torn: you can tell from reading reviews that both products are compelling with plenty of potential to do even more.

Reviews seem to suggest that both products are very good additions to the home and of course each maker has some advantages over the other. Both can play music or send things to your TV. You can order a zillion products from Amazon using Echo, and there's a vast network of partners providing support for just about every kind of smart home device there is. From Home you get amazing search and voice recognition plus the ability to ask general knowledge questions. The Home also lets you direct video from Netflix and other sources to your TV via Chromecast and control some home devices, including the Nest thermostat.

I've been aware of Amazon Echo and Google Home for the last year but hadn't had the opportunity to play with either before now. To be honest, I wasn't too keen to jump into anything voice-driven because I haven't had very good experiences with voice recognition in the past--this is my own fault, as I tend to talk fast or speak too low. But I know the technology has been getting better and better. From reading reviews, both Amazon Echo and Google Home are good useful products. Well, I was now the owner of Google Home so it was time to find out what all the excitement was about.

Unpacking

Home comes nicely packaged in an attractive white box which is very reminiscent of the experience you get with Apple products. Inside is the Google Home unit, a wall adapter, and some minimalist start-up instructions.


Home resembles an air freshener. It's white with an angled round top. The bottom colored band (gray on mine) covers the speaker. You can buy bands in other colors if you want to match your home decor. 


Google Home on my fireplace mantle

The Get Started card has just 3 steps: plug the power cable into the home, plug the other end in to a wall socket, and download the Google Home app on your phone.


The phone app detects your Home device and performs a quick test which causes your Home to make a sound--confirming you are connected to the right device.


You also configure access to your wireless network for the Home, choose a default music service, and tell it what address it's located at.


  

There are more things you can configure to get the most out of the device--see other sections below--but at this point you can already start using Home for music and search queries. From here on, you use the phone app to do further setup on Google Home such adding home devices and service accounts (see later below).

Basic Usage and Interaction

To get Google Home's attention you say a wake-up phrase of "OK Google" or "Hey Google," followed by your command or question.  I find "Hey Google" to be easiest to say.

As I mentioned earlier, I wasn't sure that *I* would get much out of a voice-driven product as I tend to speak too rapidly and softly. And how well would it do with a whole family of people talking at it? This turns out not to be a worry with Google Home: from the moment we plugged it in, everyone in our family has had no problems at all being understood. The voice recognition is really good, and it can pick up voice from quite far away.

The round top appears to be featureless white, but as you interact with Home you'll find it can do a variety of fun things with lights. As soon as Home recognizes the wake-up phrase, four lights appear to show it is active.
Google Home when active

The top of Home also responds to touch. You can tap the top to pause (or resume) playing music or video, or to interrupt a response. You can dial your finger around the top in a clockwise motion to increase volume or in the other direction to decrease volume. Of course, you can also do all these things by speaking to it.

From the reference card included in the box, here are some examples of commands you can give Home (in each case, preceded by the wake-up phrase):

"What does circumlocution mean?"
"What's the latest news from NPR?"
"Who won the Giants game?"
"How is the S&P 500 doing?"

Google Home also has great contextual memory. Once you are discussing something, it knows what "it", "he", or "she" means. For example:

"Who is president of the united states?"
"When was he born?"
"What is his favorite food?"

Since the phone app configuration includes telling the Home the address where it is located, you can ask it lots of locale-based questions:

"What's the temperature outside?"
"Where's the nearest supermarket?"
"What time is 'Passengers' playing?"

And there are also some things it can't do--yet:

"Give me directions to Panda Express" responds with an apology that Home can't give directions yet. This is kind of odd, since Google has fantastic direction-giving ability when you use it from a computer or phone. This is clearly coming, though. I have to remind myself that this product was only released last month.

Controlling the Thermostat
Home is clearly behind Amazon when it comes to partnerships that allow you to control a vast array of home devices, but they do have support right now for Nest thermostats, Philips Hue lights, Samsung Smart Things, plus the IFTTT online service.


No doubt this list will expand over time. In the meantime, I do have a Nest thermostat in my home so I configured that. In the Google Home app, I added the Nest device and provided my account information, and that was that.


Now I can give commands and queries like these:

"What's the inside temperature?"
"What's the thermostat set to?"
"Set the heat to 72 degrees"
"Make it warmer"
"Make it cooler"

I can see the day when I have more smart home devices and control them via Google Home, such as lighting and alarms.

Music

One of the most useful aspects of Home is playing music: that's where having this device in the home with a good speaker (as opposed to using your phone) really shines. The Home's speaker is pretty good and music sounds great coming from it.

In configuring Home with the phone app, I selected Google Play Music as my default music service, which automatically makes my Google Music library available to Home (alternatively, I could have selected YouTube Red, Spotify or Pandora). Now I can play songs from my library like this:

"Play my Christmas playlist"
"Skip this song"

Oddly, though, it doesn't seem I can play an individual song or album by name: "Play song" doesn't work. After some research, it appears you currently can only play playlists, not individual songs or albums from your Google Music Library. That's a bit of a downer, and hopefully will be addressed soon. I believe this may just be an issue with Google Play Music and not the other music services.

On the other hand, we've had great success just asking Home to play things that we don't even own in our music library. My wife has been getting hours of Christmas atmosphere with requests like these:

"Play some Christmas music"
"Play some instrumental Christmas music"

It's not really clear to me yet where this music is coming from--since I haven't paid for it. It makes me wonder if there's some kind of premium music trial going on that will eventually need to be paid for.

But wait, there's more. Radio is also available through Google Home, via the TuneIn service:

"Play KOST FM"

Video

I have a Chromecast device connected to my TV, and that is also something Google Home understands. After using the phone app to tell Home our Netflix account, I can now give commands like the following:

"Play Zootopia from Netflix on TV"
"Fast forward 10 minutes"
"Play 'What Does the Fox Say' from YouTube on TV"

I only have one TV and one Chromecast, in the same room as Google Home--but if I had a more elaborate setup I could tell Home where to play things:

"Play Zootopia from Netflix in Living Room"

Although video worked right away on my Chromecast, audio did not. It took me about a day of trial and error to get audio working (I had go to my LG TV Settings and turn speakers on instead of letting it default to integration with my home theater). This is an extra step I'd prefer to avoid but its not a bad reflection on the Google Home itself. When I next upgrade my TV and home theater, I'll be paying attention to Consumer Electronics Control (CEC). As I understand it, with the right set up playing video from Home can automatically turn on the TV and switch input to Chromecast.

Photos

Home can also play photos (from my Google Photos collection) on my TV via Chromecast. You can reference photos by date, by special occasion, or even by subject. I'm not sure how Google manages to find photos by subject, but it does. If (for example) I say "Play car photos on TV", it finds all my photos that contain an automobile. There's some kind of impressive analytics going on with Google Photos.

"Play photos from Christmas on TV"
"Play photos from December 22 on TV"
"Play car photos on TV"
"Play dog photos on TV"

Fun

The Home also has plenty of fun built into it, including some personality in the Google Assistant that powers Home. My son has been building up his comedic material by constantly asking Home "Tell me a joke" and getting a different joke each time.

Home can also play games. For example,

"Play mad libs"
"Play lucky trivia"
"Play crystal ball"
"Entertain me"

Google Home has the concept of applications, known as conversation actions. When you're interacting with an action such as Lucky Trivia (which is multi-player by the way), you're executing a conversation action. You don't have to say "OK Google" before each response, which is nice.

How Useful Is it?

I admit it, I expected Google Home to be an interesting geek toy but didn't really expect it to become an integral part of my home--but I was wrong. After just a few days, it's regularly used by my entire family.

Everything the Home does can also be done with my phone, so how useful is it, really? Well, very! Think about the number of times you pick up your phone or pull it out of a pocket--it's a lot. Just being able to call out voice commands is extremely convenient. When I first installed the unit, I wondered if it would be necessary to be right in front of it in order for it to recognize speech, but it turns out it does really well even when we call out commands from another room.

I also wondered how strict the Home would be about the format of commands and queries: would we have to memorize exact patterns of words in order for it to understand us? Many voice-driven devices in the past have ended up "training the user" to speak the way the device can understand. Fortunately, that isn't necessary here. The Home has excellent natural language speech recognition and is very tolerant of variations in phrasing. All of my family members have been able to interact with it right from the start.

One limitation of the Home is that it is linked to a single account--in our case, my music library, my Netflix account, my calendar, etc. There's no support as yet for switching profiles for different users. I presume this will come in time.

One other limitation that I don't expect to get resolved is there's no support for competing services like Apple iTunes. That's a shame, because the rest of my family is on Apple devices. I think that's a shortcoming of any home assistant, whether from Google, Amazon, or (coming soon) Apple: you won't necessarily be able to access every service you want to.

In my next blog post on Google Home, I'll talk about how developers can teach Google Home new actions.