

# AMAZON.KendraSearchIntent


To search documents that you have indexed with Amazon Kendra, use the `AMAZON.KendraSearchIntent` intent. When Amazon Lex V2 can't determine the next action in a conversation with the user, it triggers the search intent.

The `AMAZON.KendraSearchIntent` is available only in the English (US) (en-US) locale and in the US East (N. Virginia), US West (Oregon) and Europe (Ireland) Regions.

Amazon Kendra is a machine-learning-based search service that indexes natural language documents such as PDF documents or Microsoft Word files. It can search indexed documents and return the following types of responses to a question:
+ An answer 
+ An entry from a FAQ that might answer the question
+ A document that is related to the question

For an example of using the `AMAZON.KendraSearchIntent`, see [Example: Creating a FAQ Bot for an Amazon Kendra Index](faq-bot-kendra-search.md).

If you configure an `AMAZON.KendraSearchIntent` intent for your bot, Amazon Lex V2 calls the intent whenever it can't determine the user utterance for an intent. If there is no response from Amazon Kendra, the conversation continues as configured in the bot.

**Note**  
 Amazon Lex V2 currently does not support the `AMAZON.KendraSearchIntent` during slot elicitation. If Amazon Lex V2 can't determine the user utterance for a slot, it calls the `AMAZON.FallbackIntent`. 

When you use the `AMAZON.KendraSearchIntent` with the `AMAZON.FallbackIntent` in the same bot, Amazon Lex V2 uses the intents as follows:

1. Amazon Lex V2 calls the `AMAZON.KendraSearchIntent`. The intent calls the Amazon Kendra `Query` operation.

1. If Amazon Kendra returns a response, Amazon Lex V2 displays the result to the user.

1. If there is no response from Amazon Kendra, Amazon Lex V2 re-prompts the user. The next action depends on response from the user.
   + If the response from the user contains an utterance that Amazon Lex V2 recognizes, such as filling a slot value or confirming an intent, the conversation with the user proceeds as configured for the bot.
   + If the response from the user does not contain an utterance that Amazon Lex V2 recognizes, Amazon Lex V2 makes another call to the `Query` operation.

1. If there is no response after the configured number of retries, Amazon Lex V2 calls the `AMAZON.FallbackIntent` and ends the conversation with the user.

There are three ways to use the `AMAZON.KendraSearchIntent` to make a request to Amazon Kendra:
+ Let the search intent make the request for you. Amazon Lex V2 calls Amazon Kendra with the user's utterance as the search string. When you create the intent, you can define a query filter string that limits the number of responses that Amazon Kendra returns. Amazon Lex V2 uses the filter in the query request.
+ Add additional query parameters to the request to narrow the search results using your Lambda function. You add a `kendraQueryFilterString` field that contains Amazon Kendra query parameters to the `delegate` dialog action. When you add query parameters to the request with the Lambda function, they take precedence over the query filter that you defined when you created the intent.
+ Create a new query using the Lambda function. You can create a complete Amazon Kendra query request that Amazon Lex V2 sends. You specify the query in the `kendraQueryRequestPayload` field in the `delegate` dialog action. The `kendraQueryRequestPayload` field takes precedence over the `kendraQueryFilterString` field.

To specify the `queryFilterString` parameter when you create a bot, or to specify the `kendraQueryFilterString` field when you call the `delegate` action in a dialog Lambda function, you specify a string that is used as the attribute filter for the Amazon Kendra query. If the string isn't a valid attribute filter, you'll get an `InvalidBotConfigException` exception at runtime. For more information about attribute filters, see [Using document attributes to filter queries](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering) in the *Amazon Kendra Developer Guide*.

To have control over the query that Amazon Lex V2 sends to Amazon Kendra, you can specify a query in the `kendraQueryRequestPayload`field in your Lambda function. If the query isn't valid, Amazon Lex V2 returns an `InvalidLambdaResponseException` exception. For more information, see the [Query operation](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html) in the *Amazon Kendra Developer Guide*.

