AWS Builder Center
Day 11: Make Your AI Workflow Wait for Human Approval

Day 11: Make Your AI Workflow Wait for Human Approval

Add a human approval checkpoint to an AI-generated recommendation using AWS Step Functions, Amazon SQS, and Python.

Series: 30 Days of AI Engineering on AWS (17 articles)

  1. …
  2. 12
    Day 11: Make Your AI Workflow Wait for Human Approval This article
AWS SBG Tech Lead ’25 • Founding Member of Keralam’s First AWS SBG • AWS Certified
Day 10’s application brought together three specialist AI analyses and produced a consolidated briefing.
But its final status was only:
READY_FOR_HUMAN_REVIEW
That describes an intention. It does not actually implement human review.
Who approves the recommendation? What happens when someone rejects it? What happens when nobody responds?
Today, we will turn that missing step into a working application pattern.
The AI produces the recommendation. A separately authorized reviewer decides whether the workflow may proceed.
We will use the AWS Step Functions callback pattern to pause execution until a reviewer submits a decision. AWS documents this pattern for human approvals and other tasks that require an external response.

1. What are we building?

Our application will accept an incident briefing, prepare a review request, and wait for a human decision.
For this exercise, the proposed action is deliberately limited to:
CREATE_REVIEW_TICKET — DRY RUN
An approval reaches an  APPROVED_DRY_RUN  state.
It does not create a real ticket, modify IAM permissions, delete data, or change infrastructure.
This lets us test the approval mechanism without introducing a potentially destructive operation.
The architecture looks like this:
Day 10 AI-generated briefing
|
v
Step Functions Standard
|
v
Prepare review request
|
v
Send request to SQS
with a task token
|
v
WORKFLOW PAUSES
|
v
Authorized human reviewer
reads the request
|
v
APPROVE or REJECT
|
v
SendTaskSuccess
|
v
Validate the callback
|
+-----+------+
| |
v v
APPROVE REJECT
| |
v v
Approved Rejected
dry run outcome

No response before deadline → ApprovalExpired
Step Functions supports sending an SQS message and waiting for a callback through:
arn:aws:states:::sqs:sendMessage.waitForTaskToken
This callback integration requires a Standard workflow, not an Express workflow.
The approval stage does not need a Lambda function waiting in a loop. Step Functions holds the workflow state while the reviewer is away.

2. Approval is different from prompting and content filtering

We have already explored system prompts, Guardrails, and agent orchestration in earlier days.
Today’s control solves a different problem.
A system prompt might say:
Do not proceed without human approval.
Our design goes further: the application cannot reach its approved branch without a valid callback and the expected decision.
The approval authority is outside the model.
For this lab, we will separate these responsibilities:
Component
Allowed responsibility
Existing AI application
Generate the briefing
Step Functions execution role
Send the review request to its queue
Human reviewer role
Read requests and submit decisions
Approved branch
Return a dry-run result
The model does not receive the callback token or the reviewer’s permissions.
This separation is a design decision—not something that happens automatically because an application uses an AI agent.

3. Understand the callback token

When Step Functions enters a callback task, it provides a task token through its Context object.
In a JSONPath workflow, the reference is:
$$.Task.Token
Our workflow places that token in the SQS message. The reviewer application returns it to Step Functions with the review result.
The callback principal must belong to the same AWS account as the workflow.
Treat the token as a secret.
Do not place it in model prompts, public links, screenshots, or application logs.
There is also an important IAM detail:
states:SendTaskSuccess
does not support resource-level permissions.
Its IAM statement requires:
{
"Resource": "*"
}
rather than a specific state-machine ARN.
Restrict who receives that permission and who can obtain task tokens.
The template below additionally restricts the callback permission to the deployment Region. That is useful, but it is not workflow-level resource isolation.
References:

4. Prepare your environment

