
Building a Reliable Multi-Agent Heatwave Preparedness System with Strands Agents
How to build a verified multi-agent app with Strands Agents, and deploy it on Amazon Bedrock AgentCore Runtime. Build, verify and clean up, step by step.
Sharing, Learning, Growing Together
The problem
The World Health Organization (WHO) estimates about 489,000 heat-related deaths a year between 2000 and 2019, and calls the health impacts of heat "predictable and largely preventable" ( WHO: Heat and health ). A forecast gives a number, not a plan: what to do before, during and after the hot days, for which people, and when to get help.
HeatWise AI turns a place and a few yes/no facts about a community ("older people live here", "drinking water is limited") into a short, sourced, checked preparedness plan for households, outdoor workers and farmers. Any other input field, such as a name or phone number, is rejected. It is an informational tool: it does not diagnose, send alerts or contact anyone, and forecasts are never shown as official warnings.
How it works
Five Strands agents share the work. In Strands, an agent is a model, a system prompt and the tools it may call. A coordinator delegates to four specialists: weather, community risk, action planner, and safety. Each specialist has its own short prompt and a small allowed tool list.
The model is used only where it helps: choosing advice items from a fixed, sourced catalog, and writing a short explanation. Weather values, the risk level and the safety verdict all come from code. That split is the main idea of this article.

