

# Using Amazon Augmented AI for Human Review
Augmented AI


|  | 
| --- |
|  This feature is not available in the China Regions.  | 

When you use AI applications such as Amazon Rekognition, Amazon Textract, or your custom machine learning (ML) models, you can use Amazon Augmented AI to get human review of low-confidence predictions or random prediction samples.
<a name="what-is-amazon-augmented-ai-a2i"></a>
**What is Amazon Augmented AI?**  
Amazon Augmented AI (Amazon A2I) is a service that brings human review of ML predictions to all developers by removing the heavy lifting associated with building human review systems or managing large numbers of human reviewers. 

Many ML applications require humans to review low-confidence predictions to ensure the results are correct. For example, extracting information from scanned mortgage application forms can require human review due to low-quality scans or poor handwriting. Building human review systems can be time-consuming and expensive because it involves implementing complex processes or *workflows*, writing custom software to manage review tasks and results, and managing large groups of reviewers.

Amazon A2I streamlines building and managing human reviews for ML applications. Amazon A2I provides built-in human review workflows for common ML use cases, such as content moderation and text extraction from documents. You can also create your own workflows for ML models built on SageMaker AI or any other tools. Using Amazon A2I, you can allow human reviewers to step in when a model is unable to make a high-confidence prediction or to audit its predictions on an ongoing basis. 
<a name="a2i-use-cases-intro"></a>
**Amazon A2I Use Case Examples**  
The following examples demonstrate how you can use Amazon A2I to integrate a human review loop into your ML application. For each of these examples, you can find a Jupyter Notebook that demonstrates that workflow in [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md). 
+ **Use Amazon A2I with Amazon Textract** – Have humans review important key-value pairs in single-page documents or have Amazon Textract randomly sample and send documents from your dataset to humans for review. 
+ **Use Amazon A2I with Amazon Rekognition** – Have humans review unsafe images for explicit adult or violent content if Amazon Rekognition returns a low-confidence score, or have Amazon Rekognition randomly sample and send images from your dataset to humans for review.
+ **Use Amazon A2I to review real-time ML inferences** – Use Amazon A2I to review real-time, low-confidence inferences made by a model deployed to a SageMaker AI hosted endpoint and incrementally train your model using Amazon A2I output data.
+ **Use Amazon A2I with Amazon Comprehend** – Have humans review Amazon Comprehend inferences about text data such as sentiment analysis, text syntax, and entity detection.
+ **Use Amazon A2I with Amazon Transcribe** – Have humans review Amazon Transcribe transcriptions of video or audio files. Use the results of transcription human review loops to create a custom vocabulary and improve future transcriptions of similar video or audio content.
+ **Use Amazon A2I with Amazon Translate** – Have humans review low-confidence translations returned from Amazon Translate.
+ **Use Amazon A2I to review tabular data** – Use Amazon A2I to integrate a human review loop into an ML application that uses tabular data.

![\[Amazon Augmented AI - How It Works\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/amazon-augmented-ai-how-it-works.png)


**Topics**
+ [

# Get Started with Amazon Augmented AI
](a2i-getting-started.md)
+ [

# Use Cases and Examples Using Amazon A2I
](a2i-task-types-general.md)
+ [

# Create a Human Review Workflow
](a2i-create-flow-definition.md)
+ [

# Delete a Human Review Workflow
](a2i-delete-flow-definition.md)
+ [

# Create and Start a Human Loop
](a2i-start-human-loop.md)
+ [

# Delete a Human Loop
](a2i-delete-human-loop.md)
+ [

# Create and Manage Worker Task Templates
](a2i-instructions-overview.md)
+ [

# Monitor and Manage Your Human Loop
](a2i-monitor-humanloop-results.md)
+ [

# Amazon A2I Output Data
](a2i-output-data.md)
+ [

# Permissions and Security in Amazon Augmented AI
](a2i-permissions-security.md)
+ [

# Use Amazon CloudWatch Events in Amazon Augmented AI
](a2i-cloudwatch-events.md)
+ [

# Use APIs in Amazon Augmented AI
](a2i-api-references.md)

# Get Started with Amazon Augmented AI


To get started using Amazon Augmented AI, review the [Core Components of Amazon A2I](a2i-getting-started-core-components.md) and [Prerequisites to Using Augmented AI](a2i-getting-started-prerequisites.md). Then, use the following documentation to learn how to use the Amazon A2I console and API. 
+ [Tutorial: Get Started in the Amazon A2I Console](a2i-get-started-console.md)
+ [Tutorial: Get Started Using the Amazon A2I API](a2i-get-started-api.md)

You can also get stared using the Amazon A2I API by following a Jupyter Notebook tutorial. See [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md) for a list of notebooks and use cases. 

# Core Components of Amazon A2I


Review the following terms to familiarize yourself with the core components of Amazon A2I. 

## Task Types


The AI/ML workflow into which you integrate Amazon A2I defines an Amazon A2I *task type*. 

Amazon A2I supports:
+ Two *built-in task types*: [Amazon Textract key-value pair extraction](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-textract-task-type.html) and [Amazon Rekognition image moderation](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-rekognition-task-type.html).
+ A [custom task type](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-task-types-custom.html): Use a custom task type to integrate a human review loop into *any* machine learning workflow. You can use a custom task type to integrate Amazon A2I with other Amazon services like Amazon Comprehend, Amazon Transcribe, and Amazon Translate, as well as your own custom machine learning workflows. To learn more, see [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md).

Select a tab in the following table to see diagrams that illustrate how Amazon A2I works with each task type. Select the task type page using the links in the preceding list to learn more about that task type.

------
#### [ Amazon Textract – Key-value pair extraction ]

This image depicts the Amazon A2I built-in workflow with Amazon Textract. On the left, the resources that are required to create an Amazon Textract human review workflow are depicted: an Amazon S3 bucket, activation conditions, a worker task template, and a work team. These resources are used to create a human review workflow, or flow definition. An arrow points right to the next step in the workflow: using Amazon Textract to configure a human loop with the human review workflow. A second arrow points right from this step to the step in which activation conditions specified in the human review workflow are met. This initiates the creation of a human loop. On the right of the image, the human loop is depicted in three steps: 1) the worker UI and tools are generated and the task is made available to workers, 2) workers review input data, and finally, 3) results are saved in Amazon S3.

![\[Amazon A2I built-in workflow with Amazon Textract\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/diagrams/product-page-diagram_A21-Components_Textract@2x.png)


------
#### [ Amazon Rekognition – Image moderation ]

This image depicts the Amazon A2I built-in workflow with Amazon Rekognition. On the left, the resources that are required to create an Amazon Rekognition human review workflow are depicted: an Amazon S3 bucket, activation conditions, a worker task template, and a work team. These resources are used to create a human review workflow, or flow definition. An arrow points right to the next step in the workflow: using Amazon Rekognition to configure a human loop with the human review workflow. A second arrow points right from this step to the step in which activation conditions specified in the human review workflow are met. This initiates the creation of a human loop. On the right of the image, the human loop is depicted in three steps: 1) the worker UI and tools are generated and the task is made available to workers, 2) workers review input data, and finally, 3) results are saved in Amazon S3.