This exercise uses Python 3.10 or later, Boto3, AWS CLI, and the Mumbai Region:
ap-south-1
Use a fresh terminal configured for real AWS, not the emulator endpoint settings from Day 6.
The commands below assume two existing AWS CLI profiles:
lab-deployer
ai-reviewer
Replace these names with your configured profiles.
The deployer needs permission to create the CloudFormation, IAM, SQS, and Step Functions resources, pass the workflow execution role, and start and inspect test executions.
The reviewer should authenticate to a separate trusted role in the same account.
An administrator must configure that role and its trust relationship. Our template creates its permissions policy, not a human login.
Create a project directory:
mkdir day11-human-approval
cd day11-human-approval

py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1

python -m pip install --upgrade boto3
Verify the deployment identity:
aws sts get-caller-identity --profile lab-deployer
This approval lab uses AWS credentials for SQS and Step Functions. It does not make a new Amazon Bedrock inference request.
You can test it with a saved Day 10 briefing or the synthetic input provided below.

5. Define the infrastructure and approval workflow

Create a file named:
template.yaml
The template creates an encrypted SQS queue, a Standard workflow, a restricted workflow execution role, and an unattached reviewer policy.
CloudFormation supports defining the state machine directly in YAML. The queue uses SQS-managed server-side encryption.
AWSTemplateFormatVersion: '2010-09-09'
Description: Day 11 - Human approval for an AI-generated briefing (dry run).

Resources:
ApprovalQueue:
Type: AWS::SQS::Queue
Properties:
SqsManagedSseEnabled: true
MessageRetentionPeriod: 3600
VisibilityTimeout: 300
ReceiveMessageWaitTimeSeconds: 10

QueuePolicy:
Type: AWS::SQS::QueuePolicy
Properties:
Queues: [!Ref ApprovalQueue]
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Deny
Principal: '*'
Action: 'sqs:*'
Resource: !GetAtt ApprovalQueue.Arn
Condition:
Bool:
aws:SecureTransport: 'false'

WorkflowRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: states.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
ArnEquals:
aws:SourceArn: !Sub arn:${AWS::Partition}:states:${AWS::Region}:${AWS::AccountId}:stateMachine:${AWS::StackName}-workflow
Policies:
- PolicyName: SendApprovalRequest
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: sqs:SendMessage
Resource: !GetAtt ApprovalQueue.Arn

ApprovalWorkflow:
Type: AWS::StepFunctions::StateMachine
Properties:
StateMachineName: !Sub ${AWS::StackName}-workflow
StateMachineType: STANDARD
RoleArn: !GetAtt WorkflowRole.Arn
Definition:
QueryLanguage: JSONPath
StartAt: ValidateInput
States:
ValidateInput:
Type: Choice
Choices:
- And:
- Variable: $.briefing
IsPresent: true
- Variable: $.briefing
IsString: true
- Not:
Variable: $.briefing
StringEquals: ''
Next: PrepareRequest
Default: InvalidInput

PrepareRequest:
Type: Pass
Parameters:
request:
execution_arn.$: $$.Execution.Id
briefing.$: $.briefing
action:
type: CREATE_REVIEW_TICKET
dry_run: true
Next: WaitForApproval

WaitForApproval:
Type: Task
Resource: !Sub arn:${AWS::Partition}:states:::sqs:sendMessage.waitForTaskToken
Parameters:
QueueUrl: !Ref ApprovalQueue
MessageBody:
task_token.$: $$.Task.Token
request.$: $.request
TimeoutSeconds: 900
ResultPath: $.approval
Catch:
- ErrorEquals: [States.Timeout]
ResultPath: $.failure
Next: ApprovalExpired
- ErrorEquals: [States.ALL]
ResultPath: $.failure
Next: ApprovalFailed
Next: ValidateCallback

ValidateCallback:
Type: Choice
Choices:
- And:
- Variable: $.approval.execution_arn
IsPresent: true
- Variable: $.approval.execution_arn
IsString: true
- Variable: $.approval.execution_arn
StringEqualsPath: $.request.execution_arn
- Variable: $.approval.decision
IsPresent: true
- Variable: $.approval.decision
IsString: true
Next: RouteDecision
Default: InvalidApproval