For an example of how to use the `AMAZON.KendraSearchIntent`, see [Example: Creating a FAQ Bot for an Amazon Kendra Index](faq-bot-kendra-search.md).

## IAM Policy for Amazon Kendra Search
IAM Policy

To use the `AMAZON.KendraSearchIntent` intent, you must use a role that provides AWS Identity and Access Management (IAM) policies that enable Amazon Lex V2 to assume a runtime role that has permission to call the Amazon Kendra `Query` intent. The IAM settings that you use depend on whether you create the `AMAZON.KendraSearchIntent` using the Amazon Lex V2 console, or using an AWS SDK or the AWS Command Line Interface (AWS CLI). When you use the console, you can choose between adding permission to call Amazon Kendra to the Amazon Lex V2 service-linked role or using a role specifically for calling the Amazon Kendra `Query` operation. When you use the AWS CLI or an SDK to create the intent, you must use a role specifically for calling the `Query` operation.

### Attaching Permissions


You can use the console to attach permissions to access the Amazon Kendra `Query` operation to the default Amazon Lex V2 service-linked role. When you attach permissions to the service-linked role, you don't have to create and manage a runtime role specifically to connect to the Amazon Kendra index.

The user, role, or group that you use to access the Amazon Lex V2 console must have permissions to manage role policies. Attach the following IAM policy to the console access role. When you grant these permissions, the role has permissions to change the existing service-linked role policy. 

------
#### [ JSON ]

****  

```
{
"Version":"2012-10-17",		 	 	 
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "iam:AttachRolePolicy",
            "iam:PutRolePolicy",
            "iam:GetRolePolicy"
        ],
        "Resource": "arn:aws:iam::*:role/aws-service-role/lexv2.amazonaws.com/AWSServiceRoleForLexBots*"
    },
    {
        "Effect": "Allow",
        "Action": "iam:ListRoles",
        "Resource": "*"
    }
]
}
```

------

### Specifying a Role


You can use the console, the AWS CLI, or the API to specify a runtime role to use when calling the Amazon Kendra `Query` operation. 

