AWS Builder Center
Build Your First AI Agent on AWS with Strands + Bedrock: Tools, Guardrails, and Tests You Can Run for Free
Build Your First AI Agent on AWS with Strands + Bedrock: Tools, Guardrails, and Tests You Can Run for Free

Build Your First AI Agent on AWS with Strands + Bedrock: Tools, Guardrails, and Tests You Can Run for Free Build Your First AI Agent on AWS with Strands + Bedrock: Tools, Guardrails, and Tests You Can Run for Free

A hands-on, step-by-step guide to building a real AI agent with the open-source Strands Agents SDK and Amazon Bedrock. You'll write custom tools, add a human-approval safety hook, connect a Bedrock Guardrail, and test the whole agent with a mock model so your tests cost nothing. All code was run and tested before publishing.

Most "build an AI agent" tutorials stop at a demo that works once, on the author's laptop, when nothing goes wrong. This one goes a bit further. We'll build a small agent, make it safe, and, the part most tutorials skip, test it without spending a single token.
All the code in this article was run before I wrote it down, using the Strands Agents SDK (version 1.63.0 at the time of writing, Python 3.10 or newer, Apache-2.0 licensed). SDKs move fast, so if something doesn't match your version, check the official Strands documentation.


The scenario: Kabir's chaotic placement season

Meet Kabir, a final-year student. He's not a real person, but his problem is very real for a lot of students.
It's placement season. Every company has a different online assessment date, a different form deadline, and a different interview slot. Kabir tracks them across WhatsApp messages, email, a notes app, and his memory. Last week he missed a registration deadline because it was buried in a group chat.
What Kabir needs isn't a smarter calendar. He needs to type, in plain English, "Add the Acme online assessment on 20 November 2026" and later ask "What's due soonest?", and have something reliable handle the rest.
That's a perfect job for a small AI agent. Let's build it.


What is Strands Agents?

