Practical guide · Beginner · 45 minutes
Build an Agent with Tools Using Strands Agents

Connect a ready-made API tool and a custom Python dice-rolling function to an Amazon Bedrock agent, then verify what happened in its logs.
An agent becomes useful when it can take a well-defined action instead of only generating text. In this tutorial, you will build a small Strands Agents program with two tools: a ready-made HTTP tool for querying a rules API and a custom Python tool that rolls dice. The model decides when to call each tool; your program executes the calls; and the log output gives you evidence that the tools actually ran.
The example is intentionally small. It does not prove that every model will select tools perfectly, and it does not replace authentication, authorization, rate limiting, or production observability. It gives you a repeatable local experiment with a clear boundary between model reasoning, tool execution, and returned data.
The result you will build
The finished program gives an agent two capabilities:
- Rules lookup: the agent can use a ready-made HTTP request tool to query a rules API.
- Dice rolling: the agent can call a custom Python function that validates a dice expression and returns the rolls.
A natural-language request such as “Look up the rule section for actions, then roll 2d6” should lead to a sequence like this:
- The model receives the user request and the tool descriptions.
- The model emits a tool call for the rules lookup.
- Strands executes the HTTP tool and sends the result back to the model.
- The model emits a tool call for
roll_dice. - Strands executes the Python function and sends its result back.
- The model writes a final answer using the returned data.
The exact wording and ordering can vary. Tool selection is model-driven, so the useful verification target is not a particular sentence. It is evidence that the expected tool names were made available and that the corresponding calls were executed.
Prerequisites
You need:
- Python 3.10 or newer.
- An AWS account with access to Amazon Bedrock.
- A model enabled for your account in the AWS Region you intend to use.
- A configured AWS identity with permission to invoke that model.
- Outbound network access if you want to query the example rules API.
Keep credentials outside the source file. Use an AWS profile, environment variables, or another supported AWS credential provider. Do not paste access keys into the code, shell history, screenshots, or article notes.
Configure AWS credentials
The following command is an example of selecting a named local AWS profile:
export AWS_PROFILE=my-bedrock-profile
export AWS_REGION=us-west-2
Replace the profile name and Region with values that exist in your environment. The example does not establish that a particular Region, model, or account has access. If you normally use another AWS credential provider, keep using that provider instead.
Create the project
Create an isolated directory and virtual environment:
mkdir strands-tools-demo
cd strands-tools-demo
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install strands-agents strands-agents-tools boto3
On Windows PowerShell, activate the environment with:
.\.venv\Scripts\Activate.ps1
The package names and APIs can change over time. If installation or imports fail, inspect the installed package versions and consult the version-specific Strands documentation before changing the code.
Connect the ready-made API tool
Strands provides ready-made tools for common operations. In this example, the
API tool is the HTTP request tool from
strands_tools. It lets the model request a URL without you writing an HTTP client
wrapper for this small experiment.
The API endpoint below is an example of a public D&D 5e rules API path. Public services can change, rate-limit requests, or become unavailable. Treat the URL as a replaceable example, not as a service-level guarantee.
RULES_API_URL = "https://www.dnd5eapi.co/api/2014/rule-sections"
A ready-made HTTP tool is powerful enough to reach many destinations. That is also its main risk: the model may request a URL you did not intend to expose. In production, place an allowlist, proxy, network policy, or purpose-built wrapper between the agent and external services.
Add a custom Python dice tool
A custom tool is an ordinary Python function
exposed to the agent with the @tool decorator. Its type hints and docstring
describe the operation to the model. The function itself remains responsible for validation.
Save the following as agent.py:
import logging
import random
import re
from strands import Agent, tool
from strands.models import BedrockModel
from strands_tools import http_request
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
@tool
def roll_dice(expression: str) -> str:
"""Roll dice using a simple NdM expression.
Args:
expression: Dice expression such as "2d6" or "1d20".
Returns:
A concise description of the individual rolls and their total.
"""
match = re.fullmatch(r"\s*(\d+)\s*[dD]\s*(\d+)\s*", expression)
if not match:
return "Invalid dice expression. Use a form such as 2d6."
count = int(match.group(1))
sides = int(match.group(2))
if not 1 <= count <= 20:
return "Dice count must be between 1 and 20."
if not 2 <= sides <= 100:
return "Dice sides must be between 2 and 100."
rolls = [random.randint(1, sides) for _ in range(count)]
total = sum(rolls)
return f"{count}d{sides}: rolls={rolls}, total={total}"
model = BedrockModel(
model_id="REPLACE_WITH_A_MODEL_ID",
region_name="REPLACE_WITH_AWS_REGION",
)
agent = Agent(
model=model,
tools=[http_request, roll_dice],
system_prompt=(
"You are a rules assistant. "
"Use the HTTP tool only for the configured rules API. "
"Use roll_dice whenever the user asks for a random dice result. "
"Do not invent tool results. "
"If a tool fails, explain that it failed."
),
)
question = (
"Use the HTTP tool to look up the rules API collection at "
"https://www.dnd5eapi.co/api/2014/rule-sections. "
"Then roll 2d6 with the dice tool and report the rules lookup result "
"and the dice result separately."
)
response = agent(question)
print(response)
Replace both model placeholders before running the file. The model ID must be available to your AWS account in the selected Region. The code deliberately keeps the dice tool deterministic in shape, but not in value: every valid call produces a new random result.
Why the docstring matters
The model does not inspect your Python function the way a human developer does. The tool description and schema are the model’s working contract. A vague description such as “does dice stuff” gives the model little guidance. The example instead states the accepted input format, gives an example, and returns a compact result.
The function still validates its input because model-generated arguments are not a security boundary. Rejecting excessive dice counts and side counts prevents this toy tool from doing unexpectedly large work.
Choose the Bedrock model
The BedrockModel object connects Strands to Amazon Bedrock. Set a model ID that
supports tool calling in your account and Region. The article cannot name a universally valid
model ID because access depends on your account configuration and can change.
For a quick local experiment, you can also pass a model ID directly when supported by your
installed Strands version. Using an explicit BedrockModel keeps the Region visible
in the example and makes the provider boundary clear.
model = BedrockModel(
model_id="REPLACE_WITH_A_MODEL_ID",
region_name="REPLACE_WITH_AWS_REGION",
)
If the model rejects the request because of an unsupported schema feature, simplify the tool signature first. This example uses one string parameter and basic return text intentionally.
Run the agent
Run the program from the activated virtual environment:
python agent.py
A successful run should print a final model response. The response may summarize the rules endpoint, show the dice result, or explain an API response format. The numeric dice result will differ between runs. That output alone is not sufficient to prove that both tools ran; inspect the logs as described next.
Verify tool calls in logs
Observability starts with making the execution
path visible. The logging configuration above sets the Python root logger to
INFO, which is a useful first diagnostic setting. Strands may emit messages
through its own logger, and the exact logger names and message formats can vary by version.
Capture the run to a file so you can search it without copying secrets into a ticket:
python agent.py 2>agent.log | tee agent-output.txt
rg -i "tool|http_request|roll_dice|invocation|error" agent.log agent-output.txt
Depending on the installed version and logging configuration, look for evidence with these properties:
- The agent was given the tools
http_requestandroll_dice. - A model response requested a tool call.
- The requested tool name appears in the execution trace.
- The tool returned a result or an explicit error.
- The agent continued after the result and produced a final response.
Do not treat a line containing the word “tool” as proof by itself. Correlate the tool name, input, result, and sequence. A useful manual record looks like this:
| Evidence | What it supports | What it does not prove |
|---|---|---|
http_request appears in the tool-call trace |
The agent requested the HTTP tool by name. | That the remote API returned correct data. |
roll_dice returns rolls=[...], total=... |
The Python function executed and returned a value with the expected shape. | That the model selected the tool for every similar prompt. |
| An exception or HTTP error is logged | The failure was visible to the local process. | That the user-facing recovery message is adequate for production. |
Add explicit tool-side logging
Framework logs are useful, but tool-side logging gives you an additional, local signal. Add a logger to the custom function if you need to verify entry and exit without relying on a particular framework message format:
logger = logging.getLogger(__name__)
@tool
def roll_dice(expression: str) -> str:
logger.info("roll_dice called with expression=%r", expression)
# validation and rolling code goes here
result = f"{count}d{sides}: rolls={rolls}, total={total}"
logger.info("roll_dice completed")
return result
Avoid logging credentials, authorization headers, full customer requests, or unrestricted tool arguments. In this example the argument is harmless, but a production tool may receive personal or confidential data.
Use prompts that make verification easier
Natural-language tool selection is probabilistic. For a first smoke test, use a request that names the intended action clearly:
Call the dice tool exactly once with 1d6. Return the tool result plainly.
Then test the HTTP path separately:
Use the HTTP tool to request:
https://www.dnd5eapi.co/api/2014/rule-sections
Summarize only the returned status or response.
Finally, test the combined flow:
Use the HTTP tool for the rules API URL, then use the dice tool once with 2d6.
Keep the two results separate.
These are test prompts, not guarantees. If a model answers from prior knowledge instead of calling a tool, make the request more explicit and inspect the trace. For deterministic testing, invoke the Python function directly in a unit test and use a mocked HTTP client or local fixture rather than depending on model selection or a live public endpoint.
Failure cases and fixes
Import error for strands or strands_tools
Confirm that the virtual environment is active and that the packages were installed into the same interpreter used to run the file:
python -c "import sys; print(sys.executable)"
python -m pip show strands-agents strands-agents-tools
AWS authentication or authorization error
Check the active profile, Region, model access, and IAM permissions. Do not solve an
authentication error by putting a secret key in agent.py. If your organization
uses SSO, a role, or a credential broker, renew that session through the approved process.
Model not found or model access is unavailable
The model ID may be wrong for the selected Region, or the account may not have access. Confirm the identifier and access in the AWS console or your organization’s approved provisioning process. This article does not prescribe a model because availability is account-specific.
The agent never calls a tool
Check that both tools are present in the tools=[...] list, that the prompt
clearly asks for an action, and that the tool descriptions are specific. The model is allowed
to answer without a tool unless the model/provider configuration and prompt make tool use
necessary.
The HTTP tool fails
Test the URL outside the agent with a normal HTTP client if your environment permits it:
python -c "import urllib.request; print(urllib.request.urlopen('https://www.dnd5eapi.co/api/2014/rule-sections').status)"
A failure may come from DNS, a firewall, TLS inspection, the public service, rate limiting, or the tool’s accepted input schema. Do not assume that a successful browser request proves the agent runtime has the same network access.
The dice tool returns invalid input
The model may send a value such as “two six-sided dice” instead of 2d6. Either
keep the strict contract and ask for the supported format, or expand validation deliberately.
Do not remove bounds merely to make an invalid call pass.
Logs do not show the expected framework messages
Logging output depends on package version, logger configuration, and the execution environment. Keep the explicit log statements inside your own tools, increase the relevant logger’s level, and inspect the installed package documentation. If you need durable traces, use an application-level event record with redaction rather than depending on console formatting.
Security and operational limits
This demo exposes two important boundaries:
- The HTTP tool can create network side effects and should not receive unrestricted URL access in production.
- The custom tool executes local code, so its implementation and dependencies must be reviewed like any other application code.
Before deploying a similar agent, decide which hosts are allowed, how requests are authenticated, how timeouts and retries work, how response sizes are limited, and how tool errors are reported. Add structured logs with request IDs, but redact secrets and sensitive arguments. Consider whether the agent should be allowed to call a tool repeatedly or in parallel.
The example also has no durable state, no user authentication, no billing controls, no evaluation suite, and no guarantee that an external rules API remains available. Those are separate engineering tasks.
Reproducibility checklist
Before calling your own run successful, record:
- The Python version.
- The installed Strands package versions.
- The AWS Region and model ID, without recording credentials.
- The exact prompt used for the smoke test.
- The tool names made available to the agent.
- The relevant redacted log lines showing the calls and results.
- Whether the rules API was reachable from the same runtime.
- Any differences from the code in this article.
A reproducible record distinguishes “the model said it used a tool” from “the runtime logged a tool invocation and returned a result.” That distinction becomes increasingly important as tools gain access to data, networks, and business actions.
Summary
You connected a ready-made HTTP tool and a custom @tool-decorated Python
function to a Strands agent backed by Amazon Bedrock. The HTTP tool handles the rules lookup;
the dice function owns validation and random-number generation. Logging and controlled prompts
let you inspect whether the intended calls occurred, while the failure cases show why a final
model answer is not enough evidence on its own.
Continue with the other Agent Lab Journal guides or look up terms in the glossary.