The user, role, or group that you use to specify the runtime role must have the `iam:PassRole` permission. The following policy defines the permission. You can use the `iam:AssociatedResourceArn` and `iam:PassedToService` condition context keys to further limit the scope of the permissions. For more information, see [ IAM and AWS STS Condition Context Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/role"
        }
    ]
}
```

------

The runtime role that Amazon Lex V2 needs to use to call Amazon Kendra must have the `kendra:Query` permissions. When you use an existing IAM role for permission to call the Amazon Kendra `Query` operation, the role must have the following policy attached.

You can use the IAM console, the IAM API, or the AWS CLI to create a policy and attach it to a role. These instructions use the AWS CLI to create the role and policies.

**Note**  
The following code is formatted for Linux and MacOS. For Windows, replace the Linux line continuation character (\$1) with a caret (^).

**To add Query operation permission to a role**

1. Create a document called **KendraQueryPolicy.json** in the current directory, add the following code to it, and save it

1. In the AWS CLI, run the following command to create the IAM policy for running the Amazon Kendra `Query` operation.

   ```
   aws iam create-policy \
   --policy-name query-policy-name \
   --policy-document file://KendraQueryPolicy.json
   ```

1. Attach the policy to the IAM role that you are using to call the `Query` operation.

   ```
   aws iam attach-role-policy \
   --policy-arn arn:aws:iam::account-id:policy/query-policy-name
   --role-name role-name
   ```

You can choose to update the Amazon Lex V2 service-linked role or to use a role that you created when you create the `AMAZON.KendraSearchIntent` for your bot. The following procedure shows how to choose the IAM role to use.

**To specify the runtime role for AMAZON.KendraSearchIntent**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose the bot that you want to add the `AMAZON.KendraSearchIntent` to.

1. Choose the plus (\$1) next to **Intents**.

1. In **Add intent**, choose **Search existing intents**.

1. In **Search intents**, enter **AMAZON.KendraSearchIntent** and then choose **Add**.

1. In **Copy built-in intent**, enter a name for the intent, such as **KendraSearchIntent**, and then choose **Add**.

1. Open the **Amazon Kendra query** section.

1. For **IAM role** choose one of the following options:
   + To update the Amazon Lex V2 service-linked role to enable your bot to query Amazon Kendra indexes, choose **Add Amazon Kendra permissions**.
   + To use a role that has permission to call the Amazon Kendra `Query` operation, choose **Use an existing role**.

## Using Request and Session Attributes as Filters


To filter the response from Amazon Kendra to items related to current conversation, use session and request attributes as filters by adding the `queryFilterString` parameter when you create your bot. You specify a placeholder for the attribute when you create the intent, and then Amazon Lex V2 substitutes a value before it calls Amazon Kendra. For more information about request attributes, see [Setting request attributes for your Lex V2 bot](context-mgmt-request-attribs.md). For more information about session attributes, see [Setting session attributes for your Lex V2 bot](context-mgmt-session-attribs.md).

The following is an example of a `queryFilterString` parameter that uses a string to filter the Amazon Kendra query.

```
"{"equalsTo": {"key": "City", "value": {"stringValue": "Seattle"}}}"
```

The following is an example of a `queryFilterString` parameter that uses a session attribute called `"SourceURI"` to filter the Amazon Kendra query.

```
"{"equalsTo": {"key": "SourceURI","value": {"stringValue": "[FileURL]"}}}"
```

The following is an example of a `queryFilterString` parameter that uses a request attribute called `"DepartmentName"` to filter the Amazon Kendra query.

```
"{"equalsTo": {"key": "Department","value": {"stringValue": "((DepartmentName))"}}}"
```

The `AMAZON.KendraSearchInteng` filters use the same format as the Amazon Kendra search filters. For more information, see [Using document attributes to filter search results](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering) in the *Amazon Kendra developer guide*.

The query filter string used with the `AMAZON.KendraSearchIntent` must use lower-case letters for the first letter of each filter. For example, the following is a valid query filter for the `AMAZON.KendraSearchIntent`.

```
{
"andAllFilters": [
    {
        "equalsTo": {
            "key": "City",
            "value": {
                "stringValue": "Seattle"
            }
        }
    },
    {
        "equalsTo": {
            "key": "State",
            "value": {
                "stringValue": "Washington"
            }
        }
    }
]
}
```

## Using the Search Response


Amazon Kendra returns the response to a search in a response from the intent's `IntentClosingSetting` statement. The intent must have a `closingResponse` statement unless a Lambda function produces a closing response message.

Amazon Kendra has five types of responses. 
+ The following two responses require an FAQ to be set up for your Amazon Kendra index. For more details, see [Adding questions and answers directly to a index](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html).
  +  `x-amz-lex:kendra-search-response-question_answer-question-<N>` – The question from a FAQ that matches the search. 
  +  `x-amz-lex:kendra-search-response-question_answer-answer-<N>` – The answer from a FAQ that matches the search. 
+ The following three responses require a data source to be set up for your Amazon Kendra index. For more details, see [Creating a data source](https://docs.aws.amazon.com/kendra/latest/dg/data-source.html). 
  + `x-amz-lex:kendra-search-response-document-<N>` – An excerpt from a document in the index that is related to the text of the utterance.
  + `x-amz-lex:kendra-search-response-document-link-<N>` – The URL of a document in the index that is related to the text of the utterance.
  + `x-amz-lex:kendra-search-response-answer-<N>` – An excerpt from a document in the index that answers the question.

The responses are returned in `request` attributes. There can be up to five responses for each attribute, numbered 1 through 5. For more information about responses, see [Types of response](https://docs.aws.amazon.com/kendra/latest/dg/response-types.html) in the *Amazon Kendra Developer Guide*. 

The `closingResponse` statement must have one or more message groups. Each message group contains one or more messages. Each message can contain one or more placeholder variables that are replaced by request attributes in the response from Amazon Kendra. There must be at least one message in the message group where all of the variables in the message are replaced by request attribute values in the runtime response, or there must be a message in the group with no placeholder variables. The request attributes are set off with double parentheses ("((" "))"). The following message group messages match any response from Amazon Kendra:
+ “I found a FAQ question for you: ((x-amz-lex:kendra-search-response-question\$1answer-question-1)), and the answer is ((x-amz-lex:kendra-search-response-question\$1answer-answer-1))”
+ “I found an excerpt from a helpful document: ((x-amz-lex:kendra-search-response-document-1))”
+ “I think the answer to your questions is ((x-amz-lex:kendra-search-response-answer-1))”

## Using a Lambda Function to Manage the Request and Response


The `AMAZON.KendraSearchIntent` intent can use your dialog code hook and fulfillment code hook to manage the request to Amazon Kendra and the response. Use the dialog code hook Lambda function when you want to modify the query that you send to Amazon Kendra, and the fulfillment code hook Lambda function when you want to modify the response.

### Creating a Query with the Dialog Code Hook


You can use the dialog code hook to create a query to send to Amazon Kendra. Using the dialog code hook is optional. If you don't specify a dialog code hook, Amazon Lex V2 constructs a query from the user utterance and uses the `queryFilterString` that you provided when you configured the intent, if you provided one.

You can use two fields in the dialog code hook response to modify the request to Amazon Kendra:
+ `kendraQueryFilterString` – Use this string to specify attribute filters for the Amazon Kendra request. You can filter the query using any of the index fields defined in your index. For the structure of the filter string, see [Using document attributes to filter queries](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering) in the *Amazon Kendra Developer Guide*. If the specified filter string isn't valid, you will get an `InvalidLambdaResponseException` exception. The `kendraQueryFilterString` string overrides any query string specified in the `queryFilterString` configured for the intent.
+ `kendraQueryRequestPayload` – Use this string to specify an Amazon Kendra query. Your query can use any of the features of Amazon Kendra. If you don't specify a valid query, you get a `InvalidLambdaResponseException` exception. For more information, see [Query](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html) in the *Amazon Kendra Developer Guide*.

After you have created the filter or query string, you send the response to Amazon Lex V2 with the `dialogAction` field of the response set to `delegate`. Amazon Lex V2 sends the query to Amazon Kendra and then returns the query response to the fulfillment code hook.

### Using the Fulfillment Code Hook for the Response


After Amazon Lex V2 sends a query to Amazon Kendra, the query response is returned to the `AMAZON.KendraSearchIntent` fulfillment Lambda function. The input event to the code hook contains the complete response from Amazon Kendra. The query data is in the same structure as the one returned by the Amazon Kendra `Query` operation. For more information, see [ Query response syntax](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax) in the *Amazon Kendra Developer Guide*.

The fulfillment code hook is optional. If one does not exist, or if the code hook doesn't return a message in the response, Amazon Lex V2 uses the `closingResponse` statement for responses.

# Example: Creating a FAQ Bot for an Amazon Kendra Index


This example creates an Amazon Lex V2 bot that uses an Amazon Kendra index to provide answers to users' questions. The FAQ bot manages the dialog for the user. It uses the `AMAZON.KendraSearchIntent` intent to query the index and to present the response to the user. Here is a summary of how you will create your FAQ bot using an Amazon Kendra index:

1. Create a bot that your customers will interact with to get answers from your bot.

1. Create a custom intent. Because the `AMAZON.KendraSearchIntent` and `AMAZON.FallbackIntent` are backup intents, your bot requires at least one other intent that must contain least one utterance. This intent enables your bot to build, but is not used otherwise. Your FAQ bot will therefore contain at least three intents, as in the image below:   
![\[A Kendra FAQ bot with three intents\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/kendra-faqbot/kendra-intents.png)

1. Add the `AMAZON.KendraSearchIntent` intent to your bot and configure it to work with your [Amazon Kendra index](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html). 

1. Test the bot by making a query and verifying that the results from your Amazon Kendra index are documents that answer the query.

**Prerequisites**

Before you can use this example, you need to create an Amazon Kendra index. For more information, see [Getting started with the Amazon Kendra console](https://docs.aws.amazon.com/kendra/latest/dg/gs-console.html) in the *Amazon Kendra Developer Guide*. For this example, choose the sample dataset (**Sample AWS documentation**) as your data source.

**To create a FAQ bot:**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. In the navigation pane, choose **Bots**. 

1. Choose **Create bot**.

   1.  For the **Creation method**, choose **Create a blank bot**. 

   1.  In the **Bot configuration** section, give the bot a name that indicates its purpose, such as **KendraTestBot**, and an optional description. The name must be unique in your account. 

   1.  In the **IAM Permissions** section, choose **Create a role with basic Amazon Lex permissions**. This will create an [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) role with the permissions that Amazon Lex V2 needs to run your bot. 

   1.  In the **Children's Online Privacy Protection Act (COPPA)** section, choose **No**. 

   1.  In the **Idle session timeout** and **Advanced settings** sections, leave the default settings and choose **Next**. 

   1.  Now you are in the **Add language to bot** section. In the menu under **Voice interaction**, select **None. This is only a text based application**. Leave the default settings for the remaining fields. 

   1.  Choose **Done**. Amazon Lex V2 creates your bot and a default intent called **NewIntent**, and takes you to the page to configure this intent 

To successfully build a bot, you must create at least one intent that is separate from the `AMAZON.FallbackIntent` and the `AMAZON.KendraSearchIntent`. This intent is required to build your Amazon Lex V2 bot, but isn't used for the FAQ response. This intent must contain at least one sample utterance and the utterance must not apply to any of the questions that your customer asks.

**To create the required intent:**

1.  In the **Intent details** section, give the intent a name, such as **RequiredIntent**. 

1.  In the **Sample utterances** section, type an utterance in the box next to **Add utterance**, such as **Required utterance**. Then choose **Add utterance**. 

1. Choose **Save intent**.

Create the intent to search an Amazon Kendra index and the response message that it should return.

**To create an AMAZON.KendraSearchIntent intent and response message:**

1.  Select **Back to intents list** in the navigation pane to return to the **Intents** page for your bot. Choose **Add intent** and select **Use built-in intent** from the dropdown menu. 

1.  In the box that pops up, select the menu under **Built-in intent.** Enter **AMAZON.KendraSearchIntent** in the search bar and then choose it from the list. 

1.  Give the intent a name, such as **KendraSearchIntent**. 

1.  From the **Amazon Kendra index** dropdown menu, choose the index that you want the intent to search. The index that you created in the **Prerequisites** section should be available. 

1.  Select **Add**. 

1. In the intent editor, scroll down to the **Fulfillment** section, select the right arrow to expand the section, and add the following message in the box under **On successful fulfillment**: 

   ```
   I found a link to a document that could help you: ((x-amz-lex:kendra-search-response-document-link-1)).
   ```  
![\[Add the fulfillment response\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/kendra-faqbot/kendra-fulfillment-response.gif)

    For more information about the Amazon Kendra Search Response, see [ Using the Search Response](https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html#kendra-search-response). 

1. Choose **Save intent**, and then choose **Build** to build the bot. When the bot is ready, the banner at the top of the screen turns green and displays a success message. 

Finally, use the console test window to test responses from your bot.

**To test your FAQ bot:**

1.  After the bot is successfully built, choose **Test**. 

1.  Enter **What is Amazon Kendra?** in the console test window. Verify that the bot responds with a link. 

1.  For more information about configuring `AMAZON.KendraSearchIntent`, see [https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html](https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html) and [KendraConfiguration](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_KendraConfiguration.html). 