RouteDecision:
Type: Choice
Choices:
- Variable: $.approval.decision
StringEquals: APPROVE
Next: ApprovedDryRun
- Variable: $.approval.decision
StringEquals: REJECT
Next: Rejected
Default: InvalidApproval

ApprovedDryRun:
Type: Pass
Parameters:
status: APPROVED_DRY_RUN
request.$: $.request
approval.$: $.approval
note: No ticket was created and no infrastructure was changed.
End: true

Rejected:
Type: Pass
Parameters:
status: REJECTED
request.$: $.request
approval.$: $.approval
End: true

InvalidInput:
Type: Fail
Error: InvalidInput
Cause: A non-empty briefing string is required.

InvalidApproval:
Type: Fail
Error: InvalidApproval
Cause: Missing, mismatched, or unsupported approval response.

ApprovalExpired:
Type: Fail
Error: ApprovalExpired
Cause: No valid callback arrived before the approval deadline.

ApprovalFailed:
Type: Fail
Error: ApprovalFailed
Cause: The approval task failed. No action was authorized.

ReviewerPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Description: Attach only to the trusted human reviewer role, not the AI runtime.
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- sqs:ReceiveMessage
- sqs:DeleteMessage
Resource: !GetAtt ApprovalQueue.Arn
- Effect: Allow
Action: states:SendTaskSuccess
Resource: '*'
Condition:
StringEquals:
aws:RequestedRegion: !Ref AWS::Region

Outputs:
QueueUrl:
Value: !Ref ApprovalQueue
StateMachineArn:
Value: !Ref ApprovalWorkflow
ReviewerPolicyArn:
Value: !Ref ReviewerPolicy

Understand the important controls

The workflow constructs the proposed action.
 PrepareRequest  copies the briefing but creates the action itself.
It does not trust a model-generated  "approved": true  field or accept an arbitrary operation supplied in the input.
The approval cannot replace the original request.
The callback is stored under:
$.approval
The proposed action remains under:
$.request
The response must match this execution.
 ValidateCallback  checks the execution ARN before evaluating the decision.
This provides an additional correlation check. The task token remains the mechanism that identifies the waiting task.
Only an explicit decision is accepted.
 APPROVE  and  REJECT  are handled separately. An unknown value does not default to approval.
These checks use documented Choice-state comparisons, including  IsPresent ,  IsString , and  StringEqualsPath .
No response means no approval.
The callback task has a 900-second deadline. A timeout transitions to  ApprovalExpired , not to the approved branch.
The execution-role trust policy also limits role assumption to this account and state machine using  aws:SourceAccount  and  aws:SourceArn .
References:

6. Deploy the lab

In PowerShell:
$region = "ap-south-1"
$stack = "day11-approval"

aws cloudformation validate-template `
--template-body file://template.yaml `
--region $region `
--profile lab-deployer

aws cloudformation deploy `
--template-file template.yaml `
--stack-name $stack `
--capabilities CAPABILITY_IAM `
--region $region `
--profile lab-deployer
The deployment command creates and executes a CloudFormation change set.
Review the template before running it.
 CAPABILITY_IAM  acknowledges that the stack creates IAM resources.
Retrieve the stack outputs:
$outputs = aws cloudformation describe-stacks `
--stack-name $stack `
--region $region `
--profile lab-deployer `
--query "Stacks[0].Outputs" `
--output json | ConvertFrom-Json

$queueUrl = (
$outputs | Where-Object OutputKey -eq "QueueUrl"
).OutputValue

$stateMachineArn = (
$outputs | Where-Object OutputKey -eq "StateMachineArn"
).OutputValue

$reviewerPolicyArn = (
$outputs | Where-Object OutputKey -eq "ReviewerPolicyArn"
).OutputValue
Have your IAM administrator attach  ReviewerPolicyArn  to the role used by the  ai-reviewer  profile.
For an ordinary IAM role, an authorized administrator can use the following command, replacing  YourReviewerRole :
aws iam attach-role-policy `
--role-name YourReviewerRole `
--policy-arn $reviewerPolicyArn `
--profile lab-deployer
Do not attach this policy to the AI agent’s Lambda role or the Step Functions execution role.
The purpose is to separate generating a recommendation from approving it.