Before you start
Part 1 runs on your machine. Parts 3 to 7 deploy to AWS, create billable resources (a few cents per assessment), and Part 8 removes them.
python --version # 3.11 or lateruv --version # https://docs.astral.sh/uv/node --version # 22.xaws sts get-caller-identity # AWS parts onlynpm install -g @aws/agentcore@0.31.1 # the version I testedYou also need Amazon Nova 2 Lite model access in
us-east-1 . Commands are PowerShell (on macOS or Linux, use .venv/bin/python ). uv, npm and the app's CLI print progress to stderr, which PowerShell shows in red. That is not an error. Check the exit code.Part 1. Run it locally
1.1 Install. All later commands run from the
heatwise-ai folder.git clone https://github.com/dineshrajdhanapathyDD/HeatWise-AI.gitcd HeatWise-AI\heatwise-aiuv venv .venv --python 3.13uv pip install --python .venv\Scripts\python.exe -e ".[dev]".venv\Scripts\python.exe -m pytestExpected:
337 passed, 1 skipped, 4 deselected . The 4 deselected tests call real services. The skipped one needs the AgentCore SDK, which [dev] does not install.1.2 Start the API offline. A scripted stand-in replaces the model and labelled demo data replaces the weather. The agents, hooks, steering and checks all run for real, so you see the whole workflow for free.
$env:AGENT_MODE="offline"; $env:WEATHER_PROVIDER="demo".venv\Scripts\python.exe -m uvicorn backend.main:app --port 80001.3 Run an assessment from a second terminal:
$api = "http://localhost:8000"$body = '{"place":{"name":"demo-hot-dry"},"forecast_days":3,' + '"profile":{"elderly":true,"outdoor_workers":true}}'$job = Invoke-RestMethod -Method Post "$api/api/assessments" ` -ContentType application/json -Body $bodyStart-Sleep 2Invoke-RestMethod "$api/api/assessments/$($job.job_id)"Expected:
status is succeeded with a report_id . For the dashboard, run cd frontend; npm install; npm run build; npm run preview and open http://localhost:5173 .1.4 Try the real model. This calls Amazon Bedrock and the Open-Meteo weather service, but creates no AWS resources. Stop the server, then:
Remove-Item Env:AGENT_MODE, Env:WEATHER_PROVIDER ` -ErrorAction SilentlyContinue.venv\Scripts\python.exe -m backend.cli assess "Nagpur, Maharashtra" ` --elderly --outdoor-workers --farmers --checklist-out .\checklist.mdExit code 0 means
complete , 2 needs_human_review , 1 incomplete . incomplete usually means the weather service did not answer: the app stops instead of guessing. checklist.md lists the plan, each item with its source.Part 2. How the agents are kept honest
2.1 Hooks record what the tools really returned
Models can state things that are not in their input. In an early live run my weather agent's summary said "clear skies", and the data did not say that. A Strands hook runs code at fixed points in the agent loop.
GuardrailHook ( backend/agents/hooks.py ) runs before each tool call and cancels calls that are not allowed or over the limit:from strands.hooks import (BeforeInvocationEvent, BeforeToolCallEvent, HookProvider)
class GuardrailHook(HookProvider): def __init__(self, allowed_tools, max_tool_calls): self.allowed_tools = set(allowed_tools) self.max_tool_calls = max_tool_calls self.calls = 0
def register_hooks(self, registry, **kwargs): registry.add_callback(BeforeInvocationEvent, self.reset) registry.add_callback(BeforeToolCallEvent, self.check)
def reset(self, event): self.calls = 0
def check(self, event: BeforeToolCallEvent): name = event.tool_use.get("name", "") if name not in self.allowed_tools: event.cancel_tool = f"Tool '{name}' is not allowed." return self.calls += 1 if self.calls > self.max_tool_calls: event.cancel_tool = ("Tool call limit reached. " "Report with the data you have.")The
cancel_tool string goes back to the model as the tool result, so write it as an instruction. A second hook, EvidenceLedgerHook , stores every tool's real output. Each specialist builds its result from that record, and any model summary with a number or claim not in the data is replaced.2.2 Agents as tools
Passing a specialist's full output through the coordinator means a 7-day forecast is billed again as input tokens on every turn, and rewritten each time. Input was most of my usage: 120,010 input against 4,283 output tokens over 4 live runs. So each coordinator tool runs a specialist in Python, keeps the full result in code, and returns only a short status (trimmed from
backend/agents/coordinator.py ):@tooldef weather_intelligence(location: str = "", forecast_days: int = 3) -> str: """Delegate to the Weather Intelligence Agent.""" s = state() # this run's state, in code coord._do_weather(s, "model") # full result kept in s.weather w = s.weather return _compact({ "status": w.status, "is_stale": w.is_stale, "next": ("community_risk" if s.weather_usable() else "finalize_report"), })The place and days are bound to the run, so the model cannot change the user's request.
2.3 Steering enforces the order, code finishes the job
The plan needs the risk level, the risk needs the weather, and safety must run before the report is final. The model picks the next tool and does not always follow the prompt: one of my live runs made 9 guidance calls instead of 3. Strands steering checks each call before it runs and lets it through (
Proceed ) or cancels it with guidance ( Guide ):from strands.vended_plugins.steering import ( Guide, Proceed, SteeringHandler)
class OrderingSteeringHandler(SteeringHandler): name = "heatwise-ordering"
def __init__(self, get_state): super().__init__() self._get_state = get_state
def decide(self, tool_name): s = self._get_state() if s.weather is None and tool_name != WEATHER: return "Call weather_intelligence first." if tool_name == PLAN and s.risk is None: return "Call community_risk next." return None # full rules in the repo
async def steer_before_tool(self, *, agent, tool_use, **kwargs): reason = self.decide(tool_use.get("name", "")) if reason is None: return Proceed(reason="Order respected") return Guide(reason=reason)agent = Agent( name="coordinator", tools=self.tools, system_prompt=SYSTEM_PROMPT, hooks=[guardrail, ledger], plugins=[OrderingSteeringHandler(lambda: self._state)], tool_executor=SequentialToolExecutor(), # one tool at a time callback_handler=None,)Steering can cancel a wrong call but cannot force the right one. So after the agent finishes, normally or with an error,
_complete_pipeline runs any missing step in code under the same rules. No report is final without the safety step. In my offline tests the model kept the order on its own in 13 of 18 scenarios, and code finished the rest.2.4 Decisions made only by code
- Risk level.
backend/services/risk_rules.pyuses the NWS heat index bands and the IMD heat-wave thresholds published by WHO India (45 °C heat wave, 47 °C severe, on the plains), as an indication only. The model writes the explanation, never the level.
- Safety.
run_checksreturns pass or fail from code: fresh data, trusted sources, no unsupported numbers, no medication, dose or diagnosis wording, no unverified phone numbers, escalation advice present. A failed plan gets one revision, then the report is markedneeds_human_reviewand only passing items are shown.
Part 3. Deploy the agents on AgentCore Runtime
Amazon Bedrock AgentCore Runtime hosts agent code and bills per use. The entry point is a thin wrapper, so the same code runs locally, in tests and on AgentCore:
from bedrock_agentcore.runtime import BedrockAgentCoreAppfrom backend.agentcore_handler import run_assessment
app = BedrockAgentCoreApp()
@app.entrypointdef invoke(payload, context): return run_assessment( payload, getattr(context, "session_id", None))The runtime is declared in
HeatWiseAC/agentcore/agentcore.json : a CodeZip Python bundle (no Docker) with an extra IAM policy that allows Nova 2 Lite only.3.1 Set the deploy target (git-ignored, because it holds your account id):
$account = aws sts get-caller-identity --query Account --output text@"[{"name": "default", "account": "$account", "region": "us-east-1"}]"@ | Set-Content HeatWiseAC\agentcore\aws-targets.json -Encoding ascii3.2 Stage, validate and deploy. The stage script copies
backend/ into the AgentCore app folder and writes the Nova-only policy with your account id..venv\Scripts\python.exe infrastructure\scripts\stage_agentcore_app.pycd HeatWiseAC\agentcore\cdknpm ci # required once, or deploy fails: 'tsc' not recognizedcd ..\..agentcore validateagentcore deploy --diff --json # previewagentcore deploy -y --jsoncd ..Expected:
validate prints Valid , and the deploy creates the stack AgentCore-HeatWiseAC-default in a few minutes.3.3 Test the runtime directly. Get its ARN:
$name = "HeatWiseAC_heatwise_agent"$q = "agentRuntimes[?agentRuntimeName=='$name'].agentRuntimeArn"$arn = aws bedrock-agentcore-control list-agent-runtimes ` --region us-east-1 --output text --query $qSave this as
invoke_test.py :import json, os, uuid, boto3
client = boto3.client("bedrock-agentcore", region_name="us-east-1")resp = client.invoke_agent_runtime( agentRuntimeArn=os.environ["RUNTIME_ARN"], runtimeSessionId="heatwise-test-" + uuid.uuid4().hex, # 33+ chars payload=json.dumps({"place": {"name": "Nagpur"}, "forecast_days": 3, "profile": {"elderly": True}}).encode(),)report = json.loads(resp["response"].read())print(report["status"], report["report_id"])$env:RUNTIME_ARN = $arn.venv\Scripts\python.exe invoke_test.pyExpected:
complete and a report id after about 20 to 25 seconds (mine took 21.9).Part 4. Why the API is asynchronous, and least privilege
An HTTP API integration times out at 30 seconds, and an assessment takes 20 to 25. A slow model or weather call would push it over. So the API saves a
queued job (a record of the work with a status), starts the worker Lambda with an asynchronous invoke, and returns the job id at once. The worker calls AgentCore, validates the report against its schema, stores it, and marks the job succeeded or failed . The browser polls for the status.The worker's AgentCore client makes exactly one attempt, because a retry would start a second billable run. The tradeoff: a brief network fault fails the job.
Config(read_timeout=settings.agentcore_timeout_seconds, connect_timeout=10, retries={"max_attempts": 1, "mode": "standard"})Each function has its own IAM role. The worker can only update jobs, write reports and invoke one runtime (
infrastructure/stacks/api_stack.py ). It has no Bedrock model access, because the agents run in the runtime:worker_role.add_to_policy(iam.PolicyStatement( actions=["dynamodb:GetItem", "dynamodb:UpdateItem"], resources=[jobs.table_arn]))worker_role.add_to_policy(iam.PolicyStatement( actions=["dynamodb:PutItem"], resources=[assessments.table_arn]))worker_role.add_to_policy(iam.PolicyStatement( actions=["bedrock-agentcore:InvokeAgentRuntime"], resources=[runtime_arn, f"{runtime_arn}/runtime-endpoint/*"]))Part 5. Deploy the API with AWS CDK
Two CDK stacks:
HeatWiseData (two on-demand DynamoDB tables and one S3 bucket) and HeatWiseApi (two arm64 Lambda functions, their roles and logs, and the HTTP API). No VPC, NAT gateway or provisioned capacity..venv\Scripts\python.exe infrastructure\scripts\build_lambda_asset.pyuv venv infrastructure\.venv --python 3.13uv pip install --python infrastructure\.venv\Scripts\python.exe ` -r infrastructure\requirements.txt ` -r infrastructure\requirements-dev.txtinfrastructure\.venv\Scripts\python.exe -m pytest infrastructure\tests -qExpected: the asset builds (about 62 MiB), and the tests show
15 passed, 1 failed . The failure, test_functions , is a stale check that still expects the CORS list from before I added my Amplify URL to infrastructure/cdk.json . It does not affect the deployment.Then deploy (
bootstrap is needed once per account and region):cd infrastructure.\.venv\Scripts\Activate.ps1npx --yes aws-cdk@2.1147.0 bootstrapnpx --yes aws-cdk@2.1147.0 deploy HeatWiseData HeatWiseApi ` -c heatwise:removal=destroy ` -c "heatwise:agentcore_runtime_arn=$arn"cd ..Confirm the IAM changes with
y , then copy the HeatWiseApi.ApiUrl output. heatwise:removal=destroy lets the tables and bucket be deleted with the stacks. Use the same flags in Part 8.Dashboard (optional). Fork the repo and host it in AWS Amplify as a monorepo with app root
heatwise-ai/frontend . Set VITE_API_BASE_URL to your ApiUrl , add the Amplify URL to heatwise:cors_origins in infrastructure/cdk.json and redeploy, and add the single-page-app rewrite rule from docs/deployment.md .Part 6. Verify
$api = "<your ApiUrl>"Invoke-RestMethod "$api/api/health"$body = '{"place":{"name":"Thanjavur","state":"Tamil Nadu"},' + '"forecast_days":3,"profile":{"elderly":true,"farmers":true}}'$job = Invoke-RestMethod -Method Post "$api/api/assessments" ` -ContentType application/json -Body $bodydo { Start-Sleep 3 $j = Invoke-RestMethod "$api/api/assessments/$($job.job_id)" $j.status} while ($j.status -in "queued", "running")$j | Select-Object status, duration_ms, report_id, errorExpected: health shows
status: ok and agent_mode: agentcore . The job prints queued and running , then succeeded after about 20 to 25 seconds (mine took 21.8). In the dashboard's Agent activity tab you see the coordinator and all four specialists in order. If a job fails, read error.code .Part 7. Evaluate it
The repo has 18 synthetic scenarios with known answers, including missing humidity, a stale reading and an unreachable weather service:
.venv\Scripts\python.exe -m backend.evaluation run --mode offlineMetric (synthetic scenarios) | Offline | Live, Nova 2 Lite |
|---|---|---|
Expected status and risk level | 18/18 | 4/4 |
Weather fields extracted exactly | 326/326 | 71/71 |
Plan items with trusted sources | 322/322 | 101/101 |
Order kept by the model alone | 13/18 | 4/4 |
Unsafe injected items rejected | 9/9 | 9/9 |
These show that the code follows its documented rules. They do not show that the rules suit any real place, or anything about health outcomes. The "unsafe items" row tests the guardrail code, not the model. The live run (4 scenarios,
--mode live --confirm-live ) costs money and refuses to start without that flag. Both modes rewrite docs/evaluation.md with your timings.Part 8. Clean up
cd infrastructure.\.venv\Scripts\Activate.ps1npx --yes aws-cdk@2.1147.0 destroy HeatWiseApi HeatWiseData ` -c heatwise:removal=destroy ` -c "heatwise:agentcore_runtime_arn=$arn"cd ..\HeatWiseACagentcore remove all -y # clears local config onlyagentcore deploy -y --json # removes the runtime from AWScd ..aws cloudformation list-stacks --region us-east-1 ` --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE ` --query "StackSummaries[?contains(StackName,'HeatWise')].StackName"Expected: the last command prints no HeatWise stacks. Delete the Amplify app if you created one. The CDK bootstrap stack stays, because other CDK apps share it. If a destroy ends in
DELETE_FAILED , empty the S3 bucket ( aws s3 rm s3://<bucket> --recursive ) and run it again.What it costs
From us-east-1 on-demand prices read on 2026-11-03 (AWS Price List API and the AgentCore pricing page ) and my measured usage:
Part | Per assessment |
|---|---|
Nova 2 Lite tokens ($0.00033 per 1K input, $0.00275 per 1K output) | about $0.013 |
AgentCore Runtime (measured CPU and memory over 5 runs) | about $0.002 to $0.004 |
Worker Lambda (1024 MB, about 20 s) | about $0.0003 |
HTTP API and DynamoDB | under $0.0001 |
Total | about $0.016 to $0.017 |
About $16 to $17 per 1,000 assessments, and close to nothing idle. It is an estimate from small samples, and prices change. AgentCore is a range because I could not tell which compute version my runtime used. Memory was most of it, more than a 20-second run should need: a session may keep running after the reply. I have not confirmed that. Ending the session after each report (
StopRuntimeSession ) would test it.Lessons and tradeoffs
- Let code own the facts. Use the model to choose and explain, and check its text against the data. The cost is less flexible wording and rules to maintain.
- Cancel with an instruction. A cancelled call that says what to do next got my model back on track.
- Keep a code path to the end. Steering stops wrong calls. Only the fallback guarantees the safety step.
- Keep structured output small. Nova 2 Lite once put a number in a list-of-strings field and repeated it on every retry. Small, flat schemas and two attempts at most fixed it.
- Start on AgentCore. I first ran the agents inside Lambda and moved them later. The worker Lambda stayed only because of the 30-second API limit.
- Check the live app in a browser. All tests passed, but screenshots of the deployed site still found a phone layout overflow and a weather icon that did not match the data.
Before real use
- Sign-in. The demo API is public and only throttled, and each run costs money. Add IAM or Amazon Cognito authorization.
- Runtime role. The AgentCore CLI's default role allows any Bedrock model. Use your own role scoped to one model.
- Official warnings and local rules. Open-Meteo is forecast model data, not warnings, and the IMD thresholds are for India. Connect your national weather service and use your local rules.
- Language. Plans are English only.
- Real testing. The evaluation is synthetic. Test the plans with health workers and community members first.
Troubleshooting
Symptom | Fix |
|---|---|
Live run returns incomplete | The weather service did not answer. Retry in a minute |
Access denied on a live run | Enable Nova 2 Lite in the Bedrock console for us-east-1 |
'tsc' is not recognized on deploy | Run npm ci in HeatWiseAC\agentcore\cdk |
agentcore commands differ | Install @aws/agentcore@0.31.1 |
Health check is not agentcore | Redeploy HeatWiseApi with the runtime ARN |
Dashboard can't load reports | Add its URL to heatwise:cors_origins and redeploy |
Destroy ends in DELETE_FAILED | Empty the S3 bucket and retry |
Conclusion
HeatWise AI uses Strands Agents to turn a forecast into a community preparedness plan. The most important lesson was that a reliable agentic application needs more than several agents and a capable model. It needs controlled delegation, evidence-backed outputs, deterministic decisions, verification, a graceful fallback, and an architecture that can handle long-running work.
Strands Agents provided the orchestration building blocks, Amazon Bedrock supplied the model, and AgentCore Runtime hosted the workflow separately from the API layer. By my estimate, one assessment costs a couple of cents.
The evaluation shows that the pipeline carries the documented rules into the report and that the guardrails reject the unsafe items I injected. It does not show anything about real communities. The next steps are official warning data, authentication, local languages and a field study with partners.
Try it:
- Live demo: https://main.dmupjpltx9cou.amplifyapp.com
Thank you for taking the time to read my article! If you found it helpful, feel free to like, share, and drop your thoughts in the comments; I’d love to hear from you.
If you want to connect or dive deeper into cloud, AI and DevOps, feel free to follow me on my socials:
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article