Strands Agents is an open-source Python SDK for building AI agents. Its idea is model-driven: you give the agent three things, and it handles the loop of thinking, calling tools, and answering:
  1. A model (we'll use one on Amazon Bedrock)
  1. A system prompt (the agent's role and rules)
  1. Tools (plain Python functions the agent may call)
You don't write the "decide which function to call" logic yourself. The model decides, and Strands runs the loop.


Setup

You'll need Python 3.10 or newer, an AWS account with credentials configured, and access to a model in Amazon Bedrock (you request model access in the Bedrock console, and availability depends on your region).
python -m venv venv
source venv/bin/activate # on Windows: venv\Scripts\activate
pip install strands-agents pytest
aws configure # only needed for the live Bedrock steps
Here's the project layout we'll end up with:
placement-agent/
├── tracker.py # tools, safety hook, and agent builder
├── mock_model.py # a fake model for free tests
└── test_tracker.py # our tests




Step 1: The smallest possible agent

Before adding anything fancy, let's confirm the basics work. This calls a real Bedrock model, so it uses a little of your AWS usage:
from strands import Agent
from strands.models import BedrockModel

model = BedrockModel(
model_id="YOUR_MODEL_ID", # a model you have access to in Bedrock
region_name="us-east-1",
temperature=0.2,
)

agent = Agent(model=model, system_prompt="You are a helpful assistant.")
agent("Explain what an AWS Lambda function is in two sentences.")
Replace  YOUR_MODEL_ID  with a model ID from your Bedrock console. Some models need a cross-region inference profile ID instead of a plain model ID, so if you get an error about the model not being available on-demand, check the Bedrock docs for the right ID format in your region.
A low  temperature  (like 0.2) makes the model more predictable, which is what you want for an agent that handles deadlines.




Step 2: Give the agent tools

A chatbot only talks. An agent does things, and in Strands you give it abilities with the  @tool  decorator. Here are Kabir's four tools, which save deadlines to a small JSON file:
# tracker.py
import json
from datetime import date, datetime
from pathlib import Path

from strands import Agent, tool

DB = Path("deadlines.json")

def _load() -> list[dict]:
return json.loads(DB.read_text()) if DB.exists() else []

def _save(items: list[dict]) -> None:
DB.write_text(json.dumps(items, indent=2))

@tool
def add_deadline(company: str, task: str, due: str) -> str:
"""Save a placement-related deadline.

Args:
company: Company name, for example "Acme Corp".
task: What has to be done, for example "Online assessment".
due: Due date in YYYY-MM-DD format.
"""
try:
datetime.strptime(due, "%Y-%m-%d")
except ValueError:
return "Error: 'due' must be a date in YYYY-MM-DD format."
items = _load()
items.append({"company": company, "task": task, "due": due})
_save(items)
return f"Saved: {company} - {task} (due {due})"

@tool
def list_deadlines() -> list[dict]:
"""List every saved deadline, soonest first."""
return sorted(_load(), key=lambda d: d["due"])

@tool
def days_left(due: str) -> int:
"""Return how many days remain until a date (negative if it has passed).

Args:
due: Date in YYYY-MM-DD format.
"""
return (datetime.strptime(due, "%Y-%m-%d").date() - date.today()).days

@tool
def delete_deadline(company: str, task: str) -> str:
"""Permanently delete a saved deadline.

Args:
company: Company name exactly as saved.
task: Task name exactly as saved.
"""
items = _load()
kept = [d for d in items if not (d["company"] == company and d["task"] == task)]
_save(kept)
return f"Deleted {len(items) - len(kept)} deadline(s)."
Two things make this work, and both are easy to overlook:
  • The docstring is the instruction manual. Strands reads each function's name, type hints, and docstring to tell the model what the tool does and what arguments it takes. A vague docstring leads to a confused agent, so be specific, and say what format dates should be in.
  • The tool validates its own input. Notice  add_deadline  rejects a badly formatted date instead of trusting the model. Never assume the model will always send perfect arguments.
Tools are still normal Python functions, so you can call them directly to check they work:
print(add_deadline("Acme", "Online assessment", "2026-11-20"))
print(list_deadlines())




Step 3: Add a system prompt and conversation memory

Next, give the agent a role and some ground rules:
SYSTEM_PROMPT = (
"You are a calm placement-season assistant. Use the tools to save and look up "
"deadlines. Never guess a date: if the user does not give a full date, ask. "
"Keep answers short."
)
That "never guess a date" line matters. Without it, a model might happily turn "next Friday" into some date and save it. The prompt nudges the agent to ask instead.
By default, an agent keeps the conversation history, so follow-up questions work:
agent("Add the Acme online assessment on 20 November 2026")
agent("What did I just add?") # the agent remembers the previous turn
Long conversations eventually outgrow a model's context window, so you can control how much history is kept with a conversation manager:
from strands.agent import SlidingWindowConversationManager

agent = Agent(
model=model,
system_prompt=SYSTEM_PROMPT,
tools=[add_deadline, list_deadlines, days_left, delete_deadline],
conversation_manager=SlidingWindowConversationManager(window_size=20),
)
Remember that this memory lasts only while your program runs. The deadlines themselves survive because our tools write them to a file.




Step 4: Add a safety hook for risky actions

Here's a problem. Our agent has a  delete_deadline  tool, and a model can misunderstand a request. "Clear the Acme stuff" might delete more than Kabir intended.
If you read my earlier article on AI agent guardrails, you'll recognise the idea: don't rely on the prompt to keep the agent safe, enforce it in code. Strands lets you do that with hooks, which are functions that run at specific points in the agent's loop. This hook runs before every tool call and blocks risky tools unless a human approves:
from strands.hooks import BeforeToolCallEvent, HookProvider, HookRegistry

DESTRUCTIVE_TOOLS = {"delete_deadline"}

class ConfirmDestructive(HookProvider):
"""Blocks risky tools unless a human approves them."""

def __init__(self, approve):
self.approve = approve # a function: (tool_name, tool_input) -> bool

def register_hooks(self, registry: HookRegistry, **kwargs) -> None:
registry.add_callback(BeforeToolCallEvent, self.check)

def check(self, event: BeforeToolCallEvent) -> None:
name = event.tool_use["name"]
if name in DESTRUCTIVE_TOOLS and not self.approve(name, event.tool_use["input"]):
event.cancel_tool = f"A human declined '{name}'. Do not retry it."
Setting  event.cancel_tool  stops the tool from running, and the message you provide is handed back to the model as an error, so it knows the action didn't happen.
The  approve  function is up to you. In a terminal app, it can simply ask the user:
def ask_in_terminal(tool_name: str, tool_input: dict) -> bool:
answer = input(f"Agent wants to run {tool_name} with {tool_input}. Allow? [y/N] ")
return answer.strip().lower() == "y"
In a web app or a Slack bot, it could show an Approve / Reject button instead.
Now let's put everything together in a single builder function:
def build_agent(model, approve) -> Agent:
return Agent(
model=model,
system_prompt=SYSTEM_PROMPT,
tools=[add_deadline, list_deadlines, days_left, delete_deadline],
hooks=[ConfirmDestructive(approve)],
callback_handler=None, # silence streaming output; remove it to watch the agent think
)
Passing the model and the approval function in, instead of hard-coding them, is what makes the next step possible.




Step 5: Add a Bedrock Guardrail

The hook protects your tools. A Bedrock Guardrail protects the model's inputs and outputs, such as blocking prompt-injection attempts or redacting personal information. If you've already created one, attach it to the model:
model = BedrockModel(
model_id="YOUR_MODEL_ID",
region_name="us-east-1",
temperature=0.2,
max_tokens=1000,
guardrail_id="YOUR_GUARDRAIL_ID",
guardrail_version="1",
guardrail_trace="enabled", # helpful while testing; shows which filter fired
)
Pin a numbered guardrail version for anything beyond experiments, so a later edit to the guardrail can't silently change your agent's behaviour. (I covered how to create a guardrail in my article "5 Guardrails Every AWS AI Agent Needs Before It Touches Production".)




Step 6: Test your agent without paying for tokens

This is the part I'm most excited to share, because almost nobody does it. Testing an agent against a real model is slow, costs money, and gives different answers each time. So instead, we replace the model with a mock that replays scripted responses.
Strands'  Model  class can be subclassed, so here's a tiny fake model:
# mock_model.py
import json
from typing import Any, AsyncIterable

from strands.models import Model

class MockModel(Model):
"""A fake model that replays scripted responses, so tests cost nothing."""

def __init__(self, responses: list[list[dict[str, Any]]]):
self.responses = list(responses)
self.config: dict[str, Any] = {}

def update_config(self, **model_config):
self.config.update(model_config)

def get_config(self):
return self.config

async def structured_output(self, output_model, prompt, system_prompt=None, **kwargs):
raise NotImplementedError

async def stream(self, messages, tool_specs=None, system_prompt=None, **kwargs) -> AsyncIterable[dict[str, Any]]:
for event in self.responses.pop(0):
yield event

def tool_call(name: str, args: dict, tool_use_id: str = "t1"):
"""Scripted model turn: the model asks to call a tool."""
return [
{"messageStart": {"role": "assistant"}},
{"contentBlockStart": {"start": {"toolUse": {"toolUseId": tool_use_id, "name": name}}}},
{"contentBlockDelta": {"delta": {"toolUse": {"input": json.dumps(args)}}}},
{"contentBlockStop": {}},
{"messageStop": {"stopReason": "tool_use"}},
]

def text_reply(text: str):
"""Scripted model turn: the model answers in plain text."""
return [
{"messageStart": {"role": "assistant"}},
{"contentBlockStart": {"start": {}}},
{"contentBlockDelta": {"delta": {"text": text}}},
{"contentBlockStop": {}},
{"messageStop": {"stopReason": "end_turn"}},
]
With that, we can script a "conversation": first the model decides to call a tool, then it replies in plain text. Now write the tests:
# test_tracker.py
import json

import pytest

import tracker
from mock_model import MockModel, tool_call, text_reply

@pytest.fixture(autouse=True)
def temp_db(tmp_path, monkeypatch):
# every test gets its own empty deadlines file
monkeypatch.setattr(tracker, "DB", tmp_path / "deadlines.json")

def test_add_deadline():
model = MockModel([
tool_call("add_deadline", {"company": "Acme", "task": "OA", "due": "2026-11-20"}),
text_reply("Saved your Acme OA for 20 Nov."),
])
agent = tracker.build_agent(model, approve=lambda name, args: True)
agent("Add the Acme online assessment on 20 Nov 2026")

assert json.loads(tracker.DB.read_text()) == [
{"company": "Acme", "task": "OA", "due": "2026-11-20"}
]

def test_bad_date_is_rejected_by_the_tool():
result = tracker.add_deadline("Acme", "OA", "next friday")
assert result.startswith("Error")
assert not tracker.DB.exists()

def test_delete_is_blocked_when_human_declines():
tracker._save([{"company": "Acme", "task": "OA", "due": "2026-11-20"}])
model = MockModel([
tool_call("delete_deadline", {"company": "Acme", "task": "OA"}),
text_reply("Okay, I did not delete it."),
])
agent = tracker.build_agent(model, approve=lambda name, args: False)
agent("Delete the Acme OA")

assert len(json.loads(tracker.DB.read_text())) == 1 # still there

def test_delete_works_when_human_approves():
tracker._save([{"company": "Acme", "task": "OA", "due": "2026-11-20"}])
model = MockModel([
tool_call("delete_deadline", {"company": "Acme", "task": "OA"}),
text_reply("Deleted."),
])
agent = tracker.build_agent(model, approve=lambda name, args: True)
agent("Delete the Acme OA")

assert json.loads(tracker.DB.read_text()) == []
Run them:
python -m pytest -q
When I ran these, all four passed in about half a second, with no AWS credentials and no tokens spent.
What these tests prove, and what they don't. They prove your plumbing is right: tools save data correctly, bad input is rejected, and the safety hook really blocks a deletion when a human says no. They do not prove the real model will choose the right tool or word its answers well. For that, you still need a few live runs against Bedrock. Think of mock tests as the cheap safety net that runs on every code change, and live tests as the occasional spot check.




Step 7 (optional): Run it on AWS Lambda

Once it works locally, you can wrap the agent in a Lambda function so it can be called from an API, a chat bot, or a schedule. This is the shape of the handler:
# lambda_function.py
from strands.models import BedrockModel
from tracker import build_agent

model = BedrockModel(model_id="YOUR_MODEL_ID", temperature=0.2)

# approve always returns False, so destructive tools can never run unattended
agent = build_agent(model, approve=lambda name, args: False)

def lambda_handler(event, context):
result = agent(event["prompt"])
return {"reply": str(result)}
Note the safe default: with nobody there to click "approve", the destructive tool is simply blocked. A few more things to consider before deploying:
  • Lambda's file system is temporary, so use something like DynamoDB instead of a JSON file for real storage.
  • Give the Lambda's IAM role only the Bedrock and storage permissions it needs (least privilege again).
  • Set a sensible timeout, because agents can take several seconds per step.
  • Keep a billing alert on, since every model call costs money.
I haven't covered packaging and deploying the Lambda here, since that's a topic of its own. This snippet only shows the handler's structure.

Common mistakes to avoid

  • Vague tool docstrings. The model only knows what you tell it. Be precise about arguments and formats.
  • Trusting the model's arguments. Validate inside the tool, like the date check above.
  • Relying on the prompt for safety. "Never delete without asking" in the system prompt is a suggestion. The hook is enforcement.
  • Only testing with the live model. It's slow, costly, and non-deterministic. Mock the model for everyday tests.
  • Giving the agent too many tools at once. Start with a few and add more as you need them.
  • Forgetting the bill. Set a budget alert before you experiment.




Quick checklist (save this!)

  • Python 3.10+,  strands-agents  installed in a virtual environment
  • Bedrock model access enabled in your region
  • Tools have clear docstrings and validate their own input
  • System prompt tells the agent to ask instead of guess
  • Risky tools are gated by a hook (human approval)
  • Guardrail attached, with a pinned version
  • Mock-model tests for tools and hooks
  • A few live test runs before trusting the real thing
  • Billing alert set

Final thoughts

An agent isn't magic. It's a model, a prompt, and some Python functions with good safety checks around them. Once you see that, building one feels a lot less intimidating, and the habits that matter (clear tools, enforced safety, cheap tests) are the same ones that make any software dependable.
Start small. Build the four-tool tracker, break it with the mock tests, then connect it to a real model and try it on your own tasks. What would you automate first?
What would you build your first agent for? Tell me in the comments, and if this was useful, a like helps other builders find it.
SDK versions, model availability, and AWS pricing change over time. Verify details against the official Strands Agents and Amazon Bedrock documentation, and test in your own account before relying on anything here.
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