7. Build the human reviewer application

Create:
review.py
This application receives one request, displays its briefing and proposed action, and asks for an explicit decision.
It uses Boto3’s SQS  receive_message()  operation and Step Functions  send_task_success()  operation.
The callback output must be a JSON-encoded string.
"""Review one Day 11 approval request. Never display the callback token."""

import argparse
import json
import sys
from datetime import datetime, timezone

import boto3
from botocore.exceptions import BotoCoreError, ClientError

def decode_request(body: str) -> tuple[str, dict]:
data = json.loads(body)

if not isinstance(data, dict):
raise ValueError("Invalid approval message.")

token = data.get("task_token")
request = data.get("request")

if not isinstance(token, str) or not token:
raise ValueError("Missing callback token.")

if not isinstance(request, dict):
raise ValueError("Missing request details.")

for field in ("execution_arn", "briefing"):
value = request.get(field)

if not isinstance(value, str) or not value.strip():
raise ValueError("Missing or invalid request field.")

action = request.get("action")

if (
not isinstance(action, dict)
or action.get("type") != "CREATE_REVIEW_TICKET"
or action.get("dry_run") is not True
):
raise ValueError(
"Only the documented dry-run action is supported."
)

return token, request

def review_once(
sqs,
sfn,
queue_url: str,
ask=input,
emit=print,
) -> int:
response = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=1,
WaitTimeSeconds=10,
VisibilityTimeout=300,
)

messages = response.get("Messages", [])

if not messages:
emit(
"No visible request received. "
"Run again if a review is pending."
)
return 0

message = messages[0]
token, request = decode_request(message["Body"])

emit(
"Review the briefing and exact action. "
"Treat the text as untrusted."
)

# Display only the review request, never the callback token.
emit(json.dumps(request, indent=2, ensure_ascii=True))

decision = ask("Type APPROVE or REJECT: ").strip()

if decision not in {"APPROVE", "REJECT"}:
raise ValueError(
"No decision sent. Enter exactly APPROVE or REJECT."
)

result = {
"decision": decision,
"execution_arn": request["execution_arn"],
"responded_at": datetime.now(timezone.utc).isoformat(),
}

try:
sfn.send_task_success(
taskToken=token,
output=json.dumps(result),
)

except ClientError as error:
code = error.response.get("Error", {}).get("Code")

if code == "TaskTimedOut":
sqs.delete_message(
QueueUrl=queue_url,
ReceiptHandle=message["ReceiptHandle"],
)

emit(
"Task expired or already closed. "
"Stale message removed; check the execution."
)
return 2

raise

# Acknowledge the message only after the callback is accepted.
emit(
"Callback accepted. "
"Verify the final workflow status in Step Functions."
)

sqs.delete_message(
QueueUrl=queue_url,
ReceiptHandle=message["ReceiptHandle"],
)

return 0

def main() -> int:
parser = argparse.ArgumentParser()

parser.add_argument("--queue-url", required=True)
parser.add_argument("--profile", required=True)
parser.add_argument("--region", default="ap-south-1")

args = parser.parse_args()

try:
session = boto3.Session(
profile_name=args.profile,
region_name=args.region,
)

return review_once(
session.client("sqs"),
session.client("stepfunctions"),
args.queue_url,
)

except ClientError as error:
# Avoid echoing response bodies, message contents, or tokens.
code = error.response.get("Error", {}).get(
"Code", "Unknown"
)

print(
f"AWS request failed ({code}). "
"Check execution status before retrying.",
file=sys.stderr,
)
return 1

except (BotoCoreError, ValueError, KeyError, EOFError):
print(
"Configuration, message, or input error. "
"No approval was confirmed.",
file=sys.stderr,
)
return 1

except KeyboardInterrupt:
print(
"Review interrupted. No approval was confirmed.",
file=sys.stderr,
)
return 1

if __name__ == "__main__":
raise SystemExit(main())

