
Day 8 - Deploy Your First Strands AI Agent on AWS Lambda
Take a Python AI agent built with the Strands Agents SDK and deploy it to AWS Lambda. Connect it to Amazon Bedrock, add a custom tool, configure IAM permissions, and invoke your serverless agent using the AWS CLI.
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 9Day 8 - Deploy Your First Strands AI Agent on AWS Lambda This article
In the previous articles, we explored several parts of the AI engineering workflow:
- Day 5: Building a RAG application with Amazon Bedrock.
- Day 6: Testing AWS applications locally with AWS Emulator.
- Day 7: Adding safety and grounding checks with Amazon Bedrock Guardrails.
Now let's move from building an agent locally to deploying one on AWS.
An AI agent needs more than a model invocation. It may need to execute tools, process requests, interact with AWS services, and return results to an application.
But running a dedicated server for every small AI workload is not always necessary.
AWS Lambda provides an event-driven execution environment for running AI agents without managing servers.
For this exercise, we'll deploy a Python agent using the Strands Agents SDK, connect it to Amazon Nova Lite through Amazon Bedrock, and give it a custom calculation tool.
By the end, you'll be able to invoke your agent through AWS Lambda.
1. Understand the architecture
Our application will use four main components:
Component | Responsibility |
|---|---|
AWS Lambda | Executes the Python agent |
Strands Agents SDK | Manages the agent loop and tool execution |
Amazon Bedrock | Provides the foundation model |
Custom Python tool | Performs deterministic percentage calculations |
The architecture:
User Request | v AWS Lambda | v Strands Agents SDK | v Amazon Bedrock (Amazon Nova Lite) | v Agent Decision | +-----+-----+ | | Answer Call Tool | | | v | Python Calculator | | | v | Tool Result | | +-----+-----+ | v Final Response | v User OutputThe important distinction is that Lambda does not implement the agent reasoning itself. It provides the execution environment, while Strands manages the agent loop and tool interactions.
2. Prerequisites
Before starting, make sure you have:
- An AWS account.
- AWS CLI configured with credentials.
- Access to Amazon Bedrock and the selected foundation model.
- Basic Python knowledge.
- Familiarity with AWS Lambda and IAM.
We'll use the Mumbai Region:
ap-south-1For the model, we'll use the APAC inference profile for Amazon Nova Lite:
apac.amazon.nova-lite-v1:0This is the same model profile used in the earlier RAG exercise.
Important regional consideration: This is an APAC cross-Region inference profile, not a Mumbai-only inference configuration. Requests originating in Mumbai can be routed to other supported APAC Regions. Review the model's current destination Regions before using it with data residency requirements.
You can inspect the profile using:
aws bedrock get-inference-profile ` --inference-profile-identifier apac.amazon.nova-lite-v1:0 ` --region ap-south-1The response includes the inference profile ARN and the model ARNs associated with it.
3. Create the Python agent
First, create a project directory:
mkdir strands-lambda-agentcd strands-lambda-agentCreate a file named:
agent_handler.pyOur agent will be a simple AWS learning assistant with one custom tool.
Rather than asking the model to perform every calculation itself, we will provide a Python function that performs percentage calculations using the
Decimal type.This demonstrates an important agent engineering principle:
Use the model for reasoning and deterministic tools for operations that require exact results.
Add a custom tool
The Strands
@tool decorator turns a regular Python function into a tool that the agent can decide to invoke.from decimal import Decimal, InvalidOperationfrom strands import tool
@tooldef calculate_percentage( amount: str, percentage: str) -> str: """ Calculate a percentage of a numeric amount.
Args: amount: The original numeric amount. percentage: The percentage to calculate. """
try: base = Decimal(amount) rate = Decimal(percentage)
except (InvalidOperation, ValueError, TypeError): return "Invalid input. Please provide valid numeric values."
if not base.is_finite() or not rate.is_finite(): return "Input must contain finite numeric values."
result = base * rate / Decimal("100")
return ( f"{rate}% of {base} is " f"{result.normalize():f}" )The tool accepts two arguments:
-
amount: The original value.
-
percentage: The percentage to calculate.
For example:
amount = 1250percentage = 18
Result = 225The calculation is performed by Python, not estimated by the language model.
4. Connect Strands to Amazon Bedrock
Now let's configure the Bedrock model.
Add the following code to
agent_handler.py :import os
from strands import Agentfrom strands.models import BedrockModel
REGION = os.getenv("AWS_REGION", "ap-south-1")
MODEL_ID = os.getenv( "BEDROCK_MODEL_ID", "apac.amazon.nova-lite-v1:0")
bedrock_model = BedrockModel( model_id=MODEL_ID, region_name=REGION, temperature=0.2, max_tokens=800)A few important configuration details:
model_id Specifies the Amazon Bedrock model or inference profile that the agent will use.
region_name Specifies the Region used by the Bedrock Runtime client.
We explicitly pass the Region instead of relying on implicit configuration. Strands documents that an AWS profile's configured Region can take precedence over
AWS_REGION .temperature Controls the randomness of generated responses. We use a relatively low value for this practical assistant.
max_tokens Sets an explicit output token limit.
The Bedrock model provider handles communication with Amazon Bedrock. Lambda obtains AWS credentials through its execution role, so you do not need to place access keys inside the Python file.
5. Build the Lambda handler
Now we need to connect the agent to the Lambda execution lifecycle.
Lambda invokes a Python handler using two arguments:
def lambda_handler(event, context): ...The
event contains the incoming request, while context provides invocation metadata.Add the following complete handler to
agent_handler.py .import jsonimport logging
from strands import Agent
logger = logging.getLogger()logger.setLevel(logging.INFO)
SYSTEM_PROMPT = """You are an AWS learning assistant.
Explain AWS concepts clearly and accurately.
You have access to a calculate_percentage tool.
Whenever a user asks you to calculate a percentageof an amount, you must use this tool.
Do not estimate percentage calculations mentally.
Use the tool result in your final response.
If you are unsure about a technical fact,state that uncertainty rather than inventing an answer."""
def create_agent(): """ Create a new agent for each invocation.
The model configuration is reused, but conversation history is not shared between Lambda requests. """
return Agent( model=bedrock_model, tools=[calculate_percentage], system_prompt=SYSTEM_PROMPT, name="serverless-aws-learning-agent" )
def response(status_code: int, data: dict) -> dict:
return { "statusCode": status_code, "headers": { "Content-Type": "application/json" }, "body": json.dumps(data) }
def lambda_handler(event, context):
try:
if not isinstance(event, dict): raise ValueError("Invalid request format.")
payload = event
# Support direct Lambda invocation and # JSON requests through a Lambda Function URL. if event.get("body") is not None:
payload = event["body"]
if isinstance(payload, str): payload = json.loads(payload)
if not isinstance(payload, dict): raise ValueError("Request body must be a JSON object.")
prompt = payload.get("prompt")
if not isinstance(prompt, str) or not prompt.strip(): raise ValueError("A non-empty prompt is required.")
agent = create_agent()
result = agent(prompt.strip())
return response( 200, { "answer": str(result) } )
except (ValueError, json.JSONDecodeError) as error:
return response( 400, { "error": str(error) } )
except Exception:
logger.exception( "Agent invocation failed. Request ID: %s", getattr(context, "aws_request_id", "unknown") )
return response( 500, { "error": "Agent invocation failed." } )Why create a new Agent for every invocation?
Lambda can reuse an execution environment between invocations.
If we store a mutable agent with conversation history at module level, different requests might unintentionally share that state.
Here, we reuse the Bedrock model configuration but create a fresh Agent for each invocation.
This keeps the example stateless between requests. If you need conversation persistence, implement it explicitly using a suitable storage mechanism and a user-scoped session ID.
6. Prepare the Lambda deployment
One of the challenges with deploying Python AI applications is dependency packaging.
The Strands SDK has its own dependencies. Installing everything manually into a deployment archive can make packaging more complicated.
Fortunately, Strands provides an official AWS Lambda layer.
According to the current Strands deployment documentation, the layer is published in
ap-south-1 and supports Python 3.12 and the x86_64 architecture.For this exercise, use:
Runtime: Python 3.12
Architecture: x86_64
Layer ARN:
arn:aws:lambda:ap-south-1:856699698935:layer:strands-agents-py3_12-x86_64:2The documented mapping for layer version 2 is:
strands-agents v1.40.0You can independently inspect the layer metadata:
aws lambda get-layer-version ` --layer-name arn:aws:lambda:ap-south-1:856699698935:layer:strands-agents-py3_12-x86_64 ` --version-number 2 ` --region ap-south-1Layer versions can change over time, so verify the currently published version before deployment.
7. Create the Lambda function
Follow these steps:
- Choose Create function.
- Select Author from scratch.
- Enter the function name:
strands-serverless-agent
- Select Python 3.12.
- Select x86_64 architecture.
- Create or select an execution role with basic Lambda logging permissions.
- Create the function.
Configure the deployment layer
Open the function's Layers section.
Choose Add a layer, then select Specify an ARN.
Paste the Strands layer ARN from Step 6 and add it.
The Lambda layer makes the Strands SDK available to your function without placing it in your application's own deployment archive.
Upload the Python code
Open the Lambda Code editor.
Create a file named:
agent_handler.pyPaste the complete code from Step 5.
Make sure the Lambda handler configuration is:
agent_handler.lambda_handlerThis tells Lambda to load
agent_handler.py and execute the lambda_handler function.8. Give Lambda permission to invoke Amazon Bedrock
The next step is IAM.
Your Lambda execution role needs permission to invoke the selected Bedrock model.
For this example, the application uses the APAC Nova Lite inference profile.
Because this profile can route inference to multiple destination Regions, the IAM permissions must cover the inference profile and the foundation model resources in its destination Regions.
An appropriately scoped starting policy is:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "InvokeNovaLiteThroughApacProfile", "Effect": "Allow", "Action": [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ], "Resource": [ "arn:aws:bedrock:ap-south-1:*:inference-profile/apac.amazon.nova-lite-v1:0", "arn:aws:bedrock:ap-northeast-1::foundation-model/amazon.nova-lite-v1:0", "arn:aws:bedrock:ap-northeast-2::foundation-model/amazon.nova-lite-v1:0", "arn:aws:bedrock:ap-northeast-3::foundation-model/amazon.nova-lite-v1:0", "arn:aws:bedrock:ap-south-1::foundation-model/amazon.nova-lite-v1:0", "arn:aws:bedrock:ap-southeast-1::foundation-model/amazon.nova-lite-v1:0", "arn:aws:bedrock:ap-southeast-2::foundation-model/amazon.nova-lite-v1:0" ] } ]}Attach this as an inline policy to the Lambda execution role.
Important: Verify the inference profile ARN and its model ARNs using the
get-inference-profile command from Step 2. Use the exact profile ARN and destination model ARNs returned for your source Region when preparing a production IAM policy. The resource list above reflects the documented APAC Nova Lite routing for the Mumbai source Region.Also make sure your account has access to invoke the selected model.
The key permissions are:
-
bedrock:InvokeModel
-
bedrock:InvokeModelWithResponseStream
The second permission is included because Strands supports streaming inference through Bedrock.
For production, avoid giving the Lambda role broad Bedrock access when it only needs one model profile.
9. Configure Lambda memory and timeout
An AI agent can take longer to execute than a basic Lambda function because it may need to:
- Initialize the agent.
- Call the foundation model.
- Process a model-selected tool invocation.
- Receive the tool result.
- Call the model again to produce the final answer.
The default Lambda timeout is only three seconds, which is often too short for this kind of workload.
For this experiment, start with:
Setting | Value |
|---|---|
Memory | 1,024 MB |
Timeout | 120 seconds |
Runtime | Python 3.12 |
Architecture | x86_64 |
These are starting values, not universal performance requirements.
Monitor execution duration, memory usage, cold starts, and model latency in CloudWatch. Adjust the configuration based on actual workload measurements.
AWS Lambda supports a maximum execution timeout of 900 seconds (15 minutes).
10. Test the deployed agent
Now let's invoke the function.
Open the Lambda console's Test tab and create this test event:
{ "prompt": "Use the calculate_percentage tool to calculate 18 percent of 1250. Explain the result."}Run the test.
The expected calculation is:
18% of 1250 = 225The agent should use the custom Python tool and incorporate its returned result into the final response.
You can also invoke the Lambda function through AWS CLI.
Windows PowerShell
aws lambda invoke ` --function-name strands-serverless-agent ` --region ap-south-1 ` --cli-binary-format raw-in-base64-out ` --payload '{"prompt":"Use the calculate_percentage tool to calculate 18 percent of 1250."}' ` response.json
Get-Content .\response.jsonYou can also test a normal AWS question:
{ "prompt": "Explain the difference between AWS Lambda and Amazon EC2."}For this request, the agent can answer directly without using the calculator.
Check the execution logs in Amazon CloudWatch to investigate model invocation errors, permission failures, timeouts, and runtime exceptions.
Note: These are expected test cases. The code has not been deployed into your AWS account, so you should run the tests in your own environment before treating the result as verified execution.
11. Optional: Expose the agent through an HTTP endpoint
You can also expose this Lambda function through a Lambda Function URL.
Open:
Lambda → Configuration → Function URL → Create function URL
Select:
Auth type: AWS_IAMThe handler already supports JSON requests containing a
prompt field in the request body.For example:
{ "prompt": "Explain Amazon Bedrock in simple terms."}Because the URL uses IAM authentication, requests must be signed using AWS Signature Version 4.
The calling identity needs both:
lambda:InvokeFunctionUrllambda:InvokeFunctionDo not select
NONE for a private learning agent unless you intentionally want to expose a publicly invokable endpoint and have added appropriate abuse controls.For a larger application that needs API routing, throttling, authorizers, or API-level observability, consider integrating the Lambda function with Amazon API Gateway.
References:
12. Important considerations before production
Deploying an agent to Lambda is useful, but it does not mean every AI workload is a good fit for Lambda.
Execution time
Lambda has a maximum execution duration of 15 minutes. Long-running agent workflows may be better suited to an architecture using AWS Step Functions, Amazon SQS, or a container-based service.
Streaming responses
The documented Strands Lambda deployment example returns a completed response rather than implementing response streaming. For applications that need token-by-token streaming, the Strands deployment guide points to AWS Fargate as an alternative.
State management
Lambda execution environments can be reused. Do not rely on in-memory variables to store user-specific conversation history or sensitive information between requests.
Use an explicit persistence solution when your agent needs long-term sessions.
Tool permissions
Every tool executes with the permissions of the process hosting it. A tool that can read files, access databases, or execute commands must be reviewed carefully.
Give each tool only the access it needs.
Cost
Your application can incur costs from:
- Lambda execution duration and allocated memory.
- Amazon Bedrock input and output tokens.
- Other AWS services your tools access.
- CloudWatch logs and additional observability services.
There is no single fixed cost per agent request. Model usage and Lambda execution time depend on the actual workload.
What you accomplished today
You have taken a Python agent and deployed it into an AWS serverless execution environment.
By completing this exercise, you have:
- Created a Python agent using the Strands Agents SDK.
- Connected the agent to Amazon Nova Lite through Amazon Bedrock.
- Built a custom Python tool using the Strands
@tooldecorator.
- Configured an official Strands Lambda layer.
- Given the Lambda execution role model-invocation permissions.
- Configured memory and timeout settings.
- Invoked the deployed agent using AWS CLI.
- Explored an IAM-authenticated Lambda Function URL.
The key takeaway is that an AI agent does not need a permanently running server to become part of an AWS application.
With Strands, Amazon Bedrock, and AWS Lambda, you can build an agent workflow and run it as an event-driven serverless function.
Day 8 task
Deploy
strands-serverless-agent in your AWS account.Test two requests:
- Ask it to calculate 18% of 1250 and verify that it uses the custom tool.
- Ask it a general AWS question and verify that it returns a normal response.
Then inspect the CloudWatch logs and record the Lambda duration and memory usage.
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 9Day 8 - Deploy Your First Strands AI Agent on AWS Lambda This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article