![\[Amazon A2I built-in workflow with Amazon Rekognition\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/diagrams/product-page-diagram_A2I-Components_Rekognition@2x.png)


------
#### [ Custom Task Type ]

The following image depicts the Amazon A2I custom workflow. A custom ML model is used to generate predictions. The client application filters these predictions using user-defined criteria and determines if a human review is required. If so, these predictions are sent to Amazon A2I for human review. Amazon A2I collects the results of human review in Amazon S3, which can access by the client application. If the filter determines that no human review is needed, predictions can be fed directly to the client application. 

![\[Amazon A2I custom workflow\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/diagrams/product-page-diagram_A2I-Components_Custom@2x.png)


------

## Human Review Workflow (Flow Definition)


You use a human review workflow to specify your human *work team*, to set up your worker UI using a *worker task template*, and to provide information about how workers should complete the review task. 

For built-in task types, you also use the human review workflow to identify the conditions under which a human loop is initiated. For example, Amazon Rekognition can perform image content moderation using machine learning. You can use the human review workflow to specify that an image is sent to a human for content moderation review if Amazon Rekognition's confidence is too low.

You can use a human review workflow to create multiple human loops.

You can create a flow definition in the SageMaker AI console or with the SageMaker API. To learn more about both of these options, see [Create a Human Review Workflow](a2i-create-flow-definition.md).

**Work Team**  
A *work team* is a group of human workers to whom you send your human review tasks.

When you create a human review workflow, you specify a single work team. 

Your work team can come from the [Amazon Mechanical Turk workforce](https://docs.amazonaws.cn/sagemaker/latest/dg/sms-workforce-management-public.html), a [vendor-managed workforce](https://docs.amazonaws.cn/sagemaker/latest/dg/sms-workforce-management-vendor.html), or your own [private workforce](https://docs.amazonaws.cn/sagemaker/latest/dg/sms-workforce-private.html). When you use the private workforce, you can create multiple work teams. Each work team can be used in multiple human review workflows. To learn how to create a workforce and work teams, see [Workforces](sms-workforce-management.md).

**Worker Task Template and Human Task UI**  
You use a *worker task template* to create a worker UI (a *human task UI*) for your human review tasks.

The human task UI displays your input data, such as documents or images, and instructions to workers. It also provides interactive tools that the worker uses to complete your tasks. 

For built-in task types, you must use the Amazon A2I worker task template provided for that task type.

## Human Loops


A *human loop* is used to create a single human review job. For each human review job, you can choose the number of workers that are sent a *task* to review a single data object. For example, if you set the number of workers per object to `3` for an image classification labeling job, three workers classify each input image. Increasing the number of workers per object can improve label accuracy.

A human loop is created using a human review workflow as follows:
+ For built-in task types, the conditions specified in the human review workflow determine when the human loop is created.
+ Human review tasks are sent to the work team specified in the human review workflow. 
+ The worker task template specified in the human review workflow is used to render the human task UI. 

**When do human loops get created?**

When you use one of the *built-in task types*, the corresponding Amazon service creates and starts a human loop on your behalf when the conditions specified in your human review workflow are met. For example:
+ When you use Augmented AI with Amazon Textract, you can integrate Amazon A2I into a document review task using the API operation `AnalyzeDocument`. A human loop is created every time Amazon Textract returns inferences about key-value pairs that meet the conditions you specify in your human review workflow. 
+ When you use Augmented AI with Amazon Rekognition, you can integrate Amazon A2I into an image moderation task using the API operation `DetectModerationLabels`. A human loop is created every time Amazon Rekognition returns inferences about image content that meet the conditions you specify in your human review workflow.

When using a *custom task type*, you start a human loop using the [Amazon Augmented AI Runtime API](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/Welcome.html). When you call `StartHumanLoop` in your custom application, a task is sent to human reviewers. 

To learn how to create and start a human loop, see [Create and Start a Human Loop](a2i-start-human-loop.md).

To generate these resources and create a human review workflow, Amazon A2I integrates multiple APIs, including the Amazon Augmented AI Runtime Model, the SageMaker APIs, and APIs associated with your task type. To learn more, see [Use APIs in Amazon Augmented AI](a2i-api-references.md).

**Note**  
Amazon Region availability may differ when you use Augmented AI with other Amazon services, such as Amazon Textract. Create Augmented AI resources in the same Amazon Region that you use to interact with those Amazon services. For Amazon Region availability for all services, see the [Region Table](https://www.amazonaws.cn/about-aws/global-infrastructure/regional-product-services/).

# Prerequisites to Using Augmented AI


Amazon A2I uses resources in IAM, SageMaker AI, and Amazon S3 to create and run your human review workflows. You can create some of these resources in the Amazon A2I console when you create a human review workflow. To learn how, see [Tutorial: Get Started in the Amazon A2I Console](a2i-get-started-console.md).

To use Amazon A2I, you need the following resources:
+ One or more Amazon S3 buckets in the same Amazon Region as the workflow for your input and output data. To create a bucket, follow the instructions in [ Create a Bucket](https://docs.amazonaws.cn/AmazonS3/latest/user-guide/create-bucket.html) in the *Amazon Simple Storage Service Console User Guide*. 
+ An IAM role with required permissions to create a human review workflow and an IAM user or role with permission to access Augmented AI. For more information, see [Permissions and Security in Amazon Augmented AI](a2i-permissions-security.md).
+ A public, private, or vendor workforce for your human review workflows. If you plan to use a private workforce, you need to set one up ahead of time in the same Amazon Region as your Amazon A2I workflow. To learn more about these workforce types, see [Workforces](sms-workforce-management.md).
**Important**  
To learn about the compliance programs that cover Amazon Augmented AI at this time, see [Amazon Services in Scope by Compliance Program](https://www.amazonaws.cn/compliance/services-in-scope/). If you use Amazon Augmented AI in conjunction with other Amazon services (such as Amazon Rekognition and Amazon Textract), note that Amazon Augmented AI may not be in scope for the same compliance programs as those other services. You are responsible for how you use Amazon Augmented AI, including understanding how the service processes or stores customer data and any impact on the compliance of your data environment. You should discuss your workload objectives and goals with your Amazon account team; they can help you evaluate whether the service is a good fit for your proposed use case and architecture.

# Tutorial: Get Started in the Amazon A2I Console


The following tutorial shows you how to get started using Amazon A2I in the Amazon A2I console.

The tutorial gives you the option to use Augmented AI with Amazon Textract for document review or Amazon Rekognition for image content review.

## Prerequisites


To get started using Amazon A2I, complete the following prerequisites. 
+ Create an Amazon S3 bucket in the same Amazon Region as the workflow for your input and output data. For example, if you are using Amazon A2I with Amazon Textract in us-east-1, create your bucket in us-east-1. To create a bucket, follow the instructions in [Create a Bucket](https://docs.amazonaws.cn/AmazonS3/latest/user-guide/create-bucket.html) in the *Amazon Simple Storage Service Console User Guide*. 
+ Do one of the following:
  + If you want to complete the tutorial using Amazon Textract, download the following image and place it in your Amazon S3 bucket.  
![\[Brief employment application\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/getting-started/sample-document-final.png)
  + If you want to complete the tutorial using Amazon Rekognition, download the following image and place it in your Amazon S3 bucket.  
![\[Woman in bikini doing yoga on beach\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/getting-started/yoga_swimwear_resized.jpg)

**Note**  
The Amazon A2I console is embedded in the SageMaker AI console. 

## Step 1: Create a Work Team


First, create a work team in the Amazon A2I console and add yourself as a worker so that you can preview the worker review task.

**Important**  
This tutorial uses a private work team. The Amazon A2I private workforce is configured in the Ground Truth area of the SageMaker AI console and is shared between Amazon A2I and Ground Truth. 

**To create a private workforce using worker emails**

1. Open the SageMaker AI console at [https://console.amazonaws.cn/sagemaker/](https://console.amazonaws.cn/sagemaker/). 

1. In the navigation pane, choose **Labeling workforces** under **Ground Truth**.

1. Choose **Private**, then choose **Create private team**.

1. Choose **Invite new workers by email**.

1. For this tutorial, enter your email and any others that you want to be able to preview the human task UI. You can paste or type a list of up to 50 email addresses, separated by commas, into the email addresses box.

1. Enter an organization name and contact email.

1. Optionally, choose an Amazon SNS topic to which to subscribe the team so workers are notified by email when new Ground Truth labeling jobs become available. Amazon SNS notifications are supported by Ground Truth and are not supported by Augmented AI. If you subscribe workers to Amazon SNS notifications, they only receive notifications about Ground Truth labeling jobs. They do not receive notifications about Augmented AI tasks. 

1.  Choose **Create private team**. 

If you add yourself to a private work team, you receive an email from `no-reply@verificationemail.com` with login information. Use the link in this email to reset your password and log in to your worker portal. This is where your human review tasks appear when you create a human loop.

## Step 2: Create a Human Review Workflow


In this step, you create a human review workflow. Each human review workflow is created for a specific [task type](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-task-types-general.html). This tutorial allows you to choose between the built-in task types: Amazon Rekognition and Amazon Textract. 

**To create a human review workflow:**

1. Open the Augmented AI console at [https://console.amazonaws.cn/a2i](https://console.amazonaws.cn/a2i/) to access the **Human review workflows** page. 

1. Select **Create human review workflow**.

1. In **Workflow settings**, enter a workflow **Name**, **S3 bucket**, and the **IAM role** that you created for this tutorial, with the Amazon managed policy `AmazonAugmentedAIIntegratedAPIAccess` attached.

1. For **Task type**, select **Textract – Key-value pair extraction** or **Rekognition – Image moderation**.

1. Select the task type that you chose from the following table for instructions for that task type. 

------
#### [ Amazon Textract – Key-value pair extraction ]

   1. Select **Trigger a human review for specific form keys based on the form key confidence score or when specific form keys are missing**. 

   2. For **Key name**, enter `Mail Address`. 

   3. Set the identification confidence threshold between `0` and `99`. 

   4. Set the qualification confidence threshold between `0` and `99`.

   5. Select **Trigger a human review for all form keys identified by Amazon Textract with confidence scores in a specific range**.

   6. Set the identification confidence threshold between `0` and `90`. 

   7. Set the qualification confidence threshold between `0` and `90`.

   This initiates a human review if Amazon Textract returns a confidence score that is less than `99` for `Mail Address` and its key, or if it returns a confidence score less than `90` for any key value pair detected in the document.

   The following image shows the Amazon Textract form extraction - Conditions for invoking human review section of the Amazon A2I console. In the image, the check boxes for the two types of triggers explained in the proceeding paragraph are checked, and `Mail Address` is used as a **Key name** for the first trigger. The identification confidence threshold is defined using confidence scores for key-value pairs detect within the form and is set between 0 and 99. The qualification confidence threshold is defined using confidence scores for text contained within keys and values in a form and is set between 0 and 99. 

![\[Amazon A2I console showing the conditions for invoking human review section.\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/getting-started/Textract-conditions.png)


------
#### [ Amazon Rekognition – Image moderation ]

   1. Select **Trigger human review for labels identified by Amazon Rekognition based on label confidence score**.

   2. Set the **Threshold** between `0` and `98`. 

   This initiates a human review if Amazon Rekognition returns a confidence score that is less than `98` for an image moderation job. 

   The following image shows how you can select the **Trigger human review for labels identified by Amazon Rekognition based on label confidence score** option and enter a **Threshold** between 0 and 98 in the Amazon A2I console.

![\[Amazon A2I console showing the conditions for invoking human review section.\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/getting-started/Rek-conditions.png)


------

1. Under **Worker task template creation**, select **Create from a default template**.

1. Enter a **Template name**.

1. In **Task description** field, enter the following text:

   `Read the instructions carefully and complete the task.`

1. Under **Workers**, select **Private**.

1. Select the private team that you created.

1. Choose **Create**.

Once your human review workflow is created, it appears in the table on the **Human review workflows** page. When the **Status** is `Active`, copy and save the Workflow ARN. You need it for the next step. 

## Step 3: Start a Human Loop


You must use an API operation to start a human loop. There are a variety of language-specific SDKs that you can use to interact with these API operations. To see documentation for each of these SDKs, refer to the **See Also** section in the API documentation, as shown in the following image.

![\[Screenshot of the See Also section of the Amazon Textract API documentation\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/getting-started/see-also.png)


For this tutorial, you use one of the following APIs:
+ If you chose the Amazon Textract task type, you use the `[AnalyzeDocument](https://docs.amazonaws.cn/textract/latest/dg/API_AnalyzeDocument.html)` operation.
+ If you chose the Amazon Rekognition task type, you use the `[DetectModerationLabels](https://docs.amazonaws.cn/rekognition/latest/dg/API_DetectModerationLabels.html)` operation.

You can interact with these APIs using a SageMaker notebook instance (recommended for new users) or the Amazon Command Line Interface (Amazon CLI). Choose one of the following to learn more about these options:
+ To learn more about and set up a notebook instance, see [Amazon SageMaker notebook instances](nbi.md).
+ To learn more about and get started using the Amazon CLI, see [What Is the Amazon Command Line Interface?](https://docs.amazonaws.cn/cli/latest/userguide/cli-chap-welcome.html) in the *Amazon Command Line Interface User Guide*.

Select your task type in the following table to see example requests for Amazon Textract and Amazon Rekognition using the Amazon SDK for Python (Boto3). 

------
#### [ Amazon Textract – Key-value pair extraction ]

The following example uses the Amazon SDK for Python (Boto3) to call `analyze_document` in us-west-2. Replace the italicized red text with your resources. Include the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html) parameter if you are using the Amazon Mechanical Turk workforce. For more information, see the `[analyze\$1document](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/textract.html#Textract.Client.analyze_document)` documention in the *Amazon SDK for Python (Boto) API Reference*.

```
   response = client.analyze_document(
         Document={
                "S3Object": {
                    "Bucket": "amzn-s3-demo-bucket", 
                    "Name": "document-name.pdf"
                }
         },
         HumanLoopConfig={
            "FlowDefinitionArn":"arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
            "HumanLoopName":"human-loop-name",
            "DataAttributes" : {
                "ContentClassifiers":["FreeOfPersonallyIdentifiableInformation","FreeOfAdultContent"]
            }
         },
         FeatureTypes=["TABLES", "FORMS"])
```

------
#### [ Amazon Rekognition – Image moderation ]

The following example uses the Amazon SDK for Python (Boto3) to call `detect_moderation_labels` in us-west-2. Replace the italicized red text with your resources. Include the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html) parameter if you are using the Amazon Mechanical Turk workforce. For more information, see the `[detect\$1moderation\$1labels](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.detect_moderation_labels)` documentation in the *Amazon SDK for Python (Boto) API Reference*.

```
   response = client.detect_moderation_labels(
            Image={
                "S3Object":{
                    "Bucket": "amzn-s3-demo-bucket", 
                    "Name": "image-name.png"
                }
            },
            HumanLoopConfig={
               "FlowDefinitionArn":"arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
               "HumanLoopName":"human-loop-name",
               "DataAttributes":{
                    ContentClassifiers:["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]
                }
             })
```

------

## Step 4: View Human Loop Status in Console


When you start a human loop, you can view its status in the Amazon A2I console. 

**To view your human loop status**

1. Open the Augmented AI console at [https://console.amazonaws.cn/a2i](https://console.amazonaws.cn/a2i/) to access the **Human review workflows** page. 

1. Select the human review workflow that you used to start your human loop.

1. In the **Human loops** section, you can see your human loop. View its status in the **Status** column.

## Step 5: Download Output Data


Your output data is stored in the Amazon S3 bucket you specified when you created a human review workflow.

**To view your Amazon A2I output data**

1. Open the [Amazon S3 console](https://console.amazonaws.cn/s3/).

1. Select the Amazon S3 bucket you specified when you created your human review workflow in step 2 of this example. 

1. Starting with the folder that is named after your human review workflow, navigate to your output data by selecting the folder with the following naming convention:

   ```
   s3://output-bucket-specified-in-human-review-workflow/human-review-workflow-name/YYYY/MM/DD/hh/mm/ss/human-loop-name/output.json
   ```

1. Select `output.json` and choose **Download**. 

# Tutorial: Get Started Using the Amazon A2I API


This tutorial explains the API operations you can use to get started using Amazon A2I. 

To use a Jupyter Notebook to run these operations, select a Jupyter Notebook from [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md) and use [Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook](a2i-task-types-general.md#a2i-task-types-notebook-demo) to learn how to use it in a SageMaker AI notebook instance.

To learn more about the API operations you can use with Amazon A2I, see [Use APIs in Amazon Augmented AI](a2i-api-references.md).

## Create a Private Work Team


You can create a private work team and add yourself as a worker so that you can preview Amazon A2I. 

If you are not familiar with Amazon Cognito, we recommend that you use the SageMaker AI console to create a private workforce and add yourself as a private worker. For instructions, see [Step 1: Create a Work Team](a2i-get-started-console.md#a2i-get-started-console-step-1).

If you are familiar with Amazon Cognito, you can use the following instructions to create a private work team using the SageMaker API. After you create a work team, note the work team ARN (`WorkteamArn`).

To learn more about the private workforce and other available configurations, see [Private workforce](sms-workforce-private.md).

**Create a private workforce**  
If you have not created a private workforce, you can do so using an [Amazon Cognito user pool](https://docs.amazonaws.cn/cognito/latest/developerguide/cognito-user-identity-pools.html). Make sure that you have added yourself to this user pool. You can create a private work team using the Amazon SDK for Python (Boto3) `[create\$1workforce](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_workforce)` function. For other language-specific SDKs, refer to the list in [CreateWorkforce](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateWorkforce.html#API_CreateWorkforce_SeeAlso).

```
    
    response = client.create_workforce(
        CognitoConfig={
            "UserPool": "Pool_ID",
            "ClientId": "app-client-id"
        },
        WorkforceName="workforce-name"
    )
```

**Create a private work team**  
After you have created a private workforce in the Amazon Region to configure and start your human loop, you can create a private work team using the Amazon SDK for Python (Boto3) `[create\$1workteam](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_workteam)` function. For other language-specific SDKs, refer to the list in `[CreateWorkteam](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateWorkteam.html#API_CreateWorkteam_SeeAlso)`.

```
    response = client.create_workteam(
        WorkteamName="work-team-name",
        WorkforceName= "workforce-name",
        MemberDefinitions=[
            {
                "CognitoMemberDefinition": {
                    "UserPool": "<aws-region>_ID",
                    "UserGroup": "user-group",
                    "ClientId": "app-client-id"
                },
            }
        ]
    )
```

Access your work team ARN as follows:

```
    workteamArn = response["WorkteamArn"]
```

**List private work teams in your account**  
If you have already created a private work team, you can list all work teams in a given Amazon Region in your account using the Amazon SDK for Python (Boto3) `[list\$1workteams](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.list_workteams)` function. For other language-specific SDKs, refer to the list in `[ListWorkteams](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_ListWorkteams.html#API_ListWorkteams_SeeAlso)`. 

```
    response = client.list_workteams()
```

If you have numerous work teams in your account, you may want to use `MaxResults`, `SortBy`, and `NameContains` to filter your results.

## Create a Human Review Workflow


You can create a human review workflow using the Amazon A2I `[CreateFlowDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateFlowDefinition.html)` operation. Before you create your human review workflow, you need to create a human task UI. You can do this with the `[CreateHumanTaskUi](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html)` operation.

If you are using Amazon A2I with the Amazon Textract or Amazon Rekognition integrations, you can specify activation conditions using a JSON. 

### Create a Human Task UI


If you are creating a human review workflow to be used with Amazon Textract or Amazon Rekognition integrations, you need to use and modify pre-made worker task template. For all custom integrations, you can use your own custom worker task template. Use the following table to learn how to create a human task UI using a worker task template for the two built-in integrations. Replace the template with your own to customize this request. 

------
#### [ Amazon Textract – Key-value pair extraction ]

To learn more about this template, see [Custom Template Example for Amazon Textract](a2i-custom-templates.md#a2i-custom-templates-textract-sample).

------
#### [ Amazon Rekognition – Image moderation ]

To learn more about this template, see [Custom Template Example for Amazon Rekognition](a2i-custom-templates.md#a2i-custom-templates-rekognition-sample).

------
#### [ Custom Integration ]

The following is an example template that can be used in a custom integration. This template is used in this [notebook](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Comprehend%20DetectSentiment.ipynb), demonstrating a custom integration with Amazon Comprehend.

------

Using the template specified above, you can create a template using the Amazon SDK for Python (Boto3) `[create\$1human\$1task\$1ui](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_human_task_ui)` function. For other language-specific SDKs, refer to the list in `[CreateHumanTaskUi](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html#API_CreateHumanTaskUi_SeeAlso)`. 

```
    
    response = client.create_human_task_ui(
        HumanTaskUiName="human-task-ui-name",
        UiTemplate={
            "Content": template
        }
    )
```

This response element contains the human task UI ARN. Save this as follows:

```
    humanTaskUiArn = response["HumanTaskUiArn"]
```

### Create JSON to specify activation conditions


For Amazon Textract and Amazon Rekognition built-in integrations, you can save activation conditions in a JSON object and use this in your `CreateFlowDefinition` request. 

Next, select a tab to see example activation conditions you can use for these built-in integrations. For additional information about activation condition options, see [JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI](a2i-human-fallback-conditions-json-schema.md).

------
#### [ Amazon Textract – Key-value pair extraction ]

This example specifies conditions for specific keys (such as `Mail address`) in the document. If Amazon Textract's confidence falls outside of the thresholds set here, the document is sent to a human for review, with the specific keys that initiated the human loop prompted to the worker.

```
      import json  

      humanLoopActivationConditions = json.dumps(
        {
            "Conditions": [
                {
                  "Or": [
                    
                    {
                        "ConditionType": "ImportantFormKeyConfidenceCheck",
                        "ConditionParameters": {
                            "ImportantFormKey": "Mail address",
                            "ImportantFormKeyAliases": ["Mail Address:","Mail address:", "Mailing Add:","Mailing Addresses"],
                            "KeyValueBlockConfidenceLessThan": 100,
                            "WordBlockConfidenceLessThan": 100
                        }
                    },
                    {
                        "ConditionType": "MissingImportantFormKey",
                        "ConditionParameters": {
                            "ImportantFormKey": "Mail address",
                            "ImportantFormKeyAliases": ["Mail Address:","Mail address:","Mailing Add:","Mailing Addresses"]
                        }
                    },
                    {
                        "ConditionType": "ImportantFormKeyConfidenceCheck",
                        "ConditionParameters": {
                            "ImportantFormKey": "Phone Number",
                            "ImportantFormKeyAliases": ["Phone number:", "Phone No.:", "Number:"],
                            "KeyValueBlockConfidenceLessThan": 100,
                            "WordBlockConfidenceLessThan": 100
                        }
                    },
                    {
                      "ConditionType": "ImportantFormKeyConfidenceCheck",
                      "ConditionParameters": {
                        "ImportantFormKey": "*",
                        "KeyValueBlockConfidenceLessThan": 100,
                        "WordBlockConfidenceLessThan": 100
                      }
                    },
                    {
                      "ConditionType": "ImportantFormKeyConfidenceCheck",
                      "ConditionParameters": {
                        "ImportantFormKey": "*",
                        "KeyValueBlockConfidenceGreaterThan": 0,
                        "WordBlockConfidenceGreaterThan": 0
                      }
                    }
            ]
        }
            ]
        }
    )
```

------
#### [ Amazon Rekognition – Image moderation ]

The human loop activation conditions used here are tailored towards Amazon Rekognition content moderation; they are based on the confidence thresholds for the `Suggestive` and `Female Swimwear Or Underwear` moderation labels.

```
        import json  

        humanLoopActivationConditions = json.dumps(
        {
            "Conditions": [
                {
                  "Or": [
                    {
                        "ConditionType": "ModerationLabelConfidenceCheck",
                        "ConditionParameters": {
                            "ModerationLabelName": "Suggestive",
                            "ConfidenceLessThan": 98
                        }
                    },
                    {
                        "ConditionType": "ModerationLabelConfidenceCheck",
                        "ConditionParameters": {
                            "ModerationLabelName": "Female Swimwear Or Underwear",
                            "ConfidenceGreaterThan": 98
                        }
                    }
                  ]
               }
            ]
        }
    )
```

------

### Create a human review workflow


This section gives an example of the `CreateFlowDefinition` Amazon SDK for Python (Boto3) request using the resources created in the previous sections. For other language-specific SDKs, refer to the list in [CreateFlowDefinition](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html#API_CreateFlowDefinition_SeeAlso). Use the tabs in the following table to see the requests to create a human review workflow for Amazon Textract and Amazon Rekognition built-in integrations.

------
#### [ Amazon Textract – Key-value pair extraction ]

If you use the built-in integration with Amazon Textract, you must specify `"AWS/Textract/AnalyzeDocument/Forms/V1"` for `"AwsManagedHumanLoopRequestSource"` in `HumanLoopRequestSource`. 

```
    response = client.create_flow_definition(
        FlowDefinitionName="human-review-workflow-name",
        HumanLoopRequestSource={
            "AwsManagedHumanLoopRequestSource": "AWS/Textract/AnalyzeDocument/Forms/V1"
        }, 
        HumanLoopActivationConfig={
            "HumanLoopActivationConditionsConfig": {
                "HumanLoopActivationConditions": humanLoopActivationConditions
            }
        },
        HumanLoopConfig={
            "WorkteamArn": workteamArn,
            "HumanTaskUiArn": humanTaskUiArn,
            "TaskTitle": "Document entry review",
            "TaskDescription": "Review the document and instructions. Complete the task",
            "TaskCount": 1,
            "TaskAvailabilityLifetimeInSeconds": 43200,
            "TaskTimeLimitInSeconds": 3600,
            "TaskKeywords": [
                "document review",
            ],
        },
        OutputConfig={
            "S3OutputPath": "s3://amzn-s3-demo-bucket/prefix/",
        },
        RoleArn="arn:aws:iam::<account-number>:role/<role-name>",
        Tags=[
            {
                "Key": "string",
                "Value": "string"
            },
        ]
    )
```

------
#### [ Amazon Rekognition – Image moderation ]

If you use the built-in integration with Amazon Rekognition, you must specify `"AWS/Rekognition/DetectModerationLabels/Image/V3"` for `"AwsManagedHumanLoopRequestSource"` in `HumanLoopRequestSource`.

```
    response = client.create_flow_definition(
        FlowDefinitionName="human-review-workflow-name",
        HumanLoopRequestSource={
            "AwsManagedHumanLoopRequestSource": "AWS/Rekognition/DetectModerationLabels/Image/V3"
        }, 
        HumanLoopActivationConfig={
            "HumanLoopActivationConditionsConfig": {
                "HumanLoopActivationConditions": humanLoopActivationConditions
            }
        },
        HumanLoopConfig={
            "WorkteamArn": workteamArn,
            "HumanTaskUiArn": humanTaskUiArn,
            "TaskTitle": "Image content moderation",
            "TaskDescription": "Review the image and instructions. Complete the task",
            "TaskCount": 1,
            "TaskAvailabilityLifetimeInSeconds": 43200,
            "TaskTimeLimitInSeconds": 3600,
            "TaskKeywords": [
                "content moderation",
            ],
        },
        OutputConfig={
            "S3OutputPath": "s3://amzn-s3-demo-bucket/prefix/",
        },
        RoleArn="arn:aws:iam::<account-number>:role/<role-name>",
        Tags=[
            {
                "Key": "string",
                "Value": "string"
            },
        ]
    )
```

------
#### [ Custom Integration ]

If you use a custom integration, exclude the following parameters: `HumanLoopRequestSource`, `HumanLoopActivationConfig`.

```
    response = client.create_flow_definition(
        FlowDefinitionName="human-review-workflow-name",
        HumanLoopConfig={
            "WorkteamArn": workteamArn,
            "HumanTaskUiArn": humanTaskUiArn,
            "TaskTitle": "Image content moderation",
            "TaskDescription": "Review the image and instructions. Complete the task",
            "TaskCount": 1,
            "TaskAvailabilityLifetimeInSeconds": 43200,
            "TaskTimeLimitInSeconds": 3600,
            "TaskKeywords": [
                "content moderation",
            ],
        },
        OutputConfig={
            "S3OutputPath": "s3://amzn-s3-demo-bucket/prefix/",
        },
        RoleArn="arn:aws:iam::<account-number>:role/<role-name>",
        Tags=[
            {
                "Key": "string",
                "Value": "string"
            },
        ]
    )
```

------

After you create a human review workflow, you can retrieve the flow definition ARN from the response:

```
    humanReviewWorkflowArn = response["FlowDefinitionArn"]    
```

## Create a Human Loop


The API operation you use to start a human loop depends on the Amazon A2I integration you use. 
+ If you use the Amazon Textract built-in integration, you use the [AnalyzeDocument](https://docs.amazonaws.cn/textract/latest/dg/API_AnalyzeDocument.html) operation.
+ If you use the Amazon Rekognition built-in integration, you use the [DetectModerationLabels](https://docs.amazonaws.cn/rekognition/latest/dg/API_DetectModerationLabels.html) operation.
+ If you use a custom integration, you use the [StartHumanLoop](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_StartHumanLoop.html) operation. 

Select your task type in the following table to see example requests for Amazon Textract and Amazon Rekognition using the Amazon SDK for Python (Boto3). 

------
#### [ Amazon Textract – Key-value pair extraction ]

The following example uses the Amazon SDK for Python (Boto3) to call `analyze_document` in us-west-2. Replace the italicized red text with your resources. Include the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html) parameter if you are using the Amazon Mechanical Turk workforce. For more information, see the [analyze\$1document](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/textract.html#Textract.Client.analyze_document) documention in the *Amazon SDK for Python (Boto) API Reference*.

```
   response = client.analyze_document(
         Document={"S3Object": {"Bucket": "amzn-s3-demo-bucket", "Name": "document-name.pdf"},
         HumanLoopConfig={
            "FlowDefinitionArn":"arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
            "HumanLoopName":"human-loop-name",
            "DataAttributes" : {ContentClassifiers:["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]}
         }
         FeatureTypes=["FORMS"]
    )
```

Human loops are only created if Amazon Textract's confidence for document analysis task meets the activation conditions you specified in your human review workflow. You can check the `response` element to determine if a human loop has been created. To see everything included in this response, see [https://docs.amazonaws.cn/textract/latest/dg/API_HumanLoopActivationOutput.html](https://docs.amazonaws.cn/textract/latest/dg/API_HumanLoopActivationOutput.html).

```
    if "HumanLoopArn" in analyzeDocumentResponse["HumanLoopActivationOutput"]:
        # A human loop has been started!
        print(f"A human loop has been started with ARN: {analyzeDocumentResponse["HumanLoopActivationOutput"]["HumanLoopArn"]}"
```

------
#### [ Amazon Rekognition – Image moderation ]

The following example uses the Amazon SDK for Python (Boto3) to call `detect_moderation_labels` in us-west-2. Replace the italicized red text with your resources. Include the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html) parameter if you are using the Amazon Mechanical Turk workforce. For more information, see the [detect\$1moderation\$1labels](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.detect_moderation_labels) documention in the *Amazon SDK for Python (Boto) API Reference*.

```
   response = client.detect_moderation_labels(
            Image={"S3Object":{"Bucket": "amzn-s3-demo-bucket", "Name": "image-name.png"}},
            HumanLoopConfig={
               "FlowDefinitionArn":"arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
               "HumanLoopName":"human-loop-name",
               "DataAttributes":{ContentClassifiers:["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]}
             }
    )
```

Human loops are only created if Amazon Rekognition's confidence for an image moderation task meets the activation conditions you specified in your human review workflow. You can check the `response` element to determine if a human loop has been created. To see everything included in this response, see [https://docs.amazonaws.cn/rekognition/latest/dg/API_HumanLoopActivationOutput.html](https://docs.amazonaws.cn/rekognition/latest/dg/API_HumanLoopActivationOutput.html).

```
    if "HumanLoopArn" in response["HumanLoopActivationOutput"]:
        # A human loop has been started!
        print(f"A human loop has been started with ARN: {response["HumanLoopActivationOutput"]["HumanLoopArn"]}")
```

------
#### [ Custom Integration ]

The following example uses the Amazon SDK for Python (Boto3) to call `start_human_loop` in us-west-2. Replace the italicized red text with your resources. Include the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopDataAttributes.html) parameter if you are using the Amazon Mechanical Turk workforce. For more information, see the [start\$1human\$1loop](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-a2i-runtime.html#AugmentedAIRuntime.Client.start_human_loop) documention in the *Amazon SDK for Python (Boto) API Reference*.

```
   response = client.start_human_loop(
        HumanLoopName= "human-loop-name",
        FlowDefinitionArn= "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
        HumanLoopInput={"InputContent": inputContentJson},
        DataAttributes={"ContentClassifiers":["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]}
   )
```

This example stores input content in the variable *`inputContentJson`*. Assume that the input content contains two elements: a text blurb and sentiment (such as `Positive`, `Negative`, or `Neutral`), and it is formatted as follows:

```
    inputContent = {
        "initialValue": sentiment,
         "taskObject": blurb
     }
```

The keys `initialValue` and `taskObject` must correspond to the keys used in the liquid elements of the worker task template. Refer to the custom template in [Create a Human Task UI](#a2i-get-started-api-worker-task-template) to see an example. 

To create `inputContentJson`, do the following: 

```
    import json
    
    inputContentJson = json.dumps(inputContent)
```

A human loop starts each time you call `start_human_loop`. To check the status of your human loop, use [describe\$1human\$1loop](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-a2i-runtime.html#AugmentedAIRuntime.Client.describe_human_loop): 

```
    human_loop_info = a2i.describe_human_loop(HumanLoopName="human_loop_name")
    print(f"HumanLoop Status: {resp["HumanLoopStatus"]}")
    print(f"HumanLoop Output Destination: {resp["HumanLoopOutput"]}")
```

------

# Use Cases and Examples Using Amazon A2I
Use Cases and Examples

You can use Amazon Augmented AI to incorporate a human review into your workflow for *built-in task types*, Amazon Textract and Amazon Rekognition, or your own custom tasks using a *custom task type*. 

When you create a human review workflow using one of the built-in task types, you can specify conditions, such as confidence thresholds, that initiate a human review. The service (Amazon Rekognition or Amazon Textract) creates a human loop on your behalf when these conditions are met and supplies your input data directly to Amazon A2I to send to human reviewers. To learn more about the built-in task types, use the following:
+ [Use Amazon Augmented AI with Amazon Textract](a2i-textract-task-type.md)
+ [Use Amazon Augmented AI with Amazon Rekognition](a2i-rekognition-task-type.md)

When you use a custom task type, you create and start a human loop using the Amazon A2I Runtime API. Use the custom task type to incorporate a human review workflow with other Amazon services or your own custom ML application.
+ For more details, see [Use Amazon Augmented AI with Custom Task Types](a2i-task-types-custom.md)

The following table outlines a variety of Amazon A2I use cases that you can explore using SageMaker AI Jupyter Notebooks. To get started with a Jupyter Notebook, use the instructions in [Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook](#a2i-task-types-notebook-demo). For more examples, see this [GitHub repository](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks). 


****  

| **Use Case** | **Description** | **Task Type** | 
| --- | --- | --- | 
|  [Use Amazon A2I with Amazon Textract](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Textract%20AnalyzeDocument.ipynb)  |  Have humans review single-page documents to review important form key-value pairs, or have Amazon Textract randomly sample and send documents from your dataset to humans for review.   | Built-in | 
| [Use Amazon A2I with Amazon Rekognition](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Rekognition%20DetectModerationLabels.ipynb) |  Have humans review unsafe images for explicit adult or violent content if Amazon Rekognition returns a low confidence score, or have Amazon Rekognition randomly sample and send images from your dataset to humans for review.  |  Built-in  | 
| [Use Amazon A2I with Amazon Comprehend](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Comprehend%20DetectSentiment.ipynb) |  Have humans review Amazon Comprehend inferences about text data such as sentiment analysis, text syntax, and entity detection.  |  Custom  | 
| [Use Amazon A2I with Amazon Transcribe](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/A2I-Video-Transcription-with-Amazon-Transcribe.ipynb) |  Have humans review Amazon Transcribe transcriptions of video or audio files. Use the results of transcription human review loops to create a custom vocabulary and improve future transcriptions of similar video or audio content.  | Custom | 
| [Use Amazon A2I with Amazon Translate](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Amazon%20Translate.ipynb) |  Have humans review low-confidence translations returned from Amazon Translate.  |  Custom  | 
| [Use Amazon A2I to review real time ML inferences](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20A2I%20with%20Amazon%20SageMaker%20for%20object%20detection%20and%20model%20retraining.ipynb)  |  Use Amazon A2I to review real-time, low-confidence inferences made by a model deployed to a SageMaker AI hosted endpoint and incrementally train your model using Amazon A2I output data.  |  Custom  | 
| [Use Amazon A2I to review tabular data](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(Amazon%20A2I)%20Integration%20with%20tabular%20data.ipynb) |  Use Amazon A2I to integrate a human review loop into an ML application that uses tabular data.  |  Custom  | 

**Topics**
+ [

## Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook
](#a2i-task-types-notebook-demo)
+ [

# Use Amazon Augmented AI with Amazon Textract
](a2i-textract-task-type.md)
+ [

# Use Amazon Augmented AI with Amazon Rekognition
](a2i-rekognition-task-type.md)
+ [

# Use Amazon Augmented AI with Custom Task Types
](a2i-task-types-custom.md)

## Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook


For an end-to-end example that demonstrates how to integrate an Amazon A2I human review loop into a machine learning workflow, you can use a Jupyter Notebook from this [GitHub Repository](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks) in a SageMaker notebook instance.

**To use an Amazon A2I custom task type sample notebook in an Amazon SageMaker notebook instance:**

1. If you do not have an active SageMaker notebook instance, create one by following the instructions in [Create an Amazon SageMaker Notebook Instance for the tutorial](gs-setup-working-env.md).

1. When your notebook instance is active, choose **Open JupyterLab** to the right of the notebook instance's name. It may take a few moments for JupyterLab to load. 

1. Choose the add Github repository icon (![\[Diagonal arrow icon with N and 1 symbols, representing a one-to-many relationship.\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/icons/Git_squip_add_repo.png)) to clone a GitHub repository into your workspace. 

1. Enter the [amazon-a2i-sample-jupyter-notebooks](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks) repository HTTPS URL. 

1. Choose **CLONE**.

1. Open the notebook that you would like to run. 

1. Follow the instructions in the notebook to configure your human review workflow and human loop and run the cells. 

1. To avoid incurring unnecessary charges, when you are done with the demo, stop and delete your notebook instance in addition to any Amazon S3 buckets, IAM roles, and CloudWatch Events resources created during the walkthrough.

# Use Amazon Augmented AI with Amazon Textract
Use with Amazon Textract

Amazon Textract enables you to add document text detection and analysis to your applications. Amazon Augmented AI (Amazon A2I) directly integrates with Amazon Textract's `AnalyzeDocument` API operation. You can use `AnalyzeDocument` to analyze a document for relationships between detected items. When you add an Amazon A2I human review loop to an `AnalyzeDocument` request, Amazon A2I monitors the Amazon Textract results and sends a document to one or more human workers for review when the conditions specified in your flow definition are met. For example, if you want a human to review a specific key like `Full name:` and their associated input values, you can create an activation condition that starts a human review any time the `Full name:` key is detected or when the inference confidence for that key falls within a range that you specify. 

The following image depicts the Amazon A2I built-in workflow with Amazon Textract. On the left, the resources that are required to create an Amazon Textract human review workflow are depicted: and Amazon S3 bucket, activation conditions, a worker task template, and a work team. These resources are used to create a human review workflow, or flow definition. An arrow points right to the next step in the workflow: using Amazon Textract to configure a human loop with the human review workflow. A second arrow points right from this step to the step in which activation conditions specified in the human review workflow are met. This initiates the creation of a human loop. On the right of the image, the human loop is depicted in three steps: 1) the worker UI and tools are generated and the task is made available to workers,2) workers review input data, and finally, 3) results are saved in Amazon S3.

![\[Use Amazon Augmented AI with Amazon Textract\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/diagrams/product-page-diagram_A21-Components_Textract@2x.png)


You can specify when Amazon Textract sends a task to a human worker for review when creating a human review workflow or flow definition by specifying *activation conditions*. 

You can set the following activation conditions when using the Amazon Textract task type:
+ Initiate a human review for specific form keys based on the form key confidence score. 
+ Initiate a human review when specific form keys are missing. 
+ Initiate human review for all form keys identified by Amazon Textract with confidence scores in a specified range.
+ Randomly send a sample of forms to humans for review.

When your activation condition depends on form key confidence scores, you can use two types of prediction confidence to initiate human loops:
+ **Identification confidence** – The confidence score for key-value pairs detected within a form.
+ **Qualification confidence** – The confidence score for text contained within key and value in a form.

In the image in the following section, **Full Name: Jane Doe** is the key-value pair, **Full Name** is the key, and **Jane Doe** is the value.

You can set these activation conditions using the Amazon SageMaker AI console when you create a human review workflow, or by creating a JSON for human loop activation conditions and specifying this as input in the `HumanLoopActivationConditions` parameter of `CreateFlowDefinition` API operation. To learn how specify activation conditions in JSON format, see [JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI](a2i-human-fallback-conditions-json-schema.md) and [Use Human Loop Activation Conditions JSON Schema with Amazon Textract](a2i-json-humantaskactivationconditions-textract-example.md).

**Note**  
When using Augmented AI with Amazon Textract, create Augmented AI resources in the same Amazon Region you use to call `AnalyzeDocument`. 

## Get Started: Integrate a Human Review into an Amazon Textract Analyze Document Job


To integrate a human review into an Amazon Textract text detection and analysis job, you need to create a flow definition, and then use the Amazon Textract API to integrate that flow definition into your workflow. To learn how to create a flow definition using the SageMaker AI console or Augmented AI API, see the following topics:
+ [Create a Human Review Workflow (Console)](a2i-create-flow-definition.md#a2i-create-human-review-console)
+ [Create a Human Review Workflow (API)](a2i-create-flow-definition.md#a2i-create-human-review-api)

After you've created your flow definition, see [Using Augmented AI with Amazon Textract](https://docs.amazonaws.cn/textract/latest/dg/a2i-textract.html) to learn how to integrate your flow definition into your Amazon Textract task. 

## End-to-End Example Using Amazon Textract and Amazon A2I


For an end-to-end example that demonstrates how to use Amazon Textract with Amazon A2I using the console, see [Tutorial: Get Started in the Amazon A2I Console](a2i-get-started-console.md).

To learn how to use the Amazon A2I API to create and start a human review, you can use [Amazon Augmented AI (Amazon A2I) integration with Amazon Textract's Analyze Document [Example]](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Textract%20AnalyzeDocument.ipynb) in a SageMaker Notebook instance. To get started, see [Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook](a2i-task-types-general.md#a2i-task-types-notebook-demo).

## A2I Textract Worker Console Preview


When they're assigned a review task in an Amazon Textract workflow, workers might see a user interface similar to the following:

![\[Example review task in the A2I Textract worker console.\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i-textract-example.png)


You can customize this interface in the SageMaker AI console when you create your human review definition, or by creating and using a custom template. To learn more, see [Create and Manage Worker Task Templates](a2i-instructions-overview.md).

# Use Amazon Augmented AI with Amazon Rekognition
Use with Amazon Rekognition

Amazon Rekognition makes it easy to add image analysis to your applications. The Amazon Rekognition `DetectModerationLabels` API operation is directly integrated with Amazon A2I so that you can easily create a human loop to review unsafe images, such as explicit adult or violent content. You can use `DetectModerationLabels` to configure a human loop using a flow definition ARN. This enables Amazon A2I to analyze predictions made by Amazon Rekognition and send results to a human for review to ensure they meet the conditions set in your flow definition.

The following image depicts the Amazon A2I built-in workflow with Amazon Rekognition. On the left, the resources that are required to create an Amazon Rekognition human review workflow are depicted: and Amazon S3 bucket, activation conditions, a worker task template, and a work team. These resources are used to create a human review workflow, or flow definition. An arrow points right to the next step in the workflow: using Amazon Rekognition to configure a human loop with the human review workflow. A second arrow points right from this step to the step in which activation conditions specified in the human review workflow are met. This initiates the creation of a human loop. On the right of the image, the human loop is depicted in three steps: 1) the worker UI and tools are generated and the task is made available to workers, 2) workers review input data, and finally, 3) results are saved in Amazon S3.

![\[Use Amazon Augmented AI with Amazon Rekognition\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/diagrams/product-page-diagram_A2I-Components_Rekognition@2x.png)


You can set the following activation conditions when using the Amazon Rekognition task type:
+ Initiate human review for labels identified by Amazon Rekognition based on the label confidence score.
+ Randomly send a sample of images to humans for review.

You can set these activation conditions using the Amazon SageMaker AI console when you create a human review workflow, or by creating a JSON for human loop activation conditions and specifying this as input in the `HumanLoopActivationConditions` parameter of the `CreateFlowDefinition` API operation. To learn how specify activation conditions in JSON format, see [JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI](a2i-human-fallback-conditions-json-schema.md) and [Use Human Loop Activation Conditions JSON Schema with Amazon Rekognition](a2i-json-humantaskactivationconditions-rekognition-example.md).

**Note**  
When using Augmented AI with Amazon Rekognition, create Augmented AI resources in the same Amazon Region you use to call `DetectModerationLabels`. 

## Get Started: Integrate a Human Review into an Amazon Rekognition Image Moderation Job


To integrate a human review into an Amazon Rekognition, see the following topics:
+ [Create a Human Review Workflow (Console)](a2i-create-flow-definition.md#a2i-create-human-review-console)
+ [Create a Human Review Workflow (API)](a2i-create-flow-definition.md#a2i-create-human-review-api)

After you've created your flow definition, see [Using Augmented AI with Amazon Rekognition](https://docs.amazonaws.cn/rekognition/latest/dg/a2i-rekognition.html) to learn how to integrate your flow definition into your Amazon Rekognition task. 

## End-to-end Demo Using Amazon Rekognition and Amazon A2I


For an end-to-end example that demonstrates how to use Amazon Rekognition with Amazon A2I using the console, see [Tutorial: Get Started in the Amazon A2I Console](a2i-get-started-console.md).

To learn how to use the Amazon A2I API to create and start a human review, you can use [Amazon Augmented AI (Amazon A2I) integration with Amazon Rekognition [Example]](https://github.com/aws-samples/amazon-a2i-sample-jupyter-notebooks/blob/master/Amazon%20Augmented%20AI%20(A2I)%20and%20Rekognition%20DetectModerationLabels.ipynb) in a SageMaker notebook instance. To get started, see [Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook](a2i-task-types-general.md#a2i-task-types-notebook-demo).

## A2I Rekognition Worker Console Preview


When they're assigned a review task in an Amazon Rekognition workflow, workers might see a user interface similar to the following:

![\[Example image in the A2I Rekognition worker console.\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i-rekognition-example.png)


You can customize this interface in the SageMaker AI console when you create your human review definition, or by creating and using a custom template. To learn more, see [Create and Manage Worker Task Templates](a2i-instructions-overview.md).

# Use Amazon Augmented AI with Custom Task Types
Use With Custom Task Types

You can use Amazon Augmented AI (Amazon A2I) to incorporate a human review (human loop) into *any* machine learning workflow using the *custom task type*. This options gives you the most flexibility to customize the conditions under which your data objects are sent to humans for review, as well as the look and feel of your worker user interface.

When you use a custom task type, you create a custom human review workflow and specify the conditions under which a data object is sent for human review directly in your application. 

The following image depicts the Amazon A2I custom workflow. A custom ML model is used to generate predictions. The client application filters these predictions using user-defined criteria and determines if a human review is required. If so, these predictions are sent to Amazon A2I for human review. Amazon A2I collects the results of human review in Amazon S3, which can access by the client application. If the filter determines that no human review is needed, predictions can be fed directly to the client application. 

![\[Use Amazon Augmented AI with Custom Task Types\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/a2i/diagrams/product-page-diagram_A2I-Components_Custom@2x.png)


Use the procedures on this page to learn how to integrate Amazon A2I into any machine learning workflow using the custom task type. 

**Create a human loop using a flow definition, integrate it into your application, and monitor the results**

1. Complete the Amazon A2I [Prerequisites to Using Augmented AI](a2i-getting-started-prerequisites.md). Note the following: 
   + The path to the Amazon Simple Storage Service (Amazon S3) bucket or buckets where you store your input and output data. 
   + The Amazon Resource Name (ARN) of an Amazon Identity and Access Management (IAM) role with required permissions attached. 
   + (Optional) The ARN of your private workforce, if you plan to use one. 

1. Using HTML elements, create a custom worker template which Amazon A2I uses to generate your worker task UI. To learn how to create a custom template, see [Create Custom Worker Task Templates](a2i-custom-templates.md). 

1. Use the custom worker template from step 2 to generate a worker task template in the Amazon SageMaker AI console. To learn how, see [Create a Worker Task Template](a2i-worker-template-console.md#a2i-create-worker-template-console).

   In the next step, you create a flow definition:
   + If you want to create a flow definition using the SageMaker API, note the ARN of this worker task template for the next step.
   + If you are creating a flow definition using the console, your template automatically appears in **Worker task template** section when you choose **Create human review workflow**.

1. When creating your flow definition, provide the path to your S3 buckets, your IAM role ARN, and your worker template. 
   + To learn how to create a flow definition using the SageMaker AI `CreateFlowDefinition` API, see [Create a Human Review Workflow (API)](a2i-create-flow-definition.md#a2i-create-human-review-api). 
   + To learn how to create a flow definition using the SageMaker AI console, see [Create a Human Review Workflow (Console)](a2i-create-flow-definition.md#a2i-create-human-review-console).

1. Configure your human loop using the [Amazon A2I Runtime API](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/Welcome.html). To learn how, see [Create and Start a Human Loop](a2i-start-human-loop.md). 

1. To control when human reviews are initiated in your application, specify conditions under which `StartHumanLoop` is called in your application. Human loop activation conditions, such as confidence thresholds that initiate the human loop, are not available when using Amazon A2I with custom task types. Every `StartHumanLoop` invocation results in a human review.

Once you have started a human loop, you can manage and monitor your loops using the Amazon Augmented AI Runtime API and Amazon EventBridge (also known as Amazon CloudWatch Events). To learn more, see [Monitor and Manage Your Human Loop](a2i-monitor-humanloop-results.md).

## End-to-end Tutorial Using Amazon A2I Custom Task Types


For an end-to-end examples that demonstrates how to integrate Amazon A2I into a variety of ML workflows, see the table in [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md). To get started using one of these notebooks, see [Use SageMaker Notebook Instance with Amazon A2I Jupyter Notebook](a2i-task-types-general.md#a2i-task-types-notebook-demo).

# Create a Human Review Workflow


Use an Amazon Augmented AI (Amazon A2I) *human review workflow*, or *flow definition*, to specify the following:
+ For the Amazon Textract and Amazon Rekognition built-in task types, the conditions under which your human loop is called
+ The workforce to which your tasks are sent
+ The set of instructions that your workforce receives, which is called a *worker task template*
+ The configuration of your worker tasks, including the number of workers that receive a task and time limits to complete tasks 
+ Where your output data is stored 

You can create a human review workflow in the SageMaker AI console or using the SageMaker AI [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html) operation. You can build a worker task template using the console for Amazon Textract and Amazon Rekognition task types while creating your flow definition.

**Important**  
Human loop activation conditions, which initiate the human loop—for example, confidence thresholds—aren't available for Amazon A2I custom task types. When using the console to create a flow definition for a custom task type, you can't specify activation conditions. When using the Amazon A2I API to create a flow definition for a custom task type, you can't set the `HumanLoopActivationConditions` attribute of the `HumanLoopActivationConditionsConfig` parameter. To control when human reviews are initiated, specify conditions under which `StartHumanLoop` is called in your custom application. In this case, every `StartHumanLoop` invocation results in a human review. For more information, see [Use Amazon Augmented AI with Custom Task Types](a2i-task-types-custom.md).

**Prerequisites**

To create a human review workflow definition, you must have completed the prerequisites described in [Prerequisites to Using Augmented AI](a2i-getting-started-prerequisites.md). 

If you use the API to create a flow definition for any task type, or if you use a custom task type when creating a flow definition in the console, first create a worker task template. For more information, see [Create and Manage Worker Task Templates](a2i-instructions-overview.md).

If you want to preview your worker task template while creating a flow definition for a built-in task type in the console, ensure that you grant the role that you use to create the flow definition permission to access the Amazon S3 bucket that contains your template artifacts using a policy like the one described in [Enable Worker Task Template Previews](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai).



**Topics**
+ [

## Create a Human Review Workflow (Console)
](#a2i-create-human-review-console)
+ [

## Create a Human Review Workflow (API)
](#a2i-create-human-review-api)
+ [

# JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI
](a2i-human-fallback-conditions-json-schema.md)

## Create a Human Review Workflow (Console)


Use this procedure to create a Amazon Augmented AI (Amazon A2I) human review workflow using the SageMaker AI console. If you are new to Amazon A2I, we recommend that you create a private work team using people in your organization, and use this work team's ARN when creating your flow definition. To learn how to set up a private workforce and create a work team, see [Create a Private Workforce (Amazon SageMaker AI Console)](sms-workforce-create-private-console.md). If you have already set up a private workforce, see [Create a Work Team Using the SageMaker AI Console](sms-workforce-management-private-console.md#create-workteam-sm-console) to learn how to add a work team to that workforce.

If you are using Amazon A2I with one of the built-in task types, you can create worker instructions using a default worker task template provided by Augmented AI while creating a human review workflow in the console. To see samples of the default templates provided by Augmented AI, see the built-in task types in [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md).

**To create flow definition (console)**

1. Open the SageMaker AI console at [https://console.amazonaws.cn/sagemaker/](https://console.amazonaws.cn/sagemaker/).

1. In the navigation pane, under the **Augmented AI** section, choose **Human review workflows** and then choose **Create human review workflow**.

1. In **Overview**, do the following:

   1. For **Name**, enter a unique workflow name. The name must be lowercase, unique within the Amazon Region in your account, and can have up to 63 characters. Valid characters include: a-z, 0-9, and - (hyphen).

   1. For **S3 location for output**, enter the S3 bucket where you want to store the human review results. The bucket must be located in the same Amazon Region as the workflow.

   1. For **IAM role**, choose the role that has the required permissions. If you choose a built-in task type and want to preview your worker template in the console, provide a role with the type of policy described in [Enable Worker Task Template Previews](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai) attached.

1. For **Task type**, choose the task type that you want the human worker to perform. 

1. If you chose the Amazon Rekognition or Amazon Textract task type, specify the conditions that invoke human review.
   + For Amazon Rekognition image moderation tasks, choose an inference confidence score threshold interval that initiates human review. 
   + For Amazon Textract tasks, you can initiate a human review when specific form keys are missing or when form key detection confidence is low. You can also initiate a human review if, after evaluating all of the form keys in the text, confidence is lower than your required threshold for any form key. Two variables specify your confidence thresholds: **Identification confidence** and **Qualification confidence**. To learn more about these variables, see [Use Amazon Augmented AI with Amazon Textract](a2i-textract-task-type.md).
   + For both task types, you can randomly send a percentage of data objects (images or forms) and their labels to humans for review. 

1. Configure and specify your worker task template:

   1. If you are using the Amazon Rekognition or Amazon Textract task type:

      1. In the **Create template** section: 
        + To create instructions for your workers using the Amazon A2I default template for Amazon Rekognition and Amazon Textract task types, choose **Build from a default template**.
          + If you choose **Build from a default template**, create your instructions under **Worker task design**: 
            + Provide a **Template name** that is unique in the Amazon Region you are in. 
            + In the **Instructions** section, provide detailed instructions on how to complete your task. To help workers achieve greater accuracy, provide good and bad examples. 
            + (Optional) In **Additional instructions**, provide your workers with additional information and instructions. 

              For information on creating effective instructions, see [Creating Good Worker Instructions](a2i-creating-good-instructions-guide.md).
        + To select a custom template that you've created, choose it from the **Template** menu and provide a **Task description** to briefly describe the task for your workers. To learn how to create a custom template, see [Create a Worker Task Template](a2i-worker-template-console.md#a2i-create-worker-template-console).

   1. If you are using the custom task type:

      1. In the **Worker task template** section, select your template from the list. All of the templates that you have created in the SageMaker AI console appear in this list. To learn how to create a template for custom task types, see [Create and Manage Worker Task Templates](a2i-instructions-overview.md).

1. (Optional) Preview your worker template: 

   For Amazon Rekognition and Amazon Textract task types, you have the option to choose **See a sample worker task** to preview your worker task UI.

   If you are creating a flow definition for a custom task type, you can preview your worker task UI using the `RenderUiTemplate` operation. For more information, see [Preview a Worker Task Template](a2i-custom-templates.md#a2i-preview-your-custom-template).

1. For **Workers**, choose a workforce type.

1. Choose **Create**.

### Next Steps


After you've created a human review workflow, it appears in the console under **Human review workflows**. To see your flow definition's Amazon Resource Name (ARN) and configuration details, choose the workflow by selecting its name. 

If you are using a built-in task type, you can use the flow definition ARN to start a human loop using that Amazon service's API (for example, the Amazon Textract API). For custom task types, you can use the ARN to start a human loop using the Amazon Augmented AI Runtime API. To learn more about both options, see [Create and Start a Human Loop](a2i-start-human-loop.md).

## Create a Human Review Workflow (API)


To create a flow definition using the SageMaker API, you use the `CreateFlowDefinition` operation. After you complete the [Prerequisites to Using Augmented AI](a2i-getting-started-prerequisites.md), use the following procedure to learn how to use this API operation. 

For an overview of the `CreateFlowDefinition` operation, and details about each parameter, see [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html). 

**To create a flow definition (API)**

1. For `FlowDeﬁnitionName`, enter a unique name. The name must be unique within the Amazon Region in your account, and can have up to 63 characters. Valid characters include: a-z, 0-9, and - (hyphen).

1. For `RoleArn`, enter the ARN of the role that you configured to grant access to your data sources.

1. For `HumanLoopConfig`, enter information about the workers and what they should see. For information about each parameter in `HumanLoopConfig`, see [HumanLoopConfig](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html#sagemaker-CreateFlowDefinition-request-HumanLoopActivationConfig).

1. (Optional) If you are using a built-in task type, provide conditions that initiate a human loop in `HumanLoopActivationConﬁg`. To learn how to create the input required for the `HumanLoopActivationConﬁg` parameter, see [JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI](a2i-human-fallback-conditions-json-schema.md). If you do not specify conditions here, when you provide a flow definition to the Amazon service associated with a built-in task type (for example, Amazon Textract or Amazon Rekognition), that service sends every task to a human worker for review. 

   If you are using a custom task type, `HumanLoopActivationConfig` is disabled. To learn how to control when tasks are sent to human workers using a custom task type, see [Use Amazon Augmented AI with Custom Task Types](a2i-task-types-custom.md).

1. (Optional) If you are using a built-in task type, specify the integration source (for example, Amazon Rekognition or Amazon Textract) in the [HumanLoopRequestSource](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_HumanLoopRequestSource.html) parameter.

1. For `OutputConfig`, indicate where in Amazon Simple Storage Service (Amazon S3) to store the output of the human loop.

1. (Optional) Use `Tags` to enter key-value pairs to help you categorize and organize a flow definition. Each tag consists of a key and a value, both of which you define.

------
#### [ Amazon Textract – Key-value pair extraction ]

The following is an example of a request to create an Amazon Textract human review workflow (flow definition) using the Amazon SDK for Python (Boto3). You must use `'AWS/Textract/AnalyzeDocument/Forms/V1'` to create a Amazon Textract human loop. Only include `PublicWorkforceTaskPrice` if you are using the Mechanical Turk workforce.

```
sagemaker_client = boto3.client('sagemaker', aws_region)

response = sagemaker_client.create_flow_definition(
    FlowDefinitionName='ExampleFlowDefinition',
    HumanLoopRequestSource={
         'AwsManagedHumanLoopRequestSource': 'AWS/Textract/AnalyzeDocument/Forms/V1'
    }, 
    HumanLoopActivationConfig={
        'HumanLoopActivationConditionsConfig': {
            'HumanLoopActivationConditions': '{...}'
        }
    },
    HumanLoopConfig={
        'WorkteamArn': 'arn:aws:sagemaker:aws_region:aws_account_number:workteam/private-crowd/workteam_name',
        'HumanTaskUiArn': 'arn:aws:sagemaker:aws_region:aws_account_number:human-task-ui/template_name',
        'TaskTitle': 'Example task title',
        'TaskDescription': 'Example task description.',
        'TaskCount': 123,
        'TaskAvailabilityLifetimeInSeconds': 123,
        'TaskTimeLimitInSeconds': 123,
        'TaskKeywords': [
            'Keyword1','Keyword2'
        ],
        'PublicWorkforceTaskPrice': {
            'AmountInUsd': {
                'Dollars': 123,
                'Cents': 123,
                'TenthFractionsOfACent': 123
            }
        }
    },
    OutputConfig={
        'S3OutputPath': 's3://bucket/path/',
        'KmsKeyId': '1234abcd-12ab-34cd-56ef-1234567890ab'
    },
    RoleArn='arn:aws:iam::aws_account_number:role/role_name',
    Tags=[
        {
            'Key': 'KeyName',
            'Value': 'ValueName'
        },
    ]
)
```

------
#### [ Amazon Rekognition – Image moderation ]

The following is an example of a request to create an Amazon Rekognition human review workflow (flow definition) using the Amazon SDK for Python (Boto3). You must use `'AWS/Rekognition/DetectModerationLabels/Image/V3'` to create an Amazon Rekognition flow definition. Only include `PublicWorkforceTaskPrice` if you are using the Mechanical Turk workforce.

```
sagemaker_client = boto3.client('sagemaker', aws_region)

response = sagemaker_client.create_flow_definition(
    FlowDefinitionName='ExampleFlowDefinition',
    HumanLoopRequestSource={
         'AwsManagedHumanLoopRequestSource': 'AWS/Rekognition/DetectModerationLabels/Image/V3'
    }, 
    HumanLoopActivationConfig={
        'HumanLoopActivationConditionsConfig': {
            'HumanLoopActivationConditions': '{...}'
        }
    },
    HumanLoopConfig={
        'WorkteamArn': 'arn:aws:sagemaker:aws_region:aws_account_number:workteam/private-crowd/workteam_name',
        'HumanTaskUiArn': 'arn:aws:sagemaker:aws_region:aws_account_number:human-task-ui/template_name',
        'TaskTitle': 'Example task title',
        'TaskDescription': 'Example task description.',
        'TaskCount': 123,
        'TaskAvailabilityLifetimeInSeconds': 123,
        'TaskTimeLimitInSeconds': 123,
        'TaskKeywords': [
            'Keyword1','Keyword2'
        ],
        'PublicWorkforceTaskPrice': {
            'AmountInUsd': {
                'Dollars': 123,
                'Cents': 123,
                'TenthFractionsOfACent': 123
            }
        }
    },
    OutputConfig={
        'S3OutputPath': 's3://bucket/path/',
        'KmsKeyId': '1234abcd-12ab-34cd-56ef-1234567890ab'
    },
    RoleArn='arn:aws:iam::aws_account_number:role/role_name',
    Tags=[
        {
            'Key': 'KeyName',
            'Value': 'ValueName'
        },
    ]
)
```

------
#### [ Custom Workflow ]

The following is an example of a request to create a human review workflow (flow definition) for a custom integration. To create this type of human review workflow, omit `HumanLoopRequestSource` from the flow definition request. You only need to include `PublicWorkforceTaskPrice` if you are using the Mechanical Turk workforce.

```
sagemaker_client = boto3.client('sagemaker', aws_region)

response = sagemaker_client.create_flow_definition(
    FlowDefinitionName='ExampleFlowDefinition',
    HumanLoopActivationConfig={
        'HumanLoopActivationConditionsConfig': {
            'HumanLoopActivationConditions': '{...}'
        }
    },
    HumanLoopConfig={
        'WorkteamArn': 'arn:aws:sagemaker:aws_region:aws_account_number:workteam/private-crowd/workteam_name',
        'HumanTaskUiArn': 'arn:aws:sagemaker:aws_region:aws_acount_number:human-task-ui/template_name',
        'TaskTitle': 'Example task title',
        'TaskDescription': 'Example task description.',
        'TaskCount': 123,
        'TaskAvailabilityLifetimeInSeconds': 123,
        'TaskTimeLimitInSeconds': 123,
        'TaskKeywords': [
            'Keyword1','Keyword2'
        ],
        'PublicWorkforceTaskPrice': {
            'AmountInUsd': {
                'Dollars': 123,
                'Cents': 123,
                'TenthFractionsOfACent': 123
            }
        }
    },
    OutputConfig={
        'S3OutputPath': 's3://bucket/path/',
        'KmsKeyId': '1234abcd-12ab-34cd-56ef-1234567890ab'
    },
    RoleArn='arn:aws:iam::account_number:role/role_name',
    Tags=[
        {
            'Key': 'KeyName',
            'Value': 'ValueName'
        },
    ]
)
```

------

### Next Steps


The return value of a successful call of the `CreateFlowDefinition` API operation is a flow definition Amazon Resource Name (ARN).

If you are using a built-in task type, you can use the flow definition ARN to start a human loop using that Amazon service's API (i.e. the Amazon Textract API). For custom task types, you can use the ARN to start a human loop using the Amazon Augmented AI Runtime API. To learn more about both of these options, see [Create and Start a Human Loop](a2i-start-human-loop.md).

# JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI


The `HumanLoopActivationConditions` is an input parameter of the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html) API. This parameter is a JSON-formatted string. The JSON models the conditions under which a human loop is created when those conditions are evaluated against the response from an integrating AI service API (such as `Rekognition.DetectModerationLabels` or `Textract.AnalyzeDocument`). This response is referred to as an *inference*. For example, Amazon Rekognition sends an inference of a moderation label with an associated confidence score. In this example, the inference is the model's best estimate of the appropriate label for an image. For Amazon Textract, inference is made on the association between blocks of text (*key-value pairs*), such as the association between `Name:` and `Sue` in a form as well as content within a block of text, or *word block*, such as 'Name'.

The following is the schema for the JSON. At the top level, the `HumanLoopActivationConditions` has a JSON array, `Conditions`. Each member of this array is an independent condition that, if evaluated to `true`, results in Amazon A2I creating a human loop. Each such independent condition can be a simple condition or a complex condition. A simple condition has the following attributes:
+ `ConditionType`: This attribute identifies the type of condition. Each Amazon AI service API that integrates with Amazon A2I defines its own set of allowed `ConditionTypes`. 
  + Rekognition `DetectModerationLabels` – This API supports the `ModerationLabelConfidenceCheck` and `Sampling` `ConditionType` values.
  + Textract `AnalyzeDocument` – This API supports the `ImportantFormKeyConfidenceCheck`, `MissingImportantFormKey`, and `Sampling` `ConditionType` values.
+ `ConditionParameters` – This is a JSON object that parameterizes the condition. The set of allowed attributes of this object is dependent on the value of the `ConditionType`. Each `ConditionType` defines its own set of `ConditionParameters`. 

A member of the `Conditions` array can model a complex condition. This is accomplished by logically connecting simple conditions using the `And` and `Or` logical operators and nesting the underlying simple conditions. Up to two levels of nesting are supported. 

```
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "definitions": {
        "Condition": {
            "type": "object",
            "properties": {
                "ConditionType": {
                    "type": "string"
                },
                "ConditionParameters": {
                    "type": "object"
                }
            },
            "required": [
                "ConditionType"
            ]
        },
        "OrConditionArray": {
            "type": "object",
            "properties": {
                "Or": {
                    "type": "array",
                    "minItems": 2,
                    "items": {
                        "$ref": "#/definitions/ComplexCondition"
                    }
                }
            }
        },
        "AndConditionArray": {
            "type": "object",
            "properties": {
                "And": {
                    "type": "array",
                    "minItems": 2,
                    "items": {
                        "$ref": "#/definitions/ComplexCondition"
                    }
                }
            }
        },
        "ComplexCondition": {
            "anyOf": [
                {
                    "$ref": "#/definitions/Condition"
                },
                {
                    "$ref": "#/definitions/OrConditionArray"
                },
                {
                    "$ref": "#/definitions/AndConditionArray"
                }
            ]
        }
    },
    "type": "object",
    "properties": {
        "Conditions": {
            "type": "array",
            "items": {
                "$ref": "#/definitions/ComplexCondition"
            }
        }
    }
}
```

**Note**  
Human loop activation conditions aren't available for human review workflows that are integrated with custom task types. The `HumanLoopActivationConditions` parameter is disabled for custom task types. 

**Topics**
+ [

# Use Human Loop Activation Conditions JSON Schema with Amazon Textract
](a2i-json-humantaskactivationconditions-textract-example.md)
+ [

# Use Human Loop Activation Conditions JSON Schema with Amazon Rekognition
](a2i-json-humantaskactivationconditions-rekognition-example.md)

# Use Human Loop Activation Conditions JSON Schema with Amazon Textract


When used with Amazon A2I, the `AnalyzeDocument` operation supports the following inputs in the `ConditionType` parameter:
+ `ImportantFormKeyConfidenceCheck` – Use this condition to create a human loop when inference confidence is within a specified range for document form keys and word blocks. A *form key* is any word in a document that is associated with an input. The input is called a *value*. Together, form keys and values are referred to as *key-value pairs*. A *word block* refers to the words that Amazon Textract recognizes inside of a detected block of text. To learn more about Amazon Textract document blocks, see [Documents and Block Objects](https://docs.amazonaws.cn/textract/latest/dg/how-it-works-document-layout.html) in the *Amazon Textract Developer Guide*.
+ `MissingImportantFormKey` – Use this condition to create a human loop when Amazon Textract did not identify the key or its associated aliases within the document. 
+ `Sampling` – Use this condition to specify a percentage of forms to send to humans for review, regardless of inference confidence scores. Use this condition to do the following:
  + Audit your ML model by randomly sampling all forms analyzed by your model and sending a specified percentage to humans for review.
  + Using the `ImportantFormKeyConfidenceCheck` condition, randomly sample a percentage of the inferences that met the conditions specified in `ImportantFormKeyConfidenceCheck` to start a human loop and send only the specified percentage to humans for review. 

**Note**  
If you send the same request to `AnalyzeDocument` multiple times, the result of `Sampling` does not change for the inference of that input. For example, if you make an `AnalyzeDocument` request once, and `Sampling` doesn't initiate a human loop, subsequent requests to `AnalyzeDocument` with the same configuration do not initiate a human loop.

## `ImportantFormKeyConfidenceCheck` Inputs and Results


The `ImportantFormKeyConfidenceCheck` `ConditionType` supports the following `ConditionParameters`:
+ `ImportantFormKey` – A string representing a key in a key-value pair detected by Amazon Textract that needs to be reviewed by human workers. If the value of this parameter is the special catch-all value (\$1), then all keys are considered to be matched to the condition. You can use this to model the case where any key-value pair satisfying certain confidence thresholds needs human review.
+ `ImportantFormKeyAliases` – An array that represents alternate spellings or logical equivalents for the important form key. 
+ `KeyValueBlockConfidenceEquals`
+ `KeyValueBlockConfidenceLessThan`
+ `KeyValueBlockConfidenceLessThanEquals`
+ `KeyValueBlockConfidenceGreaterThan`
+ `KeyValueBlockConfidenceGreaterThanEquals`
+ `WordBlockConfidenceEquals`
+ `WordBlockConfidenceLessThan`
+ `WordBlockConfidenceLessThanEquals`
+ `WordBlockConfidenceGreaterThan`
+ `WordBlockConfidenceGreaterThanEquals`

When you use the `ImportantFormKeyConfidenceCheck` `ConditionType`, Amazon A2I sends the key-value block and word block inferences of the key-value blocks and associated aliases that you specified in `ImportantFormKey` and `ImportantFormKeyAliases` for human review.

When creating a flow definition, if you use the default worker task template that is provided in the **Human review workflows** section of the Amazon SageMaker AI console, key-value and block inferences sent for human review by this activation condition are included in the worker UI. If you use a custom worker task template, you need to include the `{{ task.input.selectedAiServiceResponse.blocks }}` element to include initial-value input data (inferences) from Amazon Textract. For an example of a custom template that uses this input element, see [Custom Template Example for Amazon Textract](a2i-custom-templates.md#a2i-custom-templates-textract-sample).

## `MissingImportantFormKey` Inputs and Results


The `MissingImportantFormKey` `ConditionType` supports the following `ConditionParameters`:
+ `ImportantFormKey` – A string representing a key in a key-value pair detected by Amazon Textract that needs to be reviewed by human workers.
+ `ImportantFormKeyAliases` – An array that represents alternate spellings or logical equivalents for the important form key. 

When you use the `MissingImportantFormKey` `ConditionType`, if the key in `ImportantFormKey` or aliases in `ImportantFormKeyAliases` are not included in the Amazon Textract inference, that form is sent to human for review and no predicted key-value pairs are included. For example, if Amazon Textract only identified `Address` and `Phone` in a form, but was missing the `ImportantFormKey` `Name` (in the `MissingImportantFormKey` condition type) that form would be sent to humans for review without any of the form keys detected (`Address` and `Phone`).

If you use the default worker task template that is provided in the SageMaker AI console, a task is created asking workers to identify the key in `ImportantFormKey` and associated value. If you use a custom worker task template, you need to include the `<task.input.humanLoopContext>` custom HTML element to configure this task. 

## Sampling Inputs and Results


The `Sampling` `ConditionType` supports the `RandomSamplingPercentage` `ConditionParameters`. The input for `RandomSamplingPercentage` must be real number between 0.01 and 100. This number represents the percentage of data that qualifies for a human review and is sent to humans for review. If you use the `Sampling` condition without any other conditions, this number represents the percentage of all resulting inferences made by the `AnalyzeDocument` operation from a single request that is sent to humans for review.

If you specify the `Sampling` condition without any other condition type, all key-value and block inferences are sent to workers for review. 

When creating a flow definition, if you use the default worker task template that is provided in the **Human review workflows** section of the SageMaker AI console, all key-value and block inferences sent for human review by this activation condition are included in the worker UI. If you use a custom worker task template, you need to include the `{{ task.input.selectedAiServiceResponse.blocks }}` element to include initial-value input data (inferences) from Amazon Textract. For an example of a custom template that uses this input element, see [Custom Template Example for Amazon Textract](a2i-custom-templates.md#a2i-custom-templates-textract-sample).

## Examples


While only one condition needs to evaluate to `true` to initiate a human loop, Amazon A2I evaluates all conditions for each object analyzed by Amazon Textract. The human reviewers are asked to review the important form keys for all the conditions that evaluated to `true`.

**Example 1: Detect important form keys with confidence scores in a specified range that initiate a human loop**

The following example shows a `HumanLoopActivationConditions` JSON that initiates a human loop if any one of the following three conditions is met:
+ The Amazon Textract `AnalyzeDocument` API returns a key-value pair whose key is one of `Employee Name`, `Name`, or `EmployeeName`, with the confidence of the key-value block being less than 60 and the confidences of each of the word blocks making up the key and value being less than 85.
+ The Amazon Textract `AnalyzeDocument` API returns a key-value pair whose key is one of `Pay Date`, `PayDate`, `DateOfPay`, or `pay-date`, with the confidence of the key-value block being less than 65 and the confidences of each of the word blocks making up the key and value being less than 85.
+ The Amazon Textract `AnalyzeDocument` API returns a key-value pair whose key is one of `Gross Pay`, `GrossPay`, or `GrossAmount`, with the confidence of the key-value block being less than 60 and the confidences of each of the word blocks making up the key and value being less than 85.

```
{
    "Conditions": [
        {
            "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "Employee Name",
                "ImportantFormKeyAliases": [
                    "Name",
                    "EmployeeName"
                ],
                "KeyValueBlockConfidenceLessThan": 60,
                "WordBlockConfidenceLessThan": 85
            }
        },
        {
            "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "Pay Date",
                "ImportantFormKeyAliases": [
                    "PayDate",
                    "DateOfPay",
                    "pay-date"
                ],
                "KeyValueBlockConfidenceLessThan": 65,
                "WordBlockConfidenceLessThan": 85
            }
        },
        {
            "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "Gross Pay",
                "ImportantFormKeyAliases": [
                    "GrossPay",
                    "GrossAmount"
                ],
                "KeyValueBlockConfidenceLessThan": 60,
                "WordBlockConfidenceLessThan": 85
            }
        }
    ]
}
```

**Example 2: Use `ImportantFormKeyConfidenceCheck`**

In the following example, if Amazon Textract detects a key-value pair whose confidence for the key-value block is less than 60 and is less than 90 for any underlying word blocks, it creates a human loop. The human reviewers are asked to review all the form key-value pairs that matched the confidence value comparisons.

```
{
    "Conditions": [
        {
            "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "*",
                "KeyValueBlockConfidenceLessThan": 60,
                "WordBlockConfidenceLessThan": 90
            }
        }
    ]
}
```

**Example 3: Use Sampling**

In the following example, 5% of inferences resulting from an Amazon Textract `AnalyzeDocument` request are sent to human workers for review. All detected key-value pairs returned by Amazon Textract are sent to workers for review.

```
{
  "Conditions": [
    {
      "ConditionType": "Sampling",
      "ConditionParameters": {
        "RandomSamplingPercentage": 5
      }
    }
  ]
}
```

**Example 4: Use `MissingImportantFormKey`**

In the following example, if `Mailing Address` or its alias, `Mailing Address:`, is missing from keys detected by Amazon Textract, a human review is initiated. When using the default worker task template, the worker UI asks workers to identify the key `Mailing Address` or `Mailing Address:` and its associated value. 

```
{
    "ConditionType": "MissingImportantFormKey",
    "ConditionParameters": {
        "ImportantFormKey": "Mailing Address",
        "ImportantFormKeyAliases": ["Mailing Address:"]
    }
}
```

**Example 5: Use Sampling and `ImportantFormKeyConfidenceCheck` with the `And` operator**

In this example, 5% of key-value pairs detected by Amazon Textract whose key is one of `Pay Date`, `PayDate`, `DateOfPay`, or `pay-date`, with the confidence of the key-value block less than 65 and the confidences of each of the word blocks making up the key and value less than 85, are sent to workers for review.

```
{
  "Conditions": [
    {
      "And": [
        {
          "ConditionType": "Sampling",
          "ConditionParameters": {
            "RandomSamplingPercentage": 5
          }
        },
        {
          "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "Pay Date",
                "ImportantFormKeyAliases": [
                    "PayDate",
                    "DateOfPay",
                    "pay-date"
                ],
                "KeyValueBlockConfidenceLessThan": 65,
                "WordBlockConfidenceLessThan": 85
            }
        }
      ]
    }
  ]
}
```

**Example 6: Use Sampling and `ImportantFormKeyConfidenceCheck` with the `And` operator**

Use this example to configure your human review workflow to always send low confidence inferences of a specified key-value pair for human review and sample high confidence inference of a key-value pair at a specified rate. 

In the following example, a human review is initiated in one of the following ways: 
+ Key-value pairs detected whose key is one of `Pay Date`, `PayDate`, `DateOfPay`, or `pay-date`, with key-value and word block confidences less than 60, are sent for human review. Only the `Pay Date` form key (and its aliases) and associated values are sent to workers to review. 
+ 5% of key-value pairs detected whose key is one of `Pay Date`, `PayDate`, `DateOfPay`, or `pay-date`, with key-value and word block confidences greater than 90, are sent for human review. Only the `Pay Date` form key (and its aliases) and associated values are sent to workers to review. 

```
{
  "Conditions": [
    {
      "Or": [
       {
          "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "Pay Date",
                "ImportantFormKeyAliases": [
                    "PayDate",
                    "DateOfPay",
                    "pay-date"
                ],
                "KeyValueBlockConfidenceLessThan": 60,
                "WordBlockConfidenceLessThan": 60
            }
        },
        {
            "And": [
                {
                    "ConditionType": "Sampling",
                    "ConditionParameters": {
                        "RandomSamplingPercentage": 5
                    }
                },
                {
                    "ConditionType": "ImportantFormKeyConfidenceCheck",
                        "ConditionParameters": {
                            "ImportantFormKey": "Pay Date",
                            "ImportantFormKeyAliases": [
                                "PayDate",
                                "DateOfPay",
                                "pay-date"
                        ],
                        "KeyValueBlockConfidenceLessThan": 90
                        "WordBlockConfidenceGreaterThan": 90
                    }
                }
            ]
        }
      ]
    }
  ]
}
```

**Example 7: Use Sampling and `ImportantFormKeyConfidenceCheck` with the `Or` operator**

In the following example, the Amazon Textract `AnalyzeDocument` operation returns a key-value pair whose key is one of `Pay Date`, `PayDate`, `DateOfPay`, or `pay-date`, with the confidence of the key-value block less than 65 and the confidences of each of the word blocks making up the key and value less than 85. Additionally, 5% of all other forms initiate a human loop. For each form randomly chosen, all key-value pairs detected for that form are sent to humans for review.

```
{
  "Conditions": [
    {
      "Or": [
        {
          "ConditionType": "Sampling",
          "ConditionParameters": {
            "RandomSamplingPercentage": 5
          }
        },
        {
           "ConditionType": "ImportantFormKeyConfidenceCheck",
            "ConditionParameters": {
                "ImportantFormKey": "Pay Date",
                "ImportantFormKeyAliases": [
                    "PayDate",
                    "DateOfPay",
                    "pay-date"
                ],
                "KeyValueBlockConfidenceLessThan": 65,
                "WordBlockConfidenceLessThan": 85
            }
          }
        }
      ]
    }
  ]
}
```

# Use Human Loop Activation Conditions JSON Schema with Amazon Rekognition


When used with Amazon A2I, the Amazon Rekognition `DetectModerationLabels` operation supports the following inputs in the `ConditionType` parameters:
+ `ModerationLabelConfidenceCheck` – Use this condition type to create a human loop when inference confidence is low for one or more specified labels.
+ `Sampling` – Use this condition to specify a percentage of all inferences to send to humans for review. Use this condition to do the following:
  + Audit your ML model by randomly sampling all of your model's inferences and sending a specified percentage to humans for review.
  + Using the `ModerationLabelConfidenceCheck` condition, randomly sample a percentage of the inferences that met the conditions specified in `ModerationLabelConfidenceCheck` to start a human loop and send only the specified percentage to humans for review. 

**Note**  
If you send the same request to `DetectModerationLabels` multiple times, the result of `Sampling` does not change for the inference of that input. For example, if you make a `DetectModerationLabels` request once, and `Sampling` does not initiate a human loop, subsequent requests to `DetectModerationLabels` with the same configuration don't initiate a human loop. 

When creating a flow definition, if you use the default worker task template that is provided in the **Human review workflows** section of the Amazon SageMaker AI console, inferences sent for human review by these activation conditions are included in the worker UI when a worker opens your task. If you use a custom worker task template, you need to include the `<task.input.selectedAiServiceResponse.blocks>` custom HTML element to access these inferences. For an example of a custom template that uses this HTML element, see [Custom Template Example for Amazon Rekognition](a2i-custom-templates.md#a2i-custom-templates-rekognition-sample).

## `ModerationLabelConfidenceCheck` Inputs


For the `ModerationLabelConfidenceCheck` `ConditionType`, the following `ConditionParameters` are supported:
+ `ModerationLabelName` – The exact (case-sensitive) name of a [ModerationLabel](https://docs.amazonaws.cn/rekognition/latest/dg/API_ModerationLabel.html) detected by the Amazon Rekognition `DetectModerationLabels` operation. You can specify the special catch-all value (\$1) to denote any moderation label.
+ `ConfidenceEquals`
+ `ConfidenceLessThan`
+ `ConfidenceLessThanEquals`
+ `ConfidenceGreaterThan`
+ `ConfidenceGreaterThanEquals`

When you use the `ModerationLabelConfidenceCheck` `ConditionType`, Amazon A2I sends label inferences for the labels that you specified in `ModerationLabelName` for human review.

## Sampling Inputs


The `Sampling` `ConditionType` supports the `RandomSamplingPercentage` `ConditionParameters`. The input for the `RandomSamplingPercentage` prameter should be real number between 0.01 and 100. This number represents the percentage of inferences that qualifies for a human review that are sent to humans for review. If you use the `Sampling` condition without any other conditions, this number represents the percentage of all inferences that result from a single `DetectModerationLabel` request that are sent to humans for review.

## Examples


**Example 1: Use `ModerationLabelConfidenceCheck` with the `And` operator**

The following example of a `HumanLoopActivationConditions` condition initiates a human loop when one or more of the following conditions are met:
+ Amazon Rekognition detects the `Graphic Male Nudity` moderation label with a confidence between 90 and 99.
+ Amazon Rekognition detects the `Graphic Female Nudity` moderation label with a confidence between 80 and 99.

Note the use of the `Or` and `And` logical operators to model this logic.

Although only one of the two conditions under the `Or` operator needs to evaluate to `true` for a human loop to be created, Amazon Augmented AI evaluates all conditions. Human reviewers are asked to review the moderation labels for all the conditions that evaluated to `true`.

```
{
     "Conditions": [{
         "Or": [{
                 "And": [{
                         "ConditionType": "ModerationLabelConfidenceCheck",
                         "ConditionParameters": {
                             "ModerationLabelName": "Graphic Male Nudity",
                             "ConfidenceLessThanEquals": 99
                         }
                     },
                     {
                         "ConditionType": "ModerationLabelConfidenceCheck",
                         "ConditionParameters": {
                             "ModerationLabelName": "Graphic Male Nudity",
                             "ConfidenceGreaterThanEquals": 90
                         }
                     }
                 ]
             },
             {
                 "And": [{
                         "ConditionType": "ModerationLabelConfidenceCheck",
                         "ConditionParameters": {
                             "ModerationLabelName": "Graphic Female Nudity",
                             "ConfidenceLessThanEquals": 99
                         }
                     },
                     {
                         "ConditionType": "ModerationLabelConfidenceCheck",
                         "ConditionParameters": {
                             "ModerationLabelName": "Graphic Female Nudity",
                             "ConfidenceGreaterThanEquals": 80
                         }
                     }
                 ]
             }
         ]
     }]
}
```

**Example 2: Use `ModerationLabelConfidenceCheck` with the catch-all value (\$1) **

In the following example, if any moderation label with a confidence greater than or equal to 75 is detected, a human loop is initiated. Human reviewers are asked to review all moderation labels with confidence scores greater than or equal to 75.

```
{
    "Conditions": [
        {
            "ConditionType": "ModerationLabelConfidenceCheck",
            "ConditionParameters": {
                "ModerationLabelName": "*",
                "ConfidenceGreaterThanEquals": 75
            }
        }
    ]
}
```

**Example 3: Use Sampling**

In the following example, 5% of Amazon Rekognition inferences from a `DetectModerationLabels` request are sent to human workers. When using the default worker task template provided in the SageMaker AI console, all moderation labels returned by Amazon Rekognition are sent to workers for review.

```
{
  "Conditions": [
    {
      "ConditionType": "Sampling",
      "ConditionParameters": {
        "RandomSamplingPercentage": 5
      }
    }
  ]
}
```

**Example 4: Use Sampling and `ModerationLabelConfidenceCheck` with the `And` operator**

In this example, 5% of Amazon Rekognition inferences of the `Graphic Male Nudity` moderation label with a confidence greater than 50 are sent workers for review. When using the default worker task template provided in the SageMaker AI console, only the inferences of the `Graphic Male Nudity` label are sent to workers for review. 

```
{
  "Conditions": [
    {
      "And": [
        {
          "ConditionType": "Sampling",
          "ConditionParameters": {
            "RandomSamplingPercentage": 5
          }
        },
        {
          "ConditionType": "ModerationLabelConfidenceCheck",
          "ConditionParameters": {
            "ModerationLabelName": "Graphic Male Nudity",
            "ConfidenceGreaterThan": 50
          }
        }
      ]
    }
  ]
}
```

**Example 5: Use Sampling and `ModerationLabelConfidenceCheck` with the `And` operator**

Use this example to configure your human review workflow to always send low-confidence inferences of a specified label for human review and sample high-confidence inferences of a label at a specified rate. 

In the following example, a human review is initiated in one of the following ways: 
+ Inferences for the `Graphic Male Nudity` moderation label the with confidence scores less than 60 are always sent for human review. Only the `Graphic Male Nudity` label is sent to workers to review. 
+ 5% of all inferences for the `Graphic Male Nudity` moderation label the with confidence scores greater than 90 are sent for human review. Only the `Graphic Male Nudity` label is sent to workers to review. 

```
{
  "Conditions": [
    {
      "Or": [
        {
          "ConditionType": "ModerationLabelConfidenceCheck",
          "ConditionParameters": {
            "ModerationLabelName": "Graphic Male Nudity",
            "ConfidenceLessThan": 60
          }
        },
        {
            "And": [
                {
                    "ConditionType": "Sampling",
                    "ConditionParameters": {
                        "RandomSamplingPercentage": 5
                    }
                },
                {
                    "ConditionType": "ModerationLabelConfidenceCheck",
                    "ConditionParameters": {
                        "ModerationLabelName": "Graphic Male Nudity",
                        "ConfidenceGreaterThan": 90
                    }
                }
            ]
        }
      ]
    }
  ]
}
```

**Example 6: Use Sampling and `ModerationLabelConfidenceCheck` with the `Or` operator**

In the following example, a human loop is created if the Amazon Rekognition inference response contains the 'Graphic Male Nudity' label with inference confidence greater than 50. Additionally, 5% of all other inferences initiate a human loop. 

```
{
  "Conditions": [
    {
      "Or": [
        {
          "ConditionType": "Sampling",
          "ConditionParameters": {
            "RandomSamplingPercentage": 5
          }
        },
        {
          "ConditionType": "ModerationLabelConfidenceCheck",
          "ConditionParameters": {
            "ModerationLabelName": "Graphic Male Nudity",
            "ConfidenceGreaterThan": 50
          }
        }
      ]
    }
  ]
}
```

# Delete a Human Review Workflow


When you delete a human review workflow or you delete your Amazon account while a human loop is in process, your human review workflow status changes to `Deleting`. Amazon A2I automatically stops and deletes all associated human loops if workers have not started tasks created by those human loops. If human workers are already working on a task, that task continues to be available until it is completed or expires. As long as workers are still working on a task, your human review workflow's status is `Deleting`. If these tasks are completed, the results are stored in the Amazon S3 bucket specified in your flow definition. 

Deleting a flow definition does not remove any worker answers from your S3 bucket. If the tasks are completed, but you deleted your Amazon account, the results are stored in the Augmented AI service bucket for 30 days and then permanently deleted.

After all human loops have been deleted, the human review workflow is permanently deleted. When a human review workflow has been deleted, you can reuse its name to create a new human review workflow. 

You might want to delete a human review workflow for any of the following reasons:
+ You have sent data to a set of human reviewers and you want to delete all non-started human loops because you do not want those workers to work on those tasks any longer.
+ The worker task template used to generate your worker UI does not render correctly or is not functioning as expected. 

After you delete a human review workflow, the following changes occur:
+ The human review workflow no longer appears on the **Human review workflows** page in the Augmented AI area of the Amazon SageMaker AI console. 
+ When you use the human review workflow name as input to the API operations [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DescribeFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DescribeFlowDefinition.html) or [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteFlowDefinition.html), Augmented AI returns a `ResourceNotFound` error. 
+ When you use [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_ListFlowDefinitions.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_ListFlowDefinitions.html), deleted human review workflows aren't included in the results. 
+ When you use the human review workflow ARN as input to the Augmented AI Runtime API operation `[ListHumanLoops](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_ListHumanLoops.html)`, Augmented AI returns a `ResourceNotFoundException`.

## Delete a Flow Definition Using the Console or the SageMaker API


You can delete a human review workflow on the **Human review workflows** page in the Augmented AI area of the SageMaker AI console or by using the SageMaker AI API. 

Flow definitions can only be deleted if their status is `Active`. 

**Delete a human review workflow (console)**

1. Navigate to the Augmented AI console at [https://console.amazonaws.cn/a2i/](https://console.amazonaws.cn/a2i).

1. In the navigation pane, under the **Augmented AI** section, choose **Human review workflows**.

1. Select the hyperlinked name of the human review workflow that you want to delete. 

1. On the **Summary** page of your human review workflow, choose **Delete**. 

1. In the dialog box asking you to confirm that you want to delete your human review workflow, choose **Delete**. 

You're automatically redirected to the **Human review workflows** page. While your human review workflow is being deleted, the status **Deleting** appears in the status column for that workflow. After it's deleted, it doesn't appear in the list of workflows on this page. 

**Delete a human review workflow (API)**  
You can delete a human review workflow (flow definition) using the SageMaker AI [DeleteFlowDefinition](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteFlowDefinition.html) API operation. This API operation is supported through the [Amazon CLI](https://docs.amazonaws.cn/cli/latest/reference/sagemaker/delete-flow-definition.html) and a [variety of language specific SDKs](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteFlowDefinition.html#API_DeleteFlowDefinition_SeeAlso). The following table shows example requests using SDK for Python (Boto3) and the Amazon CLI to delete the human review workflow, *`example-flow-definition`*. 

------
#### [ Amazon SDK for Python (Boto3) ]

The following request example uses the SDK for Python (Boto3) to delete the human review workflow. For more information, see [delete\$1flow\$1definition](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.delete_flow_definition) in the *Amazon SDK for Python (Boto) API Reference*.

```
import boto3

sagemaker_client = boto3.client('sagemaker')
response = sagemaker_client.delete_flow_definition(FlowDefinitionName='example-flow-definition')
```

------
#### [ Amazon CLI ]

The following request example uses the Amazon CLI to delete the human review workflow. For more information, see [delete-flow-definition](https://docs.amazonaws.cn/cli/latest/reference/sagemaker/delete-flow-definition.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*. 

```
$ aws sagemaker delete-flow-definition --flow-definition-name 'example-flow-definition'
```

------

If the action is successful, Augmented AI sends back an HTTP 200 response with an empty HTTP body.

# Create and Start a Human Loop


A *human loop* starts your human review workflow and sends data review tasks to human workers. When you use one of the Amazon A2I built-in task types, the corresponding Amazon service creates and starts a human loop on your behalf when the conditions specified in your flow definition are met. If no conditions are specified in your flow definition, a human loop is created for each object. When using Amazon A2I for a custom task, a human loop starts when your application calls `StartHumanLoop`. 

Use the following instructions to configure a human loop with Amazon Rekognition or Amazon Textract built-in task types and custom task types. 

**Prerequisites**

To create and start a human loop, you must attach the `AmazonAugmentedAIFullAccess` policy to the Amazon Identity and Access Management (IAM) user or role that configures or starts the human loop. This is the identity that you use to configure the human loop using `HumanLoopConfig` for built-in task types. For custom task types, this is the identity that you use to call `StartHumanLoop`.

Additionally, when using a built-in task type, your user or role must have permission to invoke API operations of the Amazon service associated with your task type. For example, if you are using Amazon Rekognition with Augmented AI, you must attach permissions required to call `DetectModerationLabels`. For examples of identity-based policies you can use to grant these permissions, see [Amazon Rekognition Identity-Based Policy Examples](https://docs.amazonaws.cn/rekognition/latest/dg/security_iam_id-based-policy-examples.html) and [Amazon Textract Identity-Based Policy Examples](https://docs.amazonaws.cn/textract/latest/dg/security_iam_id-based-policy-examples.html). You can also use the more general policy `AmazonAugmentedAIIntegratedAPIAccess` to grant these permissions. For more information, see [Create a User With Permissions to Invoke Amazon A2I, Amazon Textract, and Amazon Rekognition API Operations](a2i-permissions-security.md#a2i-grant-general-permission). 

To create and start a human loop, you need a flow definition ARN. To learn how to create a flow definition (or human review workflow), see [Create a Human Review Workflow](a2i-create-flow-definition.md).

**Important**  
Amazon A2I requires all S3 buckets that contain human loop input image data to have a CORS policy attached. To learn more about this change, see [CORS Permission Requirement](a2i-permissions-security.md#a2i-cors-update).

## Create and Start a Human Loop for a Built-in Task Type


To start a human loop using a built-in task type, use the corresponding service's API to provide your input data and to configure the human loop. For Amazon Textract, you use the `AnalyzeDocument` API operation. For Amazon Rekognition, you use the `DetectModerationLabels` API operation. You can use the Amazon CLI or a language-specific SDK to create requests using these API operations. 

**Important**  
When you create a human loop using a built-in task type, you can use `DataAttributes` to specify a set of `ContentClassifiers` related to the input provided to the `StartHumanLoop` operation. Use content classifiers to declare that your content is free of personally identifiable information or adult content.  
To use Amazon Mechanical Turk, ensure your data is free of personally identifiable information, including protected health information under HIPAA. Include the `FreeOfPersonallyIdentifiableInformation` content classifier. If you do not use this content classifier, SageMaker AI does not send your task to Mechanical Turk. If your data is free of adult content, also include the `'FreeOfAdultContent'` classifier. If you do not use these content classifiers, SageMaker AI may restrict the Mechanical Turk workers that can view your task.

After you start your ML job using your built-in task type's Amazon service API, Amazon A2I monitors the inference results of that service. For example, when running a job with Amazon Rekognition, Amazon A2I checks the inference confidence score for each image and compares it to the confidence thresholds specified in your flow definition. If the conditions to start a human review task are satisfied, or if you didn't specify conditions in your flow definition, a human review task is sent to workers. 

### Create an Amazon Textract Human Loop


Amazon A2I integrates with Amazon Textract so that you can configure and start a human loop using the Amazon Textract API. To send a document file to Amazon Textract for document analysis, you use the Amazon Textract [`AnalyzeDocument` API operation](https://docs.amazonaws.cn/textract/latest/dg/API_AnalyzeDocument.html). To add a human loop to this document analysis job, you must configure the parameter `HumanLoopConfig`. 

When you configure your human loop, the flow definition you specify in `FlowDefinitionArn` of `HumanLoopConfig` must be located in the same Amazon Region as the bucket identified in `Bucket` of the `Document`parameter.

The following table shows examples of how to use this operation with the Amazon CLI and Amazon SDK for Python (Boto3).

------
#### [ Amazon SDK for Python (Boto3) ]

The following request example uses the SDK for Python (Boto3). For more information, see [analyze\$1document](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/textract.html#Textract.Client.analyze_document) in the *Amazon SDK for Python (Boto) API Reference*. 

```
import boto3

textract = boto3.client('textract', aws_region)

response = textract.analyze_document(
            Document={'S3Object': {'Bucket': bucket_name, 'Name': document_name}},
            FeatureTypes=["TABLES", "FORMS"],
            HumanLoopConfig={
                'FlowDefinitionArn': 'arn:aws:sagemaker:aws_region:aws_account_number:flow-definition/flow_def_name',
                'HumanLoopName': 'human_loop_name',
                'DataAttributes': {'ContentClassifiers': ['FreeOfPersonallyIdentifiableInformation','FreeOfAdultContent']}
            }
          )
```

------
#### [ Amazon CLI ]

The following request example uses the Amazon CLI. For more information, see [analyze-document](https://docs.amazonaws.cn/cli/latest/reference/textract/analyze-document.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*.

```
$ aws textract analyze-document \
     --document '{"S3Object":{"Bucket":"bucket_name","Name":"document_name"}}' \
     --human-loop-config HumanLoopName="human_loop_name",FlowDefinitionArn="arn:aws:sagemaker:aws-region:aws_account_number:flow-definition/flow_def_name",DataAttributes='{ContentClassifiers=["FreeOfPersonallyIdentifiableInformation", "FreeOfAdultContent"]}' \
     --feature-types '["TABLES", "FORMS"]'
```

```
$ aws textract analyze-document \
     --document '{"S3Object":{"Bucket":"bucket_name","Name":"document_name"}}' \
     --human-loop-config \
          '{"HumanLoopName":"human_loop_name","FlowDefinitionArn":"arn:aws:sagemaker:aws_region:aws_account_number:flow-definition/flow_def_name","DataAttributes": {"ContentClassifiers":["FreeOfPersonallyIdentifiableInformation","FreeOfAdultContent"]}}' \
     --feature-types '["TABLES", "FORMS"]'
```

------

After you run `AnalyzeDocument` with a human loop configured, Amazon A2I monitors the results from `AnalyzeDocument` and checks it against the flow definition's activation conditions. If the Amazon Textract inference confidence score for one or more key-value pairs meets the conditions for review, Amazon A2I starts a human review loop and includes the [https://docs.amazonaws.cn/textract/latest/dg/API_HumanLoopActivationOutput.html](https://docs.amazonaws.cn/textract/latest/dg/API_HumanLoopActivationOutput.html) object in the `AnalyzeDocument` response.

### Create an Amazon Rekognition Human Loop


Amazon A2I integrates with Amazon Rekognition so that you can configure and start a human loop using the Amazon Rekognition API. To send images to Amazon Rekognition for content moderation, you use the Amazon Rekognition [`DetectModerationLabels` API operation](https://docs.amazonaws.cn/rekognition/latest/dg/API_DetectModerationLabels.html). To configure a human loop, set the `HumanLoopConfig` parameter when you configure `DetectModerationLabels`.

When you configure your human loop, the flow definition you specify in `FlowDefinitionArn` of `HumanLoopConfig` must be located in the same Amazon Region as the S3 bucket identified in `Bucket` of the `Image` parameter.

The following table shows examples of how to use this operation with the Amazon CLI and Amazon SDK for Python (Boto3).

------
#### [ Amazon SDK for Python (Boto3) ]

The following request example uses the SDK for Python (Boto3). For more information, see [detect\$1moderation\$1labels](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.detect_moderation_labels) in the *Amazon SDK for Python (Boto) API Reference*.

```
import boto3

rekognition = boto3.client("rekognition", aws_region)

response = rekognition.detect_moderation_labels( \
        Image={'S3Object': {'Bucket': bucket_name, 'Name': image_name}}, \
        HumanLoopConfig={ \
            'HumanLoopName': 'human_loop_name', \
            'FlowDefinitionArn': , "arn:aws:sagemaker:aws_region:aws_account_number:flow-definition/flow_def_name" \
            'DataAttributes': {'ContentClassifiers': ['FreeOfPersonallyIdentifiableInformation','FreeOfAdultContent']}
         })
```

------
#### [ Amazon CLI ]

The following request example uses the Amazon CLI. For more information, see [detect-moderation-labels](https://docs.amazonaws.cn/cli/latest/reference/rekognition/detect-moderation-labels.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*.

```
$ aws rekognition detect-moderation-labels \
    --image "S3Object={Bucket='bucket_name',Name='image_name'}" \
    --human-loop-config HumanLoopName="human_loop_name",FlowDefinitionArn="arn:aws:sagemaker:aws_region:aws_account_number:flow-definition/flow_def_name",DataAttributes='{ContentClassifiers=["FreeOfPersonallyIdentifiableInformation", "FreeOfAdultContent"]}'
```

```
$ aws rekognition detect-moderation-labels \
    --image "S3Object={Bucket='bucket_name',Name='image_name'}" \
    --human-loop-config \
        '{"HumanLoopName": "human_loop_name", "FlowDefinitionArn": "arn:aws:sagemaker:aws_region:aws_account_number:flow-definition/flow_def_name", "DataAttributes": {"ContentClassifiers": ["FreeOfPersonallyIdentifiableInformation", "FreeOfAdultContent"]}}'
```

------

After you run `DetectModerationLabels` with a human loop configured, Amazon A2I monitors the results from `DetectModerationLabels` and checks it against the flow definition's activation conditions. If the Amazon Rekognition inference confidence score for an image meets the conditions for review, Amazon A2I starts a human review loop and includes the response element `HumanLoopActivationOutput` in the `DetectModerationLabels` response.

## Create and Start a Human Loop for a Custom Task Type


To configure a human loop for a custom human review task, use the `StartHumanLoop` operation within your application. This section provides an example of a human loop request using the Amazon SDK for Python (Boto3) and the Amazon Command Line Interface (Amazon CLI). For documentation on other language-specific SDKs that support `StartHumanLoop`, use the **See Also** section of [StartHumanLoop](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_StartHumanLoop.html) in the Amazon Augmented AI Runtime API documentation. Refer to [Use Cases and Examples Using Amazon A2I](a2i-task-types-general.md) to see examples that demonstrate how to use Amazon A2I with a custom task type.

**Prerequisites**

To complete this procedure, you need:
+ Input data formatted as a string representation of a JSON-formatted file
+ The Amazon Resource Name (ARN) of your flow definition

**To configure the human loop**

1. For `DataAttributes`, specify a set of `ContentClassifiers` related to the input provided to the `StartHumanLoop` operation. Use content classifiers to declare that your content is free of personally identifiable information or adult content. 

   To use Amazon Mechanical Turk, ensure your data is free of personally identifiable information, including protected health information under HIPAA, and include the `FreeOfPersonallyIdentifiableInformation` content classifier. If you do not use this content classifier, SageMaker AI does not send your task to Mechanical Turk. If your data is free of adult content, also include the `'FreeOfAdultContent'` classifier. If you do not use these content classifiers, SageMaker AI may restrict the Mechanical Turk workers that can view your task.

1. For `FlowDefinitionArn`, enter the Amazon Resource Name (ARN) of your flow definition.

1. For `HumanLoopInput`, enter your input data as a string representation of a JSON-formatted file. Structure your input data and custom worker task template so that your input data is properly displayed to human workers when you start your human loop. See [Preview a Worker Task Template](a2i-custom-templates.md#a2i-preview-your-custom-template) to learn how to preview your custom worker task template. 

1. For `HumanLoopName`, enter a name for the human loop. The name must be unique within the Region in your account and can have up to 63 characters. Valid characters are a-z, 0-9, and - (hyphen).

**To start a human loop**
+ To start a human loop, submit a request similar to the following examples using your preferred language-specific SDK. 

------
#### [ Amazon SDK for Python (Boto3) ]

The following request example uses the SDK for Python (Boto3). For more information, see [Boto 3 Augmented AI Runtime](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-a2i-runtime.html#AugmentedAIRuntime.Client.start_human_loop) in the *Amazon SDK for Python (Boto) API Reference*.

```
import boto3

a2i_runtime_client = boto3.client('sagemaker-a2i-runtime')

response = a2i_runtime_client.start_human_loop(
    HumanLoopName='human_loop_name',
    FlowDefinitionArn='arn:aws:sagemaker:aws-region:xyz:flow-definition/flow_def_name',
    HumanLoopInput={
        'InputContent': '{"InputContent": {\"prompt\":\"What is the answer?\"}}'    
    },
    DataAttributes={
        'ContentClassifiers': [
            'FreeOfPersonallyIdentifiableInformation'|'FreeOfAdultContent',
        ]
    }
)
```

------
#### [ Amazon CLI ]

The following request example uses the Amazon CLI. For more information, see [start-human-loop](https://docs.amazonaws.cn/cli/latest/reference/sagemaker-a2i-runtime/start-human-loop.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*. 

```
$ aws sagemaker-a2i-runtime start-human-loop
        --flow-definition-arn 'arn:aws:sagemaker:aws_region:xyz:flow-definition/flow_def_name' \
        --human-loop-name 'human_loop_name' \
        --human-loop-input '{"InputContent": "{\"prompt\":\"What is the answer?\"}"}' \
        --data-attributes ContentClassifiers="FreeOfPersonallyIdentifiableInformation","FreeOfAdultContent" \
```

------

When you successfully start a human loop by invoking `StartHumanLoop` directly, the response includes a `HumanLoopARN` and a `HumanLoopActivationResults` object which is set to `NULL`. You can use this the human loop name to monitor and manage your human loop.

## Next Steps:


After starting a human loop, you can manage and monitor it with the Amazon Augmented AI Runtime API and Amazon CloudWatch Events. To learn more, see [Monitor and Manage Your Human Loop](a2i-monitor-humanloop-results.md).

# Delete a Human Loop


When you delete a human loop, the status changes to `Deleting`. When the human loop is deleted, the associated human review task is no longer available to workers. You might want to delete a human loop in one of the following circumstances:
+ The worker task template used to generate your worker user interface does not render correctly or is not functioning as expected. 
+ A single data object was accidentally sent to workers multiple times. 
+ You no longer need a data object reviewed by a human. 

If the status of a human loop is `InProgress`, you must stop the human loop before deleting it. When you stop a human loop, the status changes to `Stopping` while it is being stopped. When the status changes to `Stopped`, you can delete the human loop. 

If human workers are already working on a task when you stop the associated human loop, that task continues to be available until it is completed or expires. As long as workers are still working on a task, your human loop's status is `Stopping`. If these tasks are completed, the results are stored in the Amazon S3 bucket URI specified in your human review workflow. If the worker leaves the task without submitting work, it is stopped and the worker can't return to the task. If no worker has started working on the task, it is stopped immediately. 

If you delete the Amazon account used to create the human loop, it is stopped and deleted automatically. 

## Human Loop Data Retention and Deletion


When a human worker completes a human review task, the results are stored in the Amazon S3 output bucket you specified in the human review workflow used to create the human loop. Deleting or stopping a human loop does not remove any worker answers from your S3 bucket. 

Additionally, Amazon A2I temporarily stores human loop input and output data internally for the following reasons:
+ If you configure your human loops so that a single data object is sent to multiple workers for review, Amazon A2I does not write output data to your S3 bucket until all workers have completed the review task. Amazon A2I stores partial answers—answers from individual workers—internally so that it can write full results to your S3 bucket. 
+ If you report a low-quality human review result, Amazon A2I can investigate and respond to your issue. 
+ If you lose access to or delete the output S3 bucket specified in the human review workflow used to create a human loop, and the task has already been sent to one or more workers, Amazon A2I needs a place to temporarily store human review results. 

Amazon A2I deletes this data internally 30 days after a human loop's status changes to one of the following: `Deleted`, `Stopped`, or `Completed`. In other words, data is deleted 30 days after the human loop has been completed, stopped, or deleted. Additionally, this data is deleted after 30 days if you close the Amazon account used to create associated human loops.

## Stop and Delete a Flow Definition Using the Console or the Amazon A2I API


You can stop and delete a human loop in the Augmented AI console or by using the SageMaker API. When the human loop has been deleted, the status changes to `Deleted`.

**Delete a human loop (console)**

1. Navigate to the Augmented AI console at [https://console.amazonaws.cn/a2i/](https://console.amazonaws.cn/a2i).

1. In the navigation pane, under the **Augmented AI** section, choose **Human review workflows**.

1. Choose the hyperlinked name of the human review workflow you used to create the human loop you want to delete. 

1. In the **Human loops** section at the bottom of the page, select the human loop you want to stop and delete.

1. If the human loop status is `Completed`, `Stopped`, or `Failed`, select **Delete**.

   If the human loop **Status** is `InProgress`, select **Stop**. When the status changes to **Stopped**, select **Delete**.

**Delete a human loop (API)**

1. Check the status of your human loop using the Augmented AI Runtime API operation `[DescribeHumanLoop](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_DescribeHumanLoop.html)`. See examples using this operation in the following table. 

------
#### [ Amazon SDK for Python (Boto3) ]

   The following example uses the SDK for Python (Boto3) to describe the human loop named *example-human-loop*. For more information, see [describe\$1human\$1loop](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-a2i-runtime.html#AugmentedAIRuntime.Client.describe_human_loop) in the *Amazon SDK for Python (Boto) API Reference*.

   ```
   import boto3
   
   a2i_runtime_client = boto3.client('sagemaker-a2i-runtime')
   response = a2i_runtime_client.describe_human_loop(HumanLoopName='example-human-loop')
   human_loop_status = response['HumanLoopStatus']
   print(f'example-human-loop status is: {human_loop_status}')
   ```

------
#### [ Amazon CLI ]

   The following example uses the Amazon CLI to describe the human loop named *example-human-loop*. For more information, see [describe-human-loop](https://docs.amazonaws.cn/cli/latest/reference/sagemaker-a2i-runtime/describe-human-loop.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*. 

   ```
   $ aws sagemaker-a2i-runtime describe-human-loop --human-loop-name 'example-human-loop'
   ```

------

1. If the flow definition status is `Completed`, `Stopped`, or `Failed`, delete the flow definition using the Augmented AI Runtime API operation `[DeleteHumanLoop](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_DeleteHumanLoop.html)`.

------
#### [ Amazon SDK for Python (Boto3) ]

   The following example uses the SDK for Python (Boto3) to delete the human loop named *example-human-loop*. For more information, see [delete\$1human\$1loop](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-a2i-runtime.html#AugmentedAIRuntime.Client.delete_human_loop) in the *Amazon SDK for Python (Boto) API Reference*.

   ```
   import boto3
   
   a2i_runtime_client = boto3.client('sagemaker-a2i-runtime')
   response = a2i_runtime_client.delete_human_loop(HumanLoopName='example-human-loop')
   ```

------
#### [ Amazon CLI ]

   The following example uses the Amazon CLI to delete the human loop named *example-human-loop*. For more information, see [delete-human-loop](https://docs.amazonaws.cn/cli/latest/reference/sagemaker-a2i-runtime/delete-human-loop.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*. 

   ```
   $ aws sagemaker-a2i-runtime delete-human-loop --human-loop-name 'example-human-loop'
   ```

------

   If the human loop status is `InProgress`, stop the human loop using `[StopHumanLoop](https://docs.aws.amazon.com/augmented-ai/2019-11-07/APIReference/API_StopHumanLoop.html)` and then use `DeleteHumanLoop` to delete it. 

------
#### [ Amazon SDK for Python (Boto3) ]

   The following example uses the SDK for Python (Boto3) to describe the human loop named *example-human-loop*. For more information, see [stop\$1human\$1loop](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-a2i-runtime.html#AugmentedAIRuntime.Client.stop_human_loop) in the *Amazon SDK for Python (Boto) API Reference*.

   ```
   import boto3
   
   a2i_runtime_client = boto3.client('sagemaker-a2i-runtime')
   response = a2i_runtime_client.stop_human_loop(HumanLoopName='example-human-loop')
   ```

------
#### [ Amazon CLI ]

   The following example uses the Amazon CLI to describe the human loop named *example-human-loop*. For more information, see [stop-human-loop](https://docs.amazonaws.cn/cli/latest/reference/sagemaker-a2i-runtime/stop-human-loop.html) in the *[Amazon CLI Command Reference](https://docs.amazonaws.cn/cli/latest/reference/)*. 

   ```
   $ aws sagemaker-a2i-runtime stop-human-loop --human-loop-name 'example-human-loop'
   ```

------

# Create and Manage Worker Task Templates


You can create a task user interface for your workers by creating a *worker task template*. A worker task template is an HTML file that is used to display your input data and instructions to help workers complete your task.

For Amazon Rekognition or Amazon Textract task types, you can customize a pre-made worker task template using a graphical user interface (GUI) and avoid interacting with HTML code. For this option, use the instructions in [Create a Human Review Workflow (Console)](a2i-create-flow-definition.md#a2i-create-human-review-console) to create a human review workflow and customize your worker task template in the Amazon SageMaker AI console. Once you create a template using these instructions, it appears on the worker task templates page of the [Augmented AI console](https://console.amazonaws.cn/a2i).

If you are creating a human review workflow for a custom task type, you must create a *custom worker task template* using HTML code. For more information, see [Create Custom Worker Task Templates](a2i-custom-templates.md). 

If you create your template using HTML, you must use this template to generate an Amazon A2I *human task UI Amazon Resource Name (ARN)* in the Amazon A2I console. This ARN has the following format: `arn:aws:sagemaker:<aws-region>:<aws-account-number>:human-task-ui/<template-name>`. This ARN is associated with a worker task template resource that you can use in one or more human review workflows (flow definitions).

Generate a human task UI ARN using a worker task template by following the instructions found in [Create a Worker Task Template](a2i-worker-template-console.md#a2i-create-worker-template-console) or by using the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html) API operation.

**Topics**
+ [

# Create and Delete Worker Task Templates
](a2i-worker-template-console.md)
+ [

# Create Custom Worker Task Templates
](a2i-custom-templates.md)
+ [

# Creating Good Worker Instructions
](a2i-creating-good-instructions-guide.md)

# Create and Delete Worker Task Templates
Create and Delete Worker Task Templates

You can use a worker template to customize the interface and instructions that your workers see when working on your tasks. Use the instructions on this page to create a worker task template in the Augmented AI area of the Amazon SageMaker AI console. A starter template is provided for Amazon Textract and Amazon Rekognition tasks. To learn how to customize your template using HTML crowd elements, see [Create Custom Worker Task Templates](a2i-custom-templates.md).

When you create a worker template in the worker task templates page of the Augmented AI area of the SageMaker AI console, a worker task template ARN is generated. Use this ARN as the input to `HumanTaskUiArn` when you create a flow definition using the API operation [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html). You can choose this template when creating a human review workflow on the human review workflows page of the console. 

If you are creating a worker task template resource for an Amazon Textract or Amazon Rekognition task type, you can preview the worker UI that is generated from your template on the worker task templates console page. You must attach the policy described in [Enable Worker Task Template Previews](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai) to the IAM role that you use to preview the template.

## Create a Worker Task Template


You can create a worker task template using the SageMaker AI console and using the SageMaker API operation [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html). 

**Create a worker task template (console)**

1. Open the Amazon A2I console at [https://console.amazonaws.cn/a2i/](https://console.amazonaws.cn/a2i).

1. Under **Amazon Augmented AI** in the left navigation pane, choose **Worker task templates**.

1. Choose **Create template**.

1. In **Template name**, enter a unique name.

1. (Optional) Enter an **IAM role** that grants Amazon A2I the permissions necessary to call services on your behalf. 

1. In **Template type**, choose a template type from the dropdown list. If you are creating a template for a **Textract-form extraction** or **Rekognition-image moderation** task, choose the appropriate option. 

1. Enter your custom template elements as follows:
   + If you selected the Amazon Textract or Amazon Rekognition task template, the **Template editor** autopopulates with a default template that you can customize. 
   + If you are using a custom template, enter your predefined template in the editor. 

1. (Optional) To complete this step, you must provide an IAM role ARN with permission to read Amazon S3 objects that get rendered on your user interface in **Step 5**. 

   You can only preview your template if you are creating templates for Amazon Textract or Amazon Rekognition. 

   Choose **See preview** to preview the interface and instructions that workers see. This is an interactive preview. After you complete the sample task and choose **Submit**, you see the resulting output from the task that you just performed. 

   If you are creating a worker task template for a custom task type, you can preview your worker task UI using `RenderUiTemplate`. For more information, see [Preview a Worker Task Template](a2i-custom-templates.md#a2i-preview-your-custom-template).

1. When you're satisfied with your template, choose **Create**.

After you've created your template, you can select that template when you create a human review workflow in the console. Your template also appears in the **Amazon Augmented AI** section of the SageMaker AI console under **Worker task templates**. Choose your template to view its ARN. Use this ARN when using the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html) API operation . 

**Create a worker task template using a worker task template (API)**  
To generate a worker task template using the SageMaker API operation [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html), specify a name for your UI in `HumanTaskUiName` and input your HTML template in `Content` under `UiTemplate`. Find documentation on language-specific SDKs that support this API operation in the **See Also** section of the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html).

## Delete a Worker Task Template


Once you have created a worker task template, you can delete it using the SageMaker AI console or the SageMaker API operation [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteHumanTaskUi.html).

When you delete a worker task template, you are not able to use human review workflows (flow definitions) created using that template to start human loops. Any human loops that have already been created using the worker task template that you delete continue to be processed until completion and are not impacted. 

**Delete a worker task template (console)**

1. Open the Amazon A2I console at [https://console.amazonaws.cn/a2i/](https://console.amazonaws.cn/a2i).

1. Under Amazon Augmented AI in the left navigation pane, choose **Worker task templates**.

1. Select the template that you want to delete. 

1. Selete **Delete**.

1. A modal appears to confirm your choice. Select **Delete**.

**Delete a worker task template (API)**  
To delete a worker task template using the SageMaker API operation [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_DeleteHumanTaskUi.html), specify a name of your UI in `HumanTaskUiName`. 

# Create Custom Worker Task Templates


*Crowd HTML Elements* are web components that provide a number of task widgets and design elements that you can tailor to the question you want to ask. You can use these crowd elements to create a custom worker template and integrate it with an Amazon Augmented AI (Amazon A2I) human review workflow to customize the worker console and instructions. 

For a list of all HTML crowd elements available to Amazon A2I users, see [Crowd HTML Elements Reference](sms-ui-template-reference.md). For examples of templates, see the [Amazon GitHub repository](https://github.com/aws-samples/amazon-a2i-sample-task-uis), which contains over 60 sample custom task templates.

## Develop Templates Locally


When in the console to test how your template processes incoming data, you can test the look and feel of your template's HTML and custom elements in your browser by adding the following code to the top of your HTML file.

This loads the necessary code to render the custom HTML elements. Use this code if you want to develop your template's look and feel in your preferred editor instead of in the console.

This code won't parse your variables. You might want to replace them with sample content while developing locally.

## Use External Assets


Amazon Augmented AI custom templates enable you to embed external scripts and style sheets. For example, the following header embeds a `text/css` style sheet name `stylesheet` located at `https://www.example.com/my-enhancement-styles.css` into the custom template.

**Example**  

```
<script src="https://www.example.com/my-enhancment-script.js"></script>
<link rel="stylesheet" type="text/css" href="https://www.example.com/my-enhancement-styles.css">
```

If you encounter errors, ensure that your originating server is sending the correct MIME type and encoding headers with the assets.

For example, the MIME and encoding type for remote scripts is `application/javascript;CHARSET=UTF-8`.

The MIME and encoding type for remote stylesheets is `text/css;CHARSET=UTF-8`.

## Track Your Variables


When building a custom template, you must add variables to it to represent the pieces of data that might change from task to task, or worker to worker. If you're starting with one of the sample templates, you need to make sure you're aware of the variables it already uses. 

For example, for a custom template that integrates an Augmented AI human review loop with a Amazon Textract text review task, `{{ task.input.selectedAiServiceResponse.blocks }}` is used for initial-value input data. For Amazon Augmented AI (Amazon A2I) integration with Amazon Rekognition , `{{ task.input.selectedAiServiceResponse.moderationLabels }}` is used. For a custom task type, you need to determine the input parameter for your task type. Use `{{ task.input.customInputValuesForStartHumanLoop}}` where you specify `customInputValuesForStartHumanLoop`. 

## Custom Template Example for Amazon Textract


All custom templates begin and end with the `<crowd-form> </crowd-form>` elements. Like standard HTML `<form>` elements, all of your form code should go between these elements. 

For an Amazon Textract document analysis task, use the `<crowd-textract-analyze-document>` element. It uses the following attributes: 
+ `src` – Specifies the URL of the image file to be annotated.
+ `initialValue` – Sets initial values for attributes found in the worker UI.
+ `blockTypes` (required) – Determines the kind of analysis that the workers can do. Only `KEY_VALUE_SET` is currently supported. 
+ `keys` (required) – Specifies new keys and the associated text value that the worker can add.
+ `no-key-edit` (required) – Prevents the workers from editing the keys of annotations passed through `initialValue`.
+ `no-geometry-edit` – Prevents workers from editing the polygons of annotations passed through `initialValue`.

For children of the `<crowd-textract-analyze-document>` element, you must have two Regions. You can use arbitrary HTML and CSS elements in these Regions. 
+ `<full-instructions>` – Instructions that are available from the **View full instructions** link in the tool. You can leave this blank, but we recommend that you provide complete instructions to get better results.
+ `<short-instructions>` – A brief description of the task that appears in the tool's sidebar. You can leave this blank, but we recommend that you provide complete instructions to get better results.

 An Amazon Textract template would look similar to the following.

**Example**  

## Custom Template Example for Amazon Rekognition


All custom templates begin and end with the `<crowd-form> </crowd-form>` elements. Like standard HTML `<form>` elements, all of your form code should go between these elements. For an Amazon Rekognition custom task template, use the `<crowd-rekognition-detect-moderation-labels>` element. This element supports the following attributes: 
+ `categories` – An array of strings *or* an array of objects where each object has a `name` field.
  + If the categories come in as objects, the following applies:
    + The displayed categories are the value of the `name` field. 
    + The returned answer contains the *full* objects of any selected categories.
  + If the categories come in as strings, the following applies:
    + The returned answer is an array of all the strings that were selected.
+ `exclusion-category` – By setting this attribute, you create a button underneath the categories in the UI. When a user selects the button, all categories are deselected and disabled. If the worker selects the button again, you re-enable users to choose categories. If the worker submits the task by selecting **Submit** after you select the button, that task returns an empty array.

For children of the `<crowd-rekognition-detect-moderation-labels>` element, you must have two Regions.
+ `<full-instructions>` – Instructions that are available from the **View full instructions** link in the tool. You can leave this blank, but we recommend that you provide complete instructions to get better results.
+ `<short-instructions>` – Brief description of the task that appears in the tool's sidebar. You can leave this blank, but we recommend that you provide complete instructions to get better results.

A template using these elements would look similar to the following.

## Add automation with Liquid


The custom template system uses [Liquid](https://shopify.github.io/liquid/) for automation. *Liquid* is an open-source inline markup language. For more information and documentation, see the [Liquid homepage](https://shopify.github.io/liquid/).

In Liquid, the text between single curly braces and percent symbols is an instruction or *tag* that performs an operation like control flow or iteration. Text between double curly braces is a variable or *object* that outputs its value. The following list includes two types of liquid tags that you may find useful to automate template input data processing. If you select one of the following tag-types, you are redirected to the Liquid documentation.
+ [Control flow](https://shopify.github.io/liquid/tags/control-flow/): Includes programming logic operators like `if/else`, `unless`, and `case/when`.
+ [Iteration](https://shopify.github.io/liquid/tags/iteration/): Enables you to run blocks of code repeatedly using statements like for loops.

  For example, the following code example demonstrates how you can use the Liquid `for` tag to create a `for` loop. This example loops through the [https://docs.amazonaws.cn/rekognition/latest/dg/API_ModerationLabel.html](https://docs.amazonaws.cn/rekognition/latest/dg/API_ModerationLabel.html) returned from Amazon Rekognition and displays the `moderationLabels` attributes `name` and `parentName` for workers to review:

  ```
   {% for label in task.input.selectedAiServiceResponse.moderationLabels %}
      {
        name: &quot;{{ label.name }}&quot;,
        parentName: &quot;{{ label.parentName }}&quot;,
      },
   {% endfor %}
  ```

### Use variable filters


In addition to the standard [Liquid filters](https://shopify.github.io/liquid/filters/abs/) and actions, Amazon Augmented AI (Amazon A2I) offers additional filters. You apply filters by placing a pipe (`|`) character after the variable name, and then specifying a filter name. To chain filters, use the following format.

**Example**  

```
{{ <content> | <filter> | <filter> }}
```

#### Autoescape and Explicit Escape


By default, inputs are HTML-escaped to prevent confusion between your variable text and HTML. You can explicitly add the `escape` filter to make it more obvious to someone reading the source of your template that escaping is being done.

#### escape\$1once


`escape_once` ensures that if you've already escaped your code, it doesn't get re-escaped again. For example, it ensures that `&amp;` doesn't become `&amp;amp;`.

#### skip\$1autoescape


`skip_autoescape` is useful when your content is meant to be used as HTML. For example, you might have a few paragraphs of text and some images in the full instructions for a bounding box.

**Note**  
Use `skip_autoescape` sparingly. As a best practice for templates, avoid passing in functional code or markup with `skip_autoescape` unless you are absolutely sure that you have strict control over what's being passed. If you're passing user input, you could be opening your workers up to a cross-site scripting attack.

#### to\$1json


`to_json` encodes data that you provide to JavaScript Object Notation (JSON). If you provide an object, it serializes it.

#### grant\$1read\$1access


`grant_read_access` takes an Amazon Simple Storage Service (Amazon S3) URI and encodes it into an HTTPS URL with a short-lived access token for that resource. This makes it possible to display photo, audio, or video objects stored in S3 buckets that are not otherwise publicly accessible to workers.

#### s3\$1presign


 The `s3_presign` filter works the same way as the `grant_read_access` filter. `s3_presign` takes an Amazon S3 URI and encodes it into an HTTPS URL with a short-lived access token for that resource. This makes it possible to display photo, audio, or video objects stored in S3 buckets that are not otherwise publicly accessible to workers.

**Example of the variable filters**  
Input  

```
auto-escape: {{ "Have you read 'James & the Giant Peach'?" }}
explicit escape: {{ "Have you read 'James & the Giant Peach'?" | escape }}
explicit escape_once: {{ "Have you read 'James &amp; the Giant Peach'?" | escape_once }}
skip_autoescape: {{ "Have you read 'James & the Giant Peach'?" | skip_autoescape }}
to_json: {{ jsObject | to_json }}                
grant_read_access: {{ "s3://amzn-s3-demo-bucket/myphoto.png" | grant_read_access }}
s3_presign: {{ "s3://amzn-s3-demo-bucket/myphoto.png" | s3_presign }}
```

**Example**  
Output  

```
auto-escape: Have you read &#39;James &amp; the Giant Peach&#39;?
explicit escape: Have you read &#39;James &amp; the Giant Peach&#39;?
explicit escape_once: Have you read &#39;James &amp; the Giant Peach&#39;?
skip_autoescape: Have you read 'James & the Giant Peach'?
to_json: { "point_number": 8, "coords": [ 59, 76 ] }
grant_read_access: https://s3.amazonaws.com/amzn-s3-demo-bucket/myphoto.png?<access token and other params>
s3_presign: https://s3.amazonaws.com/amzn-s3-demo-bucket/myphoto.png?<access token and other params>
```

**Example of an automated classification template.**  
To automate this simple text classification sample, include the Liquid tag `{{ task.input.source }}`. This example uses the [crowd-classifier](sms-ui-template-crowd-classifier.md) element.

## Preview a Worker Task Template


To preview a custom worker task template, use the SageMaker AI `RenderUiTemplate` operation. You can use the `RenderUiTemplate` operation with the Amazon CLI or your preferred Amazon SDK. For documentation on the supported language specific SDKs for this API operation, see the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_SeeAlso](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_SeeAlso) section of the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html). 

**Prerequisites**

To preview your worker task template, the Amazon Identity and Access Management (IAM) role Amazon Resource Name (ARN), or `RoleArn`, that you use must have permission to access to the S3 objects that are used by the template. To learn how to configure your role or user see [Enable Worker Task Template Previews](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai).

**To preview your worker task template using the `RenderUiTemplate` operation:**

1. Provide a **`RoleArn`** of the role with required policies attached to preview your custom template. 

1. In the **`Input`** parameter of **`Task`**, provide a JSON object that contains values for the variables defined in the template. These are the variables that are substituted for the `task.input.source` variable. For example, if you define a task.input.text variable in your template, you can supply the variable in the JSON object as `text`: `sample text`.

1. In the **`Content`** parameter of **`UiTemplate`**, insert your template.

Once you've configured `RenderUiTemplate`, use your preferred SDK or the Amazon CLI to submit a request to render your template. If your request was successful, the response includes [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_ResponseSyntax](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_ResponseSyntax), a Liquid template that renders the HTML for the worker UI.

**Important**  
To preview your template, you need an IAM role with permissions to read Amazon S3 objects that get rendered on your user interface. For a sample policy that you can attach to your IAM role to grant these permissions, see [Enable Worker Task Template Previews](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai). 

# Creating Good Worker Instructions


Creating good instructions for your human review jobs improves your worker's accuracy in completing their task. You can modify the default instructions that are provided in the console when creating a human review workflow, or you can use the console to create a custom worker template and include your instructions in this template. The instructions are shown to the worker on the UI page where they complete their labeling task.

## Create Good Worker Instructions


There are three kinds of instructions in the Amazon Augmented AI console:
+ **Task Description** – The description should provide a succinct explanation of the task.
+ **Instructions** – These instructions are shown on the same webpage where workers complete a task. These instructions should provide an easy reference to show the worker the correct way to complete the task.
+ **Additional Instructions** – These instructions are shown in a dialog box that appears when a worker chooses **View full instructions**. We recommend that you provide detailed instructions for completing the task, and include several examples showing edge cases and other difficult situations for labeling objects.

## Add Example Images to Your Instructions


Images provide useful examples for your workers. To add a publicly accessible image to your instructions, do the following:

1. Place the cursor where the image should go in the instructions editor.

1. Choose the image icon in the editor toolbar.

1. Enter the URL of your image.

If your instruction image is in an S3 bucket that isn't publicly accessible, do the following:
+ For the image URL, enter: `{{ 'https://s3.amazonaws.com/your-bucket-name/image-file-name' | grant_read_access }}`.

This renders the image URL with a short-lived, one-time access code that's appended so the worker's browser can display it. A broken image icon is displayed in the instructions editor, but previewing the tool displays the image in the rendered preview. See [s3\$1presigngrant\$1read\$1accesss3\$1presign](a2i-custom-templates.md#a2i-custom-templates-step2-automate-grantreadaccess) for more information about the `grand_read_access` element. 

# Monitor and Manage Your Human Loop


Once you've started a human review loop, you can check the results of tasks sent to the loop and manage it using the [Amazon Augmented AI Runtime API](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/Welcome.html). Additionally, Amazon A2I integrates with Amazon EventBridge (also known as Amazon CloudWatch Events) to alert you when a human review loop status changes to `Completed`, `Failed`, or `Stopped`. This event delivery is guaranteed at least once, which means all events created when human loops finish are successfully delivered to EventBridge.

Use the procedures below to learn how to use the Amazon A2I Runtime API to monitor and manage your human loops. See [Use Amazon CloudWatch Events in Amazon Augmented AI](a2i-cloudwatch-events.md) to learn how Amazon A2I integrates with Amazon EventBridge.

**To check your output data:**

1. Check the results of your human loop by calling the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_DescribeHumanLoop.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_DescribeHumanLoop.html) operation. The result of this API operation contains information about the reason for and outcome of the loop activation.

1. Check the output data from your human loop in Amazon Simple Storage Service (Amazon S3). In the path to the data, `YYYY/MM/DD/hh/mm/ss` represents the human loop creation date with year (`YYYY`), month (`MM`), and day (`DD`), and the creation time with hour (`hh`), minute (`mm`), and second (`ss`). 

   ```
   s3://customer-output-bucket-specified-in-flow-definition/flow-definition-name/YYYY/MM/DD/hh/mm/ss/human-loop-name/output.json
   ```

You can integrate this structure with Amazon Glue or Amazon Athena to partition and analyze your output data. For more information, see [Managing Partitions for ETL Output in Amazon Glue](https://docs.amazonaws.cn/glue/latest/dg/aws-glue-programming-etl-partitions.html).

To learn more about Amazon A2I output data format, see [Amazon A2I Output Data](a2i-output-data.md).

**To stop and delete your human loop:**

1. Once a human loop has been started, you can stop your human loop by calling the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_StopHumanLoop.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_StopHumanLoop.html) operation using the `HumanLoopName`. If a human loop was successfully stopped, the server sends back an HTTP 200 response. 

1. To delete a human loop for which the status equals `Failed`, `Completed`, or `Stopped`, use the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_DeleteHumanLoop.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_DeleteHumanLoop.html) operation. 

**To list human loops:**

1. You can list all active human loops by calling the [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_ListHumanLoops.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_ListHumanLoops.html) operation. You can filter human loops by the creation date of the loop using the `CreationTimeAfter` and `CreateTimeBefore` parameters. 

1. If successful, `ListHumanLoops` returns [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopSummary.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_HumanLoopSummary.html) and `NextToken` objects in the response element. `HumanLoopSummaries` contains information about a single human loop. For example, it lists a loop's status and, if applicable, its failure reason. 

   Use the string returned in `NextToken` as an input in a subsequent call to `ListHumanLoops` to see the next page of human loops. 

# Amazon A2I Output Data
Output Data

When your machine learning workflow sends Amazon A2I a data object, a *human loop* is created and human reviewers receive a *task* to review that data object. The output data from each human review task is stored in the Amazon Simple Storage Service (Amazon S3) output bucket you specify in your human review workflow. In the path to the data, `YYYY/MM/DD/hh/mm/ss` represents the human loop creation date with year (`YYYY`), month (`MM`), and day (`DD`), and the creation time with hour (`hh`), minute (`mm`), and second (`ss`). 

```
s3://customer-output-bucket-specified-in-flow-definition/flow-definition-name/YYYY/MM/DD/hh/mm/ss/human-loop-name/output.json
```

The content of your output data depends on the type of [task type](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-task-types-general.html) (built-in or custom) and the type of [workforce](https://docs.amazonaws.cn/sagemaker/latest/dg/sms-workforce-management.html) you use. Your output data always includes the response from the human worker. Additionally, output data may include metadata about the human loop, the human reviewer (worker), and the data object. 

Use the following sections to learn more about Amazon A2I output data format for different task types and workforces. 

## Output Data From Built-In Task Types


Amazon A2I built-in task types include Amazon Textract and Amazon Rekognition. In addition to human responses, the output data from one of these tasks includes details about the reason the human loop was created and information about the integrated service used to create the human loop. Use the following table to learn more about the output data schema for all built-in task types. The *value* for each of these parameters depends on the service you use with Amazon A2I. Refer to the second table in this section for more information about these service-specific values. 


****  

| Parameter | Value Type | Example Values | Description | 
| --- | --- | --- | --- | 
| awsManagedHumanLoopRequestSource |  String  | AWS/Rekognition/DetectModerationLabels/Image/V3 or AWS/Textract/AnalyzeDocument/Forms/V1 | The API operation and associated Amazon services that requested that Amazon A2I create the a human loop. This is the API operation you use to configure your Amazon A2I human loop. | 
| flowDefinitionArn |  String  | arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name |  The Amazon Resource Number (ARN) of the human review workflow (flow definition) used to create the human loop.   | 
| humanAnswers |  List of JSON objects  | <pre>{<br />"answerContent": {<br />    "AWS/Rekognition/DetectModerationLabels/Image/V3": {<br />        "moderationLabels": [...]<br />    }<br />},</pre> or<pre>{<br />    "answerContent": {<br />        "AWS/Textract/AnalyzeDocument/Forms/V1": {<br />            "blocks": [...]<br />    }<br />},</pre> | A list of JSON objects that contain worker responses in answerContent. This object also contains submission details and, if a private workforce was used, worker metadata. To learn more, see [Track Worker Activity](#a2i-worker-id-private). For human loop output data produced from Amazon Rekognition `DetectModerationLabel` review tasks, this parameter only contains positive responses. For example, if workers select *No content*, this response is not included. | 
| humanLoopName |  String  |  `'human-loop-name'`  | The name of the human loop. | 
| inputContent |  JSON object  |  <pre>{<br />    "aiServiceRequest": {...},<br />    "aiServiceResponse": {...},<br />    "humanTaskActivationConditionResults": {...},<br />    "selectedAiServiceResponse": {...}<br />}</pre>  |  The input content the Amazon service sent to Amazon A2I when it requested a human loop be created.   | 
| aiServiceRequest |  JSON object  | <pre>{<br />    "document": {...},<br />    "featureTypes": [...],<br />    "humanLoopConfig": {...}<br />}</pre>or <pre>{<br />    "image": {...},<br />    "humanLoopConfig": {...}<br />}</pre> |  The original request sent to the Amazon service integrated with Amazon A2I. For example, if you use Amazon Rekognition with Amazon A2I, this includes the request made through the API operation `DetectModerationLabels`. For Amazon Textract integrations, this includes the request made through `AnalyzeDocument`.  | 
| aiServiceResponse |  JSON object  |  <pre>{<br />    "moderationLabels": [...],<br />    "moderationModelVersion": "3.0"<br />}</pre> or <pre>{<br />    "blocks": [...],<br />    "documentMetadata": {}<br />}</pre>  |  The full response from the Amazon service. This is the data that is used to determine if a human review is required. This object may contain metadata about the data object that is not shared with human reviewers.   | 
| selectedAiServiceResponse |  JSON object  |  <pre>{<br />    "moderationLabels": [...],<br />    "moderationModelVersion": "3.0"<br />}</pre> or <pre>{<br />    "blocks": [...],<br />    "documentMetadata": {}<br />}</pre>  |  The subset of the `aiServiceResponse` that matches the activation conditions in `ActivationConditions`. All data objects listed in `aiServiceResponse` are listed in `selectedAiServiceResponse` when inferences are randomly sampled, or all inferences initiated activation conditions.  | 
| humanTaskActivationConditionResults |  JSON object  |  <pre>{<br />     "Conditions": [...]<br />}</pre>  |  A JSON object in `inputContent` that contains the reason a human loop was created. This includes a list of the activation conditions (`Conditions`) included in your human review workflow (flow definition), and the evaluation result for each condition–this result is either `true` or `false`. To learn more about activation conditions, see [JSON Schema for Human Loop Activation Conditions in Amazon Augmented AI](a2i-human-fallback-conditions-json-schema.md).  | 

Select a tab on the following table to learn about the task type–specific parameters and see an example output-data code block for each of the built-in task types.

------
#### [ Amazon Textract Task Type Output Data ]

When you use the Amazon Textract built-in integration, you see `'AWS/Textract/AnalyzeDocument/Forms/V1'` as the value for `awsManagedHumanLoopRequestSource` in your output data.

The `answerContent` parameter contains a `Block` object that includes human responses for all blocks sent to Amazon A2I.

The `aiServiceResponse` parameter also includes a `Block` object with Amazon Textract's response to the original request sent using to `AnalyzeDocument`.

To learn more about the parameters you see in the block object, refer to [Block](https://docs.amazonaws.cn/textract/latest/dg/API_Block.html) in the *Amazon Textract Developer Guide*. 

The following is an example of the output data from an Amazon A2I human review of Amazon Textract document analysis inferences. 

```
{
    "awsManagedHumanLoopRequestSource": "AWS/Textract/AnalyzeDocument/Forms/V1",
    "flowDefinitionArn": "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
    "humanAnswers": [
        {
            "answerContent": {
                "AWS/Textract/AnalyzeDocument/Forms/V1": {
                    "blocks": [...]
                }
            },
            "submissionTime": "2020-09-28T19:17:59.880Z",
            "workerId": "111122223333",
            "workerMetadata": {
                "identityData": {
                    "identityProviderType": "Cognito",
                    "issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_111111",
                    "sub": "c6aa8eb7-9944-42e9-a6b9-111122223333"
                }
            }
        }
    ],
    "humanLoopName": "humnan-loop-name",
    "inputContent": {
        "aiServiceRequest": {
            "document": {
                "s3Object": {
                    "bucket": "amzn-s3-demo-bucket1",
                    "name": "document-demo.jpg"
                }
            },
            "featureTypes": [
                "TABLES",
                "FORMS"
            ],
            "humanLoopConfig": {
                "dataAttributes": {
                    "contentClassifiers": [
                        "FreeOfPersonallyIdentifiableInformation"
                    ]
                },
                "flowDefinitionArn": "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
                "humanLoopName": "humnan-loop-name"
            }
        },
        "aiServiceResponse": {
            "blocks": [...],
            "documentMetadata": {
                "pages": 1
            }
        },
        "humanTaskActivationConditionResults": {
            "Conditions": [
                {
                    "EvaluationResult": true,
                    "Or": [
                        {
                            "ConditionParameters": {
                                "ImportantFormKey": "Mail address",
                                "ImportantFormKeyAliases": [
                                    "Mail Address:",
                                    "Mail address:",
                                    "Mailing Add:",
                                    "Mailing Addresses"
                                ],
                                "KeyValueBlockConfidenceLessThan": 100,
                                "WordBlockConfidenceLessThan": 100
                            },
                            "ConditionType": "ImportantFormKeyConfidenceCheck",
                            "EvaluationResult": true
                        },
                        {
                            "ConditionParameters": {
                                "ImportantFormKey": "Mail address",
                                "ImportantFormKeyAliases": [
                                    "Mail Address:",
                                    "Mail address:",
                                    "Mailing Add:",
                                    "Mailing Addresses"
                                ]
                            },
                            "ConditionType": "MissingImportantFormKey",
                            "EvaluationResult": false
                        }
                    ]
                }
            ]
        },
        "selectedAiServiceResponse": {
            "blocks": [...]
        }
    }
}
```

------
#### [ Amazon Rekognition Task Type Output Data ]

When you use the Amazon Textract built-in integration, you see the string `'AWS/Rekognition/DetectModerationLabels/Image/V3'` as the value for `awsManagedHumanLoopRequestSource` in your output data.

The `answerContent` parameter contains a `moderationLabels` object that contains human responses for all moderation labels sent to Amazon A2I.

The `aiServiceResponse` parameter also includes a `moderationLabels` object with Amazon Rekognition's response to the original request sent to `DetectModerationLabels`.

To learn more about the parameters you see in the block object, refer to [ModerationLabel](https://docs.amazonaws.cn/rekognition/latest/dg/API_ModerationLabel.html) in the Amazon Rekognition Developer Guide. 

The following is an example of the output data from an Amazon A2I human review of Amazon Rekognition image moderation inferences. 

```
{
    "awsManagedHumanLoopRequestSource": "AWS/Rekognition/DetectModerationLabels/Image/V3",
    "flowDefinitionArn": "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
    "humanAnswers": [
        {
            "answerContent": {
                "AWS/Rekognition/DetectModerationLabels/Image/V3": {
                    "moderationLabels": [...]
                }
            },
            "submissionTime": "2020-09-28T19:22:35.508Z",
            "workerId": "ef7294f850a3d9d1",
            "workerMetadata": {
                "identityData": {
                    "identityProviderType": "Cognito",
                    "issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_111111",
                    "sub": "c6aa8eb7-9944-42e9-a6b9-111122223333"
                }
            }
        }
    ],
    "humanLoopName": "humnan-loop-name",
    "inputContent": {
        "aiServiceRequest": {
            "humanLoopConfig": {
                "flowDefinitionArn": "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
                "humanLoopName": "humnan-loop-name"
            },
            "image": {
                "s3Object": {
                    "bucket": "amzn-s3-demo-bucket1",
                    "name": "example-image.jpg"
                }
            }
        },
        "aiServiceResponse": {
            "moderationLabels": [...],
            "moderationModelVersion": "3.0"
        },
        "humanTaskActivationConditionResults": {
            "Conditions": [
                {
                    "EvaluationResult": true,
                    "Or": [
                        {
                            "ConditionParameters": {
                                "ConfidenceLessThan": 98,
                                "ModerationLabelName": "Suggestive"
                            },
                            "ConditionType": "ModerationLabelConfidenceCheck",
                            "EvaluationResult": true
                        },
                        {
                            "ConditionParameters": {
                                "ConfidenceGreaterThan": 98,
                                "ModerationLabelName": "Female Swimwear Or Underwear"
                            },
                            "ConditionType": "ModerationLabelConfidenceCheck",
                            "EvaluationResult": false
                        }
                    ]
                }
            ]
        },
        "selectedAiServiceResponse": {
            "moderationLabels": [
                {
                    "confidence": 96.7122802734375,
                    "name": "Suggestive",
                    "parentName": ""
                }
            ],
            "moderationModelVersion": "3.0"
        }
    }
}
```

------

## Output Data From Custom Task Types


When you add Amazon A2I to a custom human review workflow, you see the following parameters in the output data returned from human review tasks. 


****  

| Parameter | Value Type | Description | 
| --- | --- | --- | 
|  `flowDefinitionArn`  |  String  |  The Amazon Resource Number (ARN) of the human review workflow (flow definition) used to create the human loop.   | 
|  `humanAnswers`  |  List of JSON objects  | A list of JSON objects that contain worker responses in answerContent. The value in this parameter is determined by the output received from your [worker task template](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-instructions-overview.html). If you are using a private workforce, worker metadata is included. To learn more, see [Track Worker Activity](#a2i-worker-id-private). | 
|  `humanLoopName`  | String | The name of the human loop. | 
|  `inputContent`  |  JSON Object  |  The input content sent to Amazon A2I in the request to [https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_StartHumanLoop.html](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/API_StartHumanLoop.html).  | 

The following is an example of output data from a custom integration with Amazon A2I and Amazon Transcribe. In this example, the `inputContent` consists of:
+ A path to an .mp4 file in Amazon S3 and the video title
+ The transcription returned from Amazon Transcribe (parsed from Amazon Transcribe output data)
+ A start and end time used by the worker task template to clip the .mp4 file and show workers a relevant portion of the video

```
{
    "flowDefinitionArn": "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name",
    "humanAnswers": [
        {
            "answerContent": {
                "transcription": "use lambda to turn your notebook"
            },
            "submissionTime": "2020-06-18T17:08:26.246Z",
            "workerId": "ef7294f850a3d9d1",
            "workerMetadata": {
                "identityData": {
                    "identityProviderType": "Cognito",
                    "issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_111111",
                    "sub": "c6aa8eb7-9944-42e9-a6b9-111122223333"
                }
            }

        }
    ],
    "humanLoopName": "human-loop-name",
    "inputContent": {
        "audioPath": "s3://amzn-s3-demo-bucket1/a2i_transcribe_demo/Fully-Managed Notebook Instances with Amazon SageMaker - a Deep Dive.mp4",
        "end_time": 950.27,
        "original_words": "but definitely use Lambda to turn your ",
        "start_time": 948.51,
        "video_title": "Fully-Managed Notebook Instances with Amazon SageMaker - a Deep Dive.mp4"
    }
}
```

## Track Worker Activity


Amazon A2I provides information that you can use to track individual workers in task output data. To identify the worker that worked on the human review task, use the following from the output data in Amazon S3:
+ The `acceptanceTime` is the time that the worker accepted the task. The format of this date and time stamp is `YYYY-MM-DDTHH:MM:SS.mmmZ` for the year (`YYYY`), month (`MM`), day (`DD`), hour (`HH`), minute (`MM`), second (`SS`), and millisecond (`mmm`). The date and time are separated by a **T**. 
+ The `submissionTime` is the time that the worker submitted their annotations using the **Submit** button. The format of this date and time stamp is `YYYY-MM-DDTHH:MM:SS.mmmZ` for the year (`YYYY`), month (`MM`), day (`DD`), hour (`HH`), minute (`MM`), second (`SS`), and millisecond (`mmm`). The date and time are separated by a **T**. 
+ `timeSpentInSeconds` reports the total time, in seconds, that a worker actively worked on that task. This metric does not include time when a worker paused or took a break.
+ The `workerId` is unique to each worker. 
+ If you use a [private workforce](https://docs.amazonaws.cn/sagemaker/latest/dg/sms-workforce-private.html), in `workerMetadata`, you see the following.
  + The `identityProviderType` is the service used to manage the private workforce. 
  + The `issuer` is the Amazon Cognito user pool or OpenID Connect (OIDC) Identity Provider (IdP) issuer associated with the work team assigned to this human review task.
  + A unique `sub` identifier refers to the worker. If you create a workforce using Amazon Cognito, you can retrieve details about this worker (such as the name or user name) associated with this ID using Amazon Cognito. To learn how, see [Managing and Searching for User Accounts](https://docs.amazonaws.cn/cognito/latest/developerguide/how-to-manage-user-accounts.html#manage-user-accounts-searching-user-attributes) in *[Amazon Cognito Developer Guide](https://docs.amazonaws.cn/cognito/latest/developerguide/)*.

The following is an example of the output you may see if you use Amazon Cognito to create a private workforce. This is identified in the `identityProviderType`.

```
"submissionTime": "2020-12-28T18:59:58.321Z",
"acceptanceTime": "2020-12-28T18:59:15.191Z", 
"timeSpentInSeconds": 40.543,
"workerId": "a12b3cdefg4h5i67",
"workerMetadata": {
    "identityData": {
        "identityProviderType": "Cognito",
        "issuer": "https://cognito-idp.aws-region.amazonaws.com/aws-region_123456789",
        "sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
    }
}
```

 The following is an example of the output you may see if you use your own OIDC IdP to create a private workforce:

```
"workerMetadata": {
        "identityData": {
            "identityProviderType": "Oidc",
            "issuer": "https://example-oidc-ipd.com/adfs",
            "sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
        }
}
```

To learn more about using private workforces, see [Private workforce](sms-workforce-private.md).

# Permissions and Security in Amazon Augmented AI
Permissions and Security

When using Amazon Augmented AI (Amazon A2I) to create a human review workflow for your ML/AI application, you create and configure *resources* in Amazon SageMaker AI such as a human workforce and worker task templates. To configure and start a human loop, you either integrate Amazon A2I with other Amazon services such as Amazon Textract or Amazon Rekognition, or use the Amazon Augmented AI Runtime API. To create a human review workflow and start a human loop, you must attach certain policies to your Amazon Identity and Access Management (IAM) role or user. Specifically: 
+ When you start a human loop using image input data on or after January 12th, 2020, you must add a CORS header policy to the Amazon S3 bucket that contains your input data. See [CORS Permission Requirement](#a2i-cors-update) to learn more. 
+ When you create a flow definition, you need to provide a role that grants Amazon A2I permission to access Amazon S3 both for reading objects that are rendered in a human task UI and for writing the results of the human review. 

  This role must also have a trust policy attached to give SageMaker AI permission to assume the role. This allows Amazon A2I to perform actions in accordance with permissions that you attach to the role. 

  See [Add Permissions to the IAM Role Used to Create a Flow Definition](#a2i-human-review-permissions-s3) for example policies that you can modify and attach to the role you use to create a flow definition. These are the policies that are attached to the IAM role that is created in the **Human review workflows** section of the Amazon A2I area of the SageMaker AI console. 
+ To create and start human loops, you either use an API operation from a built-in task type (such as `DetectModerationLabel` or `AnalyzeDocument`) or the Amazon A2I Runtime API operation `StartHumanLoop` in a custom ML application. You need to attach the `AmazonAugmentedAIFullAccess` managed policy to the user that invokes these API operations to grant permission to these services to use Amazon A2I operations. To learn how, see [Create a User That Can Invoke Amazon A2I API Operations](#create-user-grants).

  This policy does *not* grant permission to invoke the API operations of the Amazon service associated with built-in task types. For example, `AmazonAugmentedAIFullAccess` does not grant permission to call the Amazon Rekognition `DetectModerationLabel` API operation or Amazon Textract `AnalyzeDocument` API operation. You can use the more general policy, `AmazonAugmentedAIIntegratedAPIAccess`, to grant these permissions. For more information, see [Create a User With Permissions to Invoke Amazon A2I, Amazon Textract, and Amazon Rekognition API Operations](#a2i-grant-general-permission). This is a good option when you want to grant a user broad permissions to use Amazon A2I and integrated Amazon services' API operations. 

  If you want to configure more granular permissions, see [Amazon Rekognition Identity-Based Policy Examples](https://docs.amazonaws.cn/rekognition/latest/dg/security_iam_id-based-policy-examples.html) and [Amazon Textract Identity-Based Policy Examples](https://docs.amazonaws.cn/textract/latest/dg/security_iam_id-based-policy-examples.html) for identity-based policies you can use to grant permission to use these individual services.
+ To preview your custom worker task UI template, you need an IAM role with permissions to read Amazon S3 objects that get rendered on your user interface. See a policy example in [Enable Worker Task Template Previews](#permissions-for-worker-task-templates-augmented-ai).

**Topics**
+ [

## CORS Permission Requirement
](#a2i-cors-update)
+ [

## Add Permissions to the IAM Role Used to Create a Flow Definition
](#a2i-human-review-permissions-s3)
+ [

## Create a User That Can Invoke Amazon A2I API Operations
](#create-user-grants)
+ [

## Create a User With Permissions to Invoke Amazon A2I, Amazon Textract, and Amazon Rekognition API Operations
](#a2i-grant-general-permission)
+ [

## Enable Worker Task Template Previews
](#permissions-for-worker-task-templates-augmented-ai)
+ [

## Using Amazon A2I with Amazon KMS Encrypted Buckets
](#a2i-kms-encryption)
+ [

## Additional Permissions and Security Resources
](#additional-security-resources-augmented-ai)

## CORS Permission Requirement


Earlier in 2020, widely used browsers like Chrome and Firefox changed their default behavior for rotating images based on image metadata, referred to as [EXIF data](https://en.wikipedia.org/wiki/Exif). Previously, images would always display in browsers exactly how they are stored on disk, which is typically unrotated. After the change, images now rotate according to a piece of image metadata called *orientation value*. This has important implications for the entire machine learning (ML) community. For example, if the EXIF orientation is not considered, applications that are used to annotate images may display images in unexpected orientations and result in incorrect labels. 

Starting with Chrome 89, Amazon can no longer automatically prevent the rotation of images because the web standards group W3C has decided that the ability to control rotation of images violates the web’s Same-Origin Policy. Therefore, to ensure human workers annotate your input images in a predictable orientation when you submit requests to create a human loop, you must add a CORS header policy to the S3 buckets that contain your input images.

**Important**  
If you do not add a CORS configuration to the S3 buckets that contains your input data, human review tasks for those input data objects fail.

You can add a CORS policy to an S3 bucket that contains input data in the Amazon S3 console. To set the required CORS headers on the S3 bucket that contains your input images in the S3 console, follow the directions detailed in [How do I add cross-domain resource sharing with CORS?](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/add-cors-configuration.html). Use the following CORS configuration code for the buckets that host your images. If you use the Amazon S3 console to add the policy to your bucket, you must use the JSON format.

**JSON**

```
[{
   "AllowedHeaders": [],
   "AllowedMethods": ["GET"],
   "AllowedOrigins": ["*"],
   "ExposeHeaders": []
}]
```

**XML**

```
<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>
```

The following GIF demonstrates the instructions found in the Amazon S3 documentation to add a CORS header policy using the Amazon S3 console.

![\[Gif on how to add a CORS header policy using the Amazon S3 console.\]](http://docs.amazonaws.cn/en_us/sagemaker/latest/dg/images/sms/gifs/cors-config.gif)


## Add Permissions to the IAM Role Used to Create a Flow Definition


To create a flow definition, attach the policies in this section to the role that you use when creating a human review workflow in the SageMaker AI console, or when using the `CreateFlowDefinition` API operation.
+ If you are using the console to create a human review workflow, enter the role Amazon Resource Name (ARN) in the **IAM role** field when [creating a human review workflow in the console](https://docs.amazonaws.cn/sagemaker/latest/dg/create-human-review-console.html). 
+ When creating a flow definition using the API, attach these policies to the role that is passed to the `RoleArn` parameter of the `CreateFlowDefinition` operation. 

When you create a human review workflow (flow definition), Amazon A2I invokes Amazon S3 to complete your task. To grant Amazon A2I permission to retrieve and store your files in your Amazon S3 bucket, create the following policy and attach it to your role. For example, if the images, documents, and other files that you are sending for human review are stored in an S3 bucket named `my_input_bucket`, and if you want the human reviews to be stored in a bucket named `my_output_bucket`, create the following policy. 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws-cn:s3:::my_input_bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws-cn:s3:::my_output_bucket/*"
            ]
        }
    ]
}
```

------

In addition, the IAM role must have the following trust policy to give SageMaker AI permission to assume the role. To learn more about IAM trust policies, see [Resource-Based Policies](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies.html#policies_resource-based) section of **Policies and Permissions** in the *Amazon Identity and Access Management* documentation.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowSageMakerToAssumeRole",
      "Effect": "Allow",
      "Principal": {
        "Service": "sagemaker.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

For more information about creating and managing IAM roles and policies, see the following topics in the *Amazon Identity and Access Management User Guide*: 
+ To create an IAM role, see [Creating a Role to Delegate Permissions to an IAM User](https://docs.amazonaws.cn/IAM/latest/UserGuide/id_roles_create_for-user.html). 
+ To learn how to create IAM policies, see [Creating IAM Policies](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_create.html). 
+ To learn how to attach an IAM policy to a role, see [Adding and Removing IAM Identity Permissions](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_manage-attach-detach.html).

## Create a User That Can Invoke Amazon A2I API Operations


To use Amazon A2I to create and start human loops for Amazon Rekognition, Amazon Textract, or the Amazon A2I runtime API, you must use a user that has permissions to invoke Amazon A2I operations. To do this, use the IAM console to attach the [https://console.amazonaws.cn/iam/home?region=us-east-2#/policies/arn:aws:iam::aws:policy/AmazonAugmentedAIFullAccess$jsonEditor](https://console.amazonaws.cn/iam/home?region=us-east-2#/policies/arn:aws:iam::aws:policy/AmazonAugmentedAIFullAccess$jsonEditor) managed policy to a new or existing user. 

This policy grants permission to a user to invoke API operations from the SageMaker API for flow definition creation and management and the Amazon Augmented AI Runtime API for human loop creation and management. To learn more about these API operations, see [Use APIs in Amazon Augmented AI](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-api-references.html).

`AmazonAugmentedAIFullAccess` does not grant permissions to use Amazon Rekognition or Amazon Textract API operations. 

**Note**  
You can also attach the `AmazonAugmentedAIFullAccess` policy to an IAM role that is used to create and start a human loop. 

To provide access, add permissions to your users, groups, or roles:
+ Users managed in IAM through an identity provider:

  Create a role for identity federation. Follow the instructions in [Create a role for a third-party identity provider (federation)](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_create_for-idp.html) in the *IAM User Guide*.
+ IAM users:
  + Create a role that your user can assume. Follow the instructions in [Create a role for an IAM user](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_create_for-user.html) in the *IAM User Guide*.
  + (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in [Adding permissions to a user (console)](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) in the *IAM User Guide*.

For more information, see [Adding and Removing IAM Identity Permissions](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *Amazon Identity and Access Management User Guide*.

## Create a User With Permissions to Invoke Amazon A2I, Amazon Textract, and Amazon Rekognition API Operations


To create a user that has permission to invoke the API operations used by the built-in task types (that is, `DetectModerationLables` for Amazon Rekognition and `AnalyzeDocument` for Amazon Textract) and permission to use all Amazon A2I API operations, attach the IAM managed policy, `AmazonAugmentedAIIntegratedAPIAccess`. You may want to use this policy when you want to grant broad permissions to a user using Amazon A2I with more than one task type. To learn more about these API operations, see [Use APIs in Amazon Augmented AI](https://docs.amazonaws.cn/sagemaker/latest/dg/a2i-api-references.html).

**Note**  
You can also attach the `AmazonAugmentedAIIntegratedAPIAccess` policy to an IAM role that is used to create and start a human loop. 

To provide access, add permissions to your users, groups, or roles:
+ Users managed in IAM through an identity provider:

  Create a role for identity federation. Follow the instructions in [Create a role for a third-party identity provider (federation)](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_create_for-idp.html) in the *IAM User Guide*.
+ IAM users:
  + Create a role that your user can assume. Follow the instructions in [Create a role for an IAM user](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_create_for-user.html) in the *IAM User Guide*.
  + (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in [Adding permissions to a user (console)](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) in the *IAM User Guide*.

For more information, see [Adding and Removing IAM Identity Permissions](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *Amazon Identity and Access Management User Guide*.

## Enable Worker Task Template Previews


To customize the interface and instructions that your workers see when working on your tasks, you create a worker task template. You can create the template using the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html) operation or the SageMaker AI console. 

To preview your template, you need an IAM role with the following permissions to read Amazon S3 objects that get rendered on your user interface. 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws-cn:s3:::my_input_bucket/*"
            ]
        }
    ]
}
```

------

For Amazon Rekognition and Amazon Textract task types, you can preview your template using the Amazon Augmented AI section of the SageMaker AI console. For custom task types, you preview your template by invoking the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_RenderUiTemplate.html) operation. To preview your template, follow the instructions for your task type:
+  Amazon Rekognition and Amazon Textract task types – In the SageMaker AI console, use the role's Amazon Resource Name (ARN) in the procedure documented in [Create a Worker Task Template](a2i-worker-template-console.md#a2i-create-worker-template-console).
+ Custom task types – In the `RenderUiTemplate` operation, use the role's ARN in the `RoleArn` parameter.

## Using Amazon A2I with Amazon KMS Encrypted Buckets


If you specify an Amazon Key Management Service (Amazon KMS) customer managed key to encrypt output data in `OutputConfig` of [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html), you must add an IAM policy similar to the following to that key. This policy gives the IAM execution role that you use to create your human loops permission to use this key to perform all of the actions listed in `"Action"`. To learn more about these actions, see [Amazon KMS permissions](https://docs.amazonaws.cn/kms/latest/developerguide/kms-api-permissions-reference.html) in the Amazon Key Management Service Developer Guide.

To use this policy, replace the IAM service-role ARN in `"Principal"` with the ARN of the execution role you use to create the human review workflow (flow definition). When you create a labeling job using `CreateFlowDefinition`, this is the ARN you specify for [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateLabelingJob.html#sagemaker-CreateLabelingJob-request-RoleArn](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateLabelingJob.html#sagemaker-CreateLabelingJob-request-RoleArn). Note that you cannot provide a `KmsKeyId` when you create a flow definition in the console.

```
{
    "Sid": "AllowUseOfKmsKey",
    "Effect": "Allow",
    "Principal": {
        "AWS": "arn:aws:iam::111122223333:role/service-role/example-role"
    },
    "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:DescribeKey"
    ],
    "Resource": "*"
}
```

## Additional Permissions and Security Resources

+ [Control access to SageMaker AI resources by using tags](security_iam_id-based-policy-examples.md#access-tag-policy).
+ [Identity-based policies for Amazon SageMaker AI](security_iam_service-with-iam.md#security_iam_service-with-iam-id-based-policies)
+ [Control creation of SageMaker AI resources with condition keys](security_iam_id-based-policy-examples.md#sagemaker-condition-examples)
+ [Amazon SageMaker AI API Permissions: Actions, Permissions, and Resources Reference](api-permissions-reference.md)
+ [Configure security in Amazon SageMaker AI](security.md)

# Use Amazon CloudWatch Events in Amazon Augmented AI
CloudWatch Events

Amazon Augmented AI uses Amazon CloudWatch Events to alert you when a human review loop status changes to `Completed`, `Failed`, or `Stopped`. This event delivery is guaranteed at least once, which means all events created when human loops finish are successfully delivered to CloudWatch Events (Amazon EventBridge). When a review loop changes to one of these states, Augmented AI sends an event to CloudWatch Events similar to the following.

```
{
    "version":"0",
    "id":"12345678-1111-2222-3333-12345EXAMPLE",
    "detail-type":"SageMaker A2I HumanLoop Status Change",
    "source":"aws.sagemaker",
    "account":"1111111111111",
    "time":"2019-11-14T17:49:25Z",
    "region":"us-east-1",
    "resources":["arn:aws:sagemaker:us-east-1:111111111111:human-loop/humanloop-nov-14-1"],
    "detail":{
        "creationTime":"2019-11-14T17:37:36.740Z",
        "failureCode":null,
        "failureReason":null,
        "flowDefinitionArn":"arn:aws:sagemaker:us-east-1:111111111111:flow-definition/flowdef-nov-12",
        "humanLoopArn":"arn:aws:sagemaker:us-east-1:111111111111:human-loop/humanloop-nov-14-1",
        "humanLoopName":"humanloop-nov-14-1",
        "humanLoopOutput":{ 
            "outputS3Uri":"s3://customer-output-bucket-specified-in-flow-definition/flowdef-nov-12/2019/11/14/17/37/36/humanloop-nov-14-1/output.json"
        },
        "humanLoopStatus":"Completed"
    }
}
```

The details in the JSON output include the following:

`creationTime`  
The timestamp when Augmented AI created the human loop.

`failureCode`  
A failure code denoting a specific type of failure.

`failureReason`  
The reason why a human loop has failed. The failure reason is only returned when the human review loop status is `failed`.

`flowDefinitionArn`  
The Amazon Resource Name (ARN) of the flow definition, or *human review workflow*.

`humanLoopArn`  
The Amazon Resource Name (ARN) of the human loop.

`humanLoopName`  
The name of the human loop.

`humanLoopOutput`  
An object containing information about the output of the human loop.

`outputS3Uri`  
The location of the Amazon S3 object where Augmented AI stores your human loop output.

`humanLoopStatus`  
The status of the human loop.

## Send Events from Your Human Loop to CloudWatch Events


To configure a CloudWatch Events rule to get status updates, or *events*, for your Amazon A2I human loops, use the Amazon Command Line Interface (Amazon CLI) [https://docs.amazonaws.cn/cli/latest/reference/events/put-rule.html](https://docs.amazonaws.cn/cli/latest/reference/events/put-rule.html) command. When using the `put-rule` command, specify the following to receive human loop statuses: 
+ `\"source\":[\"aws.sagemaker\"]`
+ `\"detail-type\":[\"SageMaker A2I HumanLoop Status Change\"]`

To configure a CloudWatch Events rule to watch for all status changes, use the following command and replace the placeholder text. For example, replace `"A2IHumanLoopStatusChanges"` with a unique CloudWatch Events rule name and *`"arn:aws:iam::111122223333:role/MyRoleForThisRule"`* with the Amazon Resource Number (ARN) of an IAM role with an events.amazonaws.com trust policy attached. Replace *region* with the Amazon Region in which you want to create the rule. 

```
aws events put-rule --name "A2IHumanLoopStatusChanges" 
    --event-pattern "{\"source\":[\"aws.sagemaker\"],\"detail-type\":[\"SageMaker A2I HumanLoop Status Change\"]}" 
    --role-arn "arn:aws:iam::111122223333:role/MyRoleForThisRule" 
    --region "region"
```

To learn more about the `put-rule` request, see [Event Patterns in CloudWatch Events](https://docs.amazonaws.cn/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html) in the *Amazon CloudWatch Events User Guide*.

## Set Up a Target to Process Events


To process events, you need to set up a target. For example, if you want to receive an email when a human loop status changes, use a procedure in [Setting Up Amazon SNS Notifications](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/US_SetupSNS.html) in the *Amazon CloudWatch User Guide *to set up an Amazon SNS topic and subscribe your email to it. Once you have created a topic, you can use it to create a target. 

**To add a target to your CloudWatch Events rule**

1. Open the CloudWatch console: [https://console.amazonaws.cn/cloudwatch/home](https://console.amazonaws.cn/cloudwatch/home)

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

1. Choose the rule to which you want to add a target. 

1. Choose **Actions**, and then choose **Edit**.

1. Under **Targets**, choose **Add Target** and choose the Amazon service you want to act when a human loop status change event is detected. 

1. Configure your target. For instructions, see the topic for configuring a target in the [Amazon documentation for that service](https://docs.amazonaws.cn/index.html).

1. Choose **Configure details**.

1. For **Name**, enter a name and, optionally, provide details about the purpose of the rule in **Description**. 

1. Make sure that the check box next to **State** is selected so that your rule is listed as **Enabled**. 

1. Choose **Update rule**.

## Use Human Review Output


After you receive human review results, you can analyze the results and compare them to machine learning predictions. The JSON that is stored in the Amazon S3 bucket contains both the machine learning predictions and the human review results.

## More Information


[Events that Amazon SageMaker AI sends to Amazon EventBridge](automating-sagemaker-with-eventbridge.md)

# Use APIs in Amazon Augmented AI
API References

You can create a human review workflow or a worker task template programmatically. The APIs you use depend on whether you are creating a Amazon Rekognition, Amazon Textract, or custom task type. This topic provides links to API reference documentation for each task type and programming task.

The following APIs can be used with Augmented AI:

**Amazon Augmented AI**  
Use the Augmented AI API to start, stop, and delete human review loops. You can also list all human review loops and return information about human review loops in your account.  
Learn more about human review loop APIs in the [Amazon Augmented AI Runtime API Reference](https://docs.amazonaws.cn/augmented-ai/2019-11-07/APIReference/Welcome.html).

**Amazon Rekognition**  
Use the **HumanLoopConfig** parameter of the `[ DetectModerationLabels](https://docs.amazonaws.cn/rekognition/latest/dg/API_DetectModerationLabels.html)` API to initiate a human review workflow using Amazon Rekognition.

**Amazon SageMaker AI**  
Use the Amazon SageMaker API to create a `FlowDefinition`, also known as a *human review workflow*. You can also create a `HumanTaskUi` or *worker task template*.  
For more information, see the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateFlowDefinition.html) or the [https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html](https://docs.amazonaws.cn/sagemaker/latest/APIReference/API_CreateHumanTaskUi.html) API documentation.

**Amazon Textract**  
Use the **HumanLoopConfig** parameter of the [AnalyzeDocument](https://docs.amazonaws.cn/textract/latest/dg/API_AnalyzeDocument.html) API to initiate a human review workflow using Amazon Textract.

## Programmatic Tutorials


The following tutorials provide example code and step-by-step instructions for creating human review workflows and worker task templates programmatically.
+ [Tutorial: Get Started Using the Amazon A2I API](a2i-get-started-api.md)
+ [Create a Human Review Workflow (API)](a2i-create-flow-definition.md#a2i-create-human-review-api)
+ [Create and Start a Human Loop](a2i-start-human-loop.md)
+ [Using Amazon Augmented AI with Amazon Rekognition](https://docs.amazonaws.cn/rekognition/latest/dg/a2i-rekognition.html) in the *Amazon Rekognition Developer Guide*
+ [Using Amazon Augmented AI with Amazon Textract AnalyzeDocument](https://docs.amazonaws.cn/textract/latest/dg/a2i-textract.html) in the *Amazon Textract Developer Guide*