Why does rejection also use  SendTaskSuccess ?

Because completing the review and approving the proposal are different things.
The callback API reports that the review task completed.
The result contains the business decision:
{
"decision": "REJECT"
}
Our Choice state reads that decision and routes to  Rejected .
Therefore, an execution can finish successfully while its business outcome is  REJECTED .
Do not interpret Step Functions’ execution status alone as approval.

Why delete the message after sending the callback?

The application first submits the decision, then acknowledges the queue message.
If the callback fails because of a permission or service error, the script leaves the message available for later recovery.
If AWS returns  TaskTimedOut , the token may have expired or the task may already have closed.
The script removes the stale message but does not claim that an approval occurred.
References:

8. Start an approval request

Create  request.json :
{
"briefing": "SIMULATED INCIDENT: The analysis recommends opening a human-reviewed investigation ticket for increased HTTP 5xx responses. Root cause is not confirmed. No infrastructure changes are requested."
}
This is a synthetic fixture, not a real incident analysis.
Start an execution:
$executionArn = aws stepfunctions start-execution `
--state-machine-arn $stateMachineArn `
--name ("day11-" + [guid]::NewGuid().ToString()) `
--input file://request.json `
--region $region `
--profile lab-deployer `
--query executionArn `
--output text
Open the execution in Step Functions.
The intended progression is:
ValidateInput
|
v
PrepareRequest
|
v
WaitForApproval
The workflow should remain at  WaitForApproval  until a callback arrives or the deadline expires.
Now run the reviewer:
python review.py `
--queue-url "$queueUrl" `
--profile ai-reviewer `
--region $region
Read the displayed request and enter exactly:
APPROVE
Inspect the execution:
aws stepfunctions describe-execution `
--execution-arn $executionArn `
--region $region `
--profile lab-deployer `
--query "{status:status,output:output,error:error,cause:cause}"
For an accepted approval, the workflow output should include:
{
"status": "APPROVED_DRY_RUN",
"note": "No ticket was created and no infrastructure was changed."
}
The full output also contains the original review request and callback result.

9. Test more than the approval path

An approval feature is not complete just because one approval succeeds.
Use a new execution for each test.
Test
Expected outcome in this lab
Enter  APPROVE 
Output contains  APPROVED_DRY_RUN 
Enter  REJECT 
Output contains  REJECTED ; no approved branch runs
Enter an unsupported response
Reviewer sends no callback
Submit no decision
Workflow reaches  ApprovalExpired 
Start with a missing or invalid briefing
Workflow reaches  InvalidInput 
Supply an invalid or mismatched callback
Workflow must not enter the approved branch
To test expiration quickly, change this field in the template:
TimeoutSeconds: 900
to:
TimeoutSeconds: 30
Redeploy and start a new execution. Do not submit a decision.
Restore the longer timeout afterward.

Understand the two different timers

The approval deadline starts when Step Functions begins the waiting task.
The SQS visibility timeout starts when a consumer receives the message. It temporarily hides the message from other consumers; it is not the approval deadline.
Our script requests a 300-second visibility timeout. It does not renew that period, so use it for a short, single-reviewer exercise.
A production review application needs a deliberate approach to longer reviews and concurrent reviewers.
SQS Standard queues can also deliver duplicates, including during the visibility period.

10. Connect this to the actual Day 10 output

Day 10’s final output already includes a field named:
briefing
You can save that output as  request.json  and pass it to this workflow.
The approval workflow reads the  briefing  field and constructs its own review request.
Extra fields, including any input field that claims approval, are not carried forward by  PrepareRequest .
This gives us a useful separation:
AI analysis
|
v
Generated briefing
|
v
Application-defined review request
|
v
Human decision
|
v
Controlled continuation
For today, keep the analysis workflow and approval workflow separate.
That makes it easier to test the human-review mechanism without repeatedly invoking the model.
A future integration can start the approval workflow after the analysis completes.
The important requirement is that the AI runtime must not also receive the reviewer’s callback authority.

11. What needs to change before production?

Make reviewer authorization specific

