

# Using AppInstanceBots as intelligent channel agents for Amazon Chime SDK messaging
<a name="appinstance-bots"></a>

You can use `AppInstanceBots` as intelligent channel agents. The agents recognize key phrases sent via `ChannelMessages` by channel members. The bot's natural language understanding model resolves the messages. In turn, that allows one or more channel members to engage in a natural language dialog defined by the bot's model. You supply the bots, so you control the depth of dialog and integration with your enterprise systems.

**Prerequisites**
+ Knowledge of basic Amazon Chime SDK functionality, such as creating `AppInstanceUsers`, managing channels, and sending and receiving messages.
+ The ability to invoke the Amazon Chime SDK Messaging APIs.
+ Knowledge of basic Amazon Lex V2 functionality, such as creating an Amazon Lex V2 Bot, modeling intents and slots, creating bot versions, aliases, using session state, and Lambda hook integration.

**Important**  
Use of Amazon Lex V2 is subject to the [AWS Service Terms](https://aws.amazon.com/service-terms/), including the terms specific to the AWS Machine Learning and Artificial Intelligence Services.

**Topics**
+ [Creating an Amazon Lex V2 bot for Amazon Chime SDK messaging](create-lex-bot.md)
+ [Setting up AppInstance bots for Amazon Chime SDK messaging](appinstance-bot-setup.md)
+ [Creating a channel membership for an AppInstanceBot for Amazon Chime SDK messaging](channel-membership.md)
+ [Sending messages to an AppInstanceBot for Amazon Chime SDK messaging](message-appinstancebot.md)
+ [Processing messages from Amazon Lex for Amazon Chime SDK messaging](process-from-lexv2.md)
+ [Processing responses from an AppInstanceBot for Amazon Chime SDK messaging](process-response.md)
+ [Using rules to send events to Amazon EventBridge for Amazon Chime SDK messaging](event-bridge-alerts.md)
+ [Troubleshooting AppInstanceBots configured with Amazon Lex V2 bots for Amazon Chime SDK messaging](troubleshoot-lex-bots.md)

# Creating an Amazon Lex V2 bot for Amazon Chime SDK messaging
<a name="create-lex-bot"></a>

To use AppInstance bots as agents, you first need to create an Amazon Lex V2 bot to manage the dialog interaction for an intelligent-agent scenario. To get started building an Amazon Lex V2 bot, see [Getting Started with Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/getting-started.html) in the *Amazon Lex V2 Developer Guide*. For information about migrating an Amazon Lex V1 bot to Amazon Lex V2, see the [Amazon Lex V1 to V2 migration guide](https://docs.aws.amazon.com/lexv2/latest/dg/migration.html).

**Topics**
+ [Prerequisites](#lex-prereqs)
+ [Granting invocation permissions](#invocation-perms)
+ [Creating a welcome intent for Amazon Chime SDK messaging](welcome-intent.md)
+ [Creating Amazon Lex V2 bot versions for Amazon Chime SDK messaging](lex-versions.md)
+ [Creating Amazon Lex V2 bot aliases for Amazon Chime SDK messaging](lex-aliases.md)

## Prerequisites
<a name="lex-prereqs"></a>

Your Amazon Lex V2 bot must have the following prerequisites.
+ You must create the bot in an AWS Region that supports Amazon Lex V2 runtime endpoints.
+ You must create the bot in the same AWS account and Region as the `AppInstance` and `AppInstanceBot`.
+ The bot must grant invocation permissions via a resource-based policy to the `messaging.chime.amazonaws.com` service principal.
+ The bot can model a Welcome Intent. This allows `AppInstanceBot` to announce itself and its capabilities upon membership in a channel.
+ The bot should have a production version and aliases in order to configure the `AppInstanceBot`.
+ The bot must use a supported language and locale. For more information about languages and locales, see [Languages and locales supported in Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html) in the *Amazon Lex V2 Developer Guide*.

## Granting invocation permissions
<a name="invocation-perms"></a>

For an `AppInstanceBot` to invoke an Amazon Lex V2 Bot, the Amazon Chime SDK messaging service principal must have permission to invoke the Amazon Lex Bot resource. For more information about Amazon Lex V2 resource-based policy permissions, see [Resource-based policy examples for Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/security_iam_resource-based-policy-examples.html) in the *Amazon Lex V2 Developer Guide*.

The following example shows a resource-based policy.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "messaging.chime.amazonaws.com"
      },
      "Action": [
        "lex:PutSession",
        "lex:DeleteSession",
        "lex:RecognizeText"
      ],
      "Resource": "arn:aws:lex:us-east-1:111122223333:bot-alias/lex-bot-id/lex-bot-alias-id",
      "Condition": {
        "StringEquals": {
        "AWS:SourceAccount": "111122223333"
        },
        "ArnEquals": {
        "AWS:SourceArn": "arn:aws:chime:us-east-1:111122223333:app-instance/app-instance-id/bot/app-instance-bot-id"
        }
      }
    }
  ]
}
```

------

**Note**  
To allow one `AppInstanceBot` to invoke an Amazon Lex V2 bot, use the AppInstanceBot's ID. To allow all `AppInstanceBots` within an `AppInstance` to invoke an Amazon Lex V2 bot, use a wildcard. For example:  
`arn:aws:chime:region:aws-account-id:app-instance/app-instance-id/bot/*`

# Creating a welcome intent for Amazon Chime SDK messaging
<a name="welcome-intent"></a>

If you add an optional welcome intent to your Amazon Lex V2 bot model, your `AppInstanceBot` can announce itself and its capabilities when it joins a channel. The welcome intent can display a message, or it can initiate a dialog with channel members. The name of the of welcome intent can vary, and you define it in the AppInstanceBot's configuration.

For more information about intents, see [Adding intents](https://docs.aws.amazon.com/lexv2/latest/dg/build-intents.html) in the *Amazon Lex V2 Developer Guide*

# Creating Amazon Lex V2 bot versions for Amazon Chime SDK messaging
<a name="lex-versions"></a>

When you create an Amazon Lex V2 Bot, you only create a *draft* version. The draft is a working copy of the bot that you can update. By default, the draft version is associated with an alias called `TestBotAlias`, and you should only use the draft bot for manual testing.

After you finish dialog modeling and building the draft bot, you create one or more *versions*, numbered snapshots of the draft Lex bot. Versions allow you to control the implementation that your client applications use. For example, you can publish versions for use in different parts of your workflow, such as development, beta deployment, and production.

For more information about Lex bot versioning, see [Creating versions](https://docs.aws.amazon.com/lexv2/latest/dg/versions.html) in the *Amazon Lex V2 Developer Guide*.

# Creating Amazon Lex V2 bot aliases for Amazon Chime SDK messaging
<a name="lex-aliases"></a>

Once you create one or more versions of an Amazon Lex V2 bot, you create *aliases*. Aliases act as named pointers to the versions of an Amazon Lex V2 bot. For example, You can only associate an alias with one version at a time.

For more information about Lex bot aliases, see [Creating aliases](https://docs.aws.amazon.com/lexv2/latest/dg/aliases.html) in the *Lex V2 Developer Guide*.

# Setting up AppInstance bots for Amazon Chime SDK messaging
<a name="appinstance-bot-setup"></a>

After you have an Amazon Lex V2 bot with a model, version, and alias, you use the Amazon Chime SDK messaging APIs or the CLI to create an AppInstanceBot. For more information about using the APIs, see to the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_identity-chime_CreateAppInstanceBot.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_identity-chime_CreateAppInstanceBot.html) API documentation.

**Note**  
You use the `InvokedBy` attribute to configure the dialog interaction behavior of the `AppInstanceBot`. You can configure the types of message that trigger a bot, such as standard messages or targeted messages.

The following example shows how to use the AWS CLI to create an AppInstanceBot that all standard messages with `MENTIONS`, and targeted messages, can invoke.

```
aws chime-sdk-identity create-app-instance-bot \
--app-instance-arn app-instance-arn \
--name app-instance-bot-name \
--configuration '{
   "Lex": {
      "LexBotAliasArn": "lex-bot-alias-arn",
      "LocaleId": "lex_bot_alias_locale_id",
      "InvokedBy": {
          "StandardMessages": "MENTIONS",
          "TargetedMessages": "ALL"
      }
      "WelcomeIntent": "welcome-intent-name"
   }
}
```

# Creating a channel membership for an AppInstanceBot for Amazon Chime SDK messaging
<a name="channel-membership"></a>

Once you create the AppInstanceBot, you add it as a member to a new or existing channel. For more information see [CreateChannel](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_messaging-chime_CreateChannel.html) and [ CreateChannelMembership](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_messaging-chime_CreateChannelMembership.html) in the *Amazon Chime SDK messaging API* documentation.

The following example shows how to use the AWS CLI to create a channel and add an `AppInstanceBot` as a member.

```
aws chime-sdk-messaging create-channel \
--chime-bearer caller_app_instance_user_arn \
--app-instance-arn app_instance_arn \
--name channel_name \
--member-arns '[
   "app_instance_bot_arn"
]'
```

The following example shows how to use the AWS CLI to add an `AppInstanceBot` to an existing channel.

```
aws chime-sdk-messaging create-channel-membership \
--chime-bearer caller_app_instance_user_arn \
--channel-arn channel_arn \
--member-arn app_instance_bot_arn
```

# Sending messages to an AppInstanceBot for Amazon Chime SDK messaging
<a name="message-appinstancebot"></a>

You use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_messaging-chime_SendChannelMessage.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_messaging-chime_SendChannelMessage.html) API to send messages to an AppInstanceBot. You send the messages to the channel in which the AppInstanceBot is a member. If the [natural language understanding model](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html) recognizes the message content and elicits an Amazon Lex intent, the AppInstanceBot responds with a channel message and initiates a dialog.

You can also send target messages to a member of the channel, which could be an AppInstanceUser or an AppInstanceBot. Only the target and the sender can view targeted messages. Only users who can see targeted messages can take actions on them. However, administrators can delete targeted messages that they can’t see. 

The following example shows how to use the AWS CLI to send a channel message.

```
aws chime-sdk-messaging send-channel-message \
--chime-bearer caller_app_instance_user_arn \
--channel-arn channel_arn \
--content content \
--type STANDARD \
--persistence PERSISTENT
```

# Processing messages from Amazon Lex for Amazon Chime SDK messaging
<a name="process-from-lexv2"></a>

When sending messages to Amazon Lex, Amazon Chime SDK Messaging populates the `CHIME.channel.arn` and `CHIME.sender.arn` with the channel and sender’s ARN information as request attributes. You can use the attributes to determine who sent a message and the channel the sender belongs to. For more information, refer to [ Enabling custom logic with AWS Lambda functions](https://docs.aws.amazon.com/lexv2/latest/dg/lambda.html) in the *Amazon Lex Developer Guide*.

# Processing responses from an AppInstanceBot for Amazon Chime SDK messaging
<a name="process-response"></a>

When a user sends a message, the AppInstanceBot responds with a channel message. You can list channel messages to get the bot's response. 

The following example shows you to use the CLI to list channel messages.

```
aws chime-sdk-messaging list-channel-messages \
--chime-bearer caller_app_instance_user_arn \
--channel-arn channel_arn
```

Success responses from an AppInstanceBot take the following format. 

```
{
    "MessageId": "messageId",
    "Content": "*{\"Messages\":[{\"...\"}]}*",
    "ContentType": "application/amz-chime-lex-msgs",
    "MessageAttributes": {
        "CHIME.LEX.sessionState.intent.name": {
            "StringValues": [
                "lex_bot_intent_name"
            ]
        },
        "CHIME.LEX.sessionState.intent.state": {
            "StringValues": [
                "lex_bot_intent_fullfilment_status"
            ]
        },
        "CHIME.LEX.sessionState.originatingRequestId": {
            "StringValues": [
                "lex_bot_originating_request_id"
            ]
        },
        "CHIME.LEX.sessionState.sessionId": {
            "StringValues": [
                "lex_bot_session_id"
            ]
        }
    },
    "Sender": {
        "Arn": "app_instance_bot_arn",
        "Name": "app_instance_bot_name"
    },
    "Type": "STANDARD",
}
```

**Content**  
The `Content` field contains a list of messages originating from the Amazon Lex V2 bot. For more information about those messages, refer to [ messages](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeText.html#lexv2-runtime_RecognizeText-response-messages) in the Amazon Lex V2 `RecognizeText` API.  
The following example shows how to use the `Content` field in a welcome message.  

```
{
    "Messages":
    [
        {
            "Content": "Hello!",
            "ContentType": "PlainText"
        },
        {
            "ContentType": "ImageResponseCard",
            "ImageResponseCard":
            {
                "Title": "Hello! I'm BB, the Bank Bot.",
                "Subtitle": "I can help you with the following transactions",
                "Buttons":
                [
                    {
                        "Text": "Check balance",
                        "Value": "Check balance"
                    },
                    {
                        "Text": "Escalate to agent",
                        "Value": "Escalate to agent"
                    }
                ]
            }
        }
    ]
}
```
For a failure response, the Content field contains an error message and code in the following format:  

```
{
    "Code": error_code
}
```

**ContentType**  
The `ContentType` refers to the type of payload the `Content` field contains, and must be checked to parse the `Content` field.   
The Lex V2 bot uses a different `ContentType`.
`ContentType` is set to `application/amz-chime-lex-msgs` for a success response, or `application/amz-chime-lex-error` for a failure response.

**MessageAttributes**  
A *MessageAttribute* is a map of string keys to string values. A response from an `AppInstanceBot` contains the following message attributes mapped to a response from an Amazon Lex bot.   
+ **CHIME.LEX.sessionState.intent.name** – The name of the Lex bot intent that the request attempted to fulfill.
+ **CHIME.LEX.sessionState.intent.state** – The current state of the intent. Possible values include: `Fulfilled`, `InProgress`, and `Failed`. 
+ **CHIME.LEX.sessionState.originatingRequestId** – A unique identifier for a specific request to Amazon Lex bot. This is set to the `MessageId` of the originating user message that triggered the AppInstanceBot.
+ **CHIME.LEX.sessionState.sessionId** – A unique identifier for a conversation between the user and the bot. When a user starts a chat with your bot, Amazon Lex creates a session.
For more information about Amazon Lex sessions and session states, refer to [https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_SessionState.html](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_SessionState.html) in the *Amazon Lex API Reference*, and [Managing sessions](https://docs.aws.amazon.com/lexv2/latest/dg/using-sessions.html) in the *in the Amazon Lex V2 Developer Guide*  
For more information about the attributes that Amazon Lex V2 returns, refer to the [Amazon Lex Runtime V2](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_Operations_Amazon_Lex_Runtime_V2.html) APIs.

# Using rules to send events to Amazon EventBridge for Amazon Chime SDK messaging
<a name="event-bridge-alerts"></a>

The Amazon Chime SDK delivers EventBridge events when an error prevents it from invoking the Amazon Lex V2 Bot. You can create EventBridge rules that recognize those events and automatically take action when the rule is matched. For more information, see [ Amazon EventBridge rules](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html) in the *Amazon EventBridge User Guide*.

The following example shows a typical failure event.

```
{
  version: '0',
  id: '12345678-1234-1234-1234-111122223333',
  'detail-type': 'Chime Messaging AppInstanceBot Lex Failure',
  source: 'aws.chime',
  account: 'aws-account-id',
  time: 'yyyy-mm-ddThh:mm:ssZ',
  region: "region",
  resources: [],
  detail: {    
    resourceArn: 'arn:aws:chime:region:aws-account-id:app-instance/app-instance-id/bot/app-instance-bot-id',
    failureReason: "1 validation error detected: Value at 'text' failed to satisfy constraint: Member must have length less than or equal to 1024 (Service: LexRuntimeV2, Status Code: 400, Request ID: request-id)"
  }
}
```

# Troubleshooting AppInstanceBots configured with Amazon Lex V2 bots for Amazon Chime SDK messaging
<a name="troubleshoot-lex-bots"></a>

The following topics explain how to troubleshoot common problems with AppInstanceBots.

## Finding Amazon Lex V2 failures
<a name="find-lex-failures"></a>

The Amazon Chime SDK messaging delivers [Amazon EventBridge events](https://docs.aws.amazon.com/chime-sdk/latest/dg/event-bridge-alerts.html) when an error prevents it from invoking the Amazon Lex V2 bot. For more information about setting up rules and configuring notification targets, refer to [Getting started with Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-get-started.html) in the *Amazon EventBridge User Guide*.

If you receive EventBridge events in AWS CloudWatch Logs, you can use AWS CloudWatch Logs Insights to query EventBridge events based on the Amazon Chime SDK messaging detail-type. The `failureReason` lists the cause of the failure. 

The following example shows a typical query.

```
fields @timestamp, @message
| filter `detail-type` = "Chime Messaging AppInstanceBot Lex Failure"
| sort @timestamp desc
```

If Amazon Chime SDK Messaging can invoke your Amazon Lex V2 bot, the SDK sends `CONTROL` messages with an error message.

## Troubleshooting Amazon Lex V2 bot permission errors
<a name="lex-permission-errors"></a>

For an AppInstanceBot to invoke an Amazon Lex V2 Bot, the Amazon Chime SDK messaging service principal must have permission to invoke the Amazon Lex V2 Bot resource. Also, ensure the `AWS:SourceArn` of the resource policy condition matches the ARN of the AppInstanceBot.

For more information about configuring an AppInstanceBot to invoke an Amazon Lex V2 bot, refer to [Creating an Amazon Lex V2 bot for Amazon Chime SDK messaging](create-lex-bot.md), earlier in this section.

## Troubleshooting Amazon Lex V2 bot throttling
<a name="lex-throttling"></a>

Amazon Lex has a service quota for the maximum number of concurrent text-mode conversations per bot alias. You can contact the Amazon Lex service team for quota increases. For more information, refer to [Amazon Lex guidelines and quotas](https://docs.aws.amazon.com/lexv2/latest/dg/quotas.html) in the *Amazon Lex Developer Guide*.