This lab uses a trusted-reviewer queue.
Any principal with the reviewer permissions and access to a request can review that request.
It does not implement assignment to a particular employee, tenant, team, or approval level.
For production, place an authenticated approval service between the user interface and Step Functions. That service should check whether the signed-in user is allowed to approve the specific request before submitting the callback.
Do not trust a client-provided field such as:
{
"reviewer": "administrator"
}
as proof of identity or authority.

Approve an exact action, not a vague intention

Our action is a fixed dry-run operation, and the workflow retains the original request.
For a real action, present the exact operation and parameters to the reviewer: target resource, environment, scope, expected effect, and relevant limits.
The downstream executor should use that reviewed snapshot.
It should not ask the model to generate a different action after approval.
When approval refers to external stored data, bind the decision to a version or content hash so a later edit cannot silently change what was approved.

Design the real executor for duplicate requests

SQS Standard delivery is at least once, so duplicate messages are possible. AWS recommends idempotent consumers.
Before replacing the dry-run state with a real action, give that action a stable request identifier and design it so a retry cannot create duplicate tickets, send duplicate payments, or repeat a configuration change.
A callback token is useful for completing a workflow task. It is not a complete business-level idempotency system.

Keep an audit record without leaking tokens

Standard workflows record execution history in Step Functions.
CloudWatch logging is optional and is not enabled by default for an API- or CloudFormation-created workflow.
AWS also lists  SendTaskSuccess  as a CloudTrail management event.
Use authenticated caller records and an application audit trail to establish who submitted a decision—not merely a reviewer name inside callback JSON.
For a production review service, record the request identifier, reviewed action version, authenticated reviewer, decision, reason, and timestamps.
Do not copy callback tokens into that business audit record.
References:

Protect sensitive briefings and control payload size

Our example sends the briefing through the workflow and queue.
Use synthetic or appropriately sanitized information while learning.
Step Functions’ service integration input and result limit is 256 KiB. Keep large reports outside the workflow payload and pass protected references when necessary.
If a reviewer accesses a report through an external reference, make sure the referenced version cannot change unnoticed between review and execution.

Understand costs

Standard Step Functions pricing is based on state transitions, rather than charging for the elapsed time spent waiting for a person.
SQS API requests can also incur charges.
This lab does not keep Lambda running while waiting and does not add a model invocation of its own.
That does not make the entire application free. Earlier model calls, workflow transitions, queue operations, and any additional logging still need to be considered.

12. Clean up the lab

First, stop any remaining test executions.
Because the reviewer policy was attached to a role outside the stack, detach it before deleting the stack:
aws iam detach-role-policy `
--role-name YourReviewerRole `
--policy-arn $reviewerPolicyArn `
--profile lab-deployer
Then remove the dedicated lab resources:
aws cloudformation delete-stack `
--stack-name $stack `
--region $region `
--profile lab-deployer

aws cloudformation wait stack-delete-complete `
--stack-name $stack `
--region $region `
--profile lab-deployer
This cleanup targets the Day 11 stack, including remaining queued requests.
It does not delete your Day 10 project or the existing reviewer role.

Your Day 11 challenge

Demonstrate three separate executions:
  1. One approved.
  1. One rejected.
  1. One expired.
For each execution, record the path taken and its final business outcome.
Do not include task tokens in screenshots.
Then replace the synthetic briefing with a saved output from your Day 10 application and review it through the same process.

Day 11 complete

Today, we added a human approval checkpoint to an AI workflow using AWS Step Functions, Amazon SQS, and Python.
The workflow can pause for a decision, distinguish approval from rejection, and stop when the review deadline expires.
More importantly, the AI runtime does not receive the authority to approve its own recommendation.
The key lesson is straightforward:
An AI system can recommend an action without being authorized to approve that action.
Today, we made that distinction part of the workflow rather than leaving it inside a prompt.
30 Days. 30 Tasks. Real AI Building.

Series: 30 Days of AI Engineering on AWS (17 articles)

  1. …
  2. 12
    Day 11: Make Your AI Workflow Wait for Human Approval This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article