AWS Builder Center
Building an AI-Powered FinOps Agent That Explains Your AWS Bill — Using Amazon Bedrock AgentCore

Building an AI-Powered FinOps Agent That Explains Your AWS Bill — Using Amazon Bedrock AgentCore

How we built an intelligent billing analyst that queries cost data, detects anomalies, and produces executive summaries — deployed and running on AWS in under an hour.

The Problem: "Why Did Our AWS Bill Go Up?"

It's the question every cloud team dreads. A stakeholder pings you on Monday morning: "Our AWS bill increased 23% last month. Why?"
What follows is a manual investigation that can take hours. You open Cost Explorer, click through dashboards, cross-reference account IDs, eyeball charts for anomalies, and eventually piece together a narrative. By the time you've found the root cause — an ML team spun up GPU instances, a data pipeline started cross-region transfers — you've burned half a day on something that could be automated.
What if you could just ask an AI agent: "Why did our bill go up?" — and get a precise, data-backed answer with dollar amounts, root causes, and optimization recommendations?
That's exactly what we built.



What We Built

BillExplainer is a FinOps assistant powered by Amazon Bedrock AgentCore and the Strands Agents framework. It analyzes AWS Cost & Usage Report (CUR) data and produces clear, actionable explanations of cloud spending.
Here's what it can do:
  • Query billing data directly using SQL against a DuckDB database
  • Detect cost anomalies using statistical z-score analysis across services, accounts, and usage types
  • Generate optimization recommendations tailored to each finding
  • Remember prior analyses across conversations so it can say "last time I checked, EC2 was $12,400 — now it's $15,600"
  • Export executive summaries as styled HTML reports, Markdown, or JSON
The architecture looks like this:
┌──────────────────────────────────────────────────────────────────┐
│ User Interface │
│ ┌─────────────────┐ ┌───────────────────────────────────┐ │
│ │ Streamlit Chat │ │ CLI (agentcore invoke) │ │
│ │ UI (port 8502) │ │ │ │
│ └────────┬─────────┘ └──────────────┬────────────────────┘ │
│ │ │ │
│ └──────────────┬───────────────┘ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Amazon Bedrock AgentCore Runtime │ │
│ │ │ │
│ │ ┌─────────────────────────────────────────────────┐ │ │
│ │ │ Strands Agent (Claude Sonnet) │ │ │
│ │ │ │ │ │
│ │ │ System Prompt: FinOps Analyst Workflow │ │ │
│ │ │ 8-Step Analysis → Evidence-Based Findings │ │ │
│ │ └────────┬─────────────┬──────────────┬────────────┘ │ │
│ │ │ │ │ │ │
│ │ ┌───────▼──────┐ ┌───▼───────┐ ┌───▼──────────────┐ │ │
│ │ │ 5 Agent │ │ Bedrock │ │ AgentCore │ │ │
│ │ │ Tools │ │ Models │ │ Memory │ │ │
│ │ └──────────────┘ └───────────┘ └──────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Tool Layer │ │
│ │ │ │
│ │ ┌──────────────┐ ┌────────────────┐ ┌──────────────┐ │ │
│ │ │ Schema │ │ SQL Query │ │ Anomaly │ │ │
│ │ │ Discovery │ │ Engine │ │ Detection │ │ │
│ │ │ │ │ │ │ (z-score) │ │ │
│ │ └──────┬───────┘ └───────┬────────┘ └──────┬───────┘ │ │
│ │ │ │ │ │ │
│ │ └──────────────────┼───────────────────┘ │ │
│ │ ▼ │ │
│ │ ┌──────────────┐ │ │
│ │ │ DuckDB │ │ │
│ │ │ (CUR Data) │ │ │
│ │ └──────────────┘ │ │
│ │ │ │
│ │ ┌──────────────┐ ┌────────────────┐ │ │
│ │ │ Optimization │ │ Executive │ │ │
│ │ │ Recommender │ │ Summary Export │ │ │
│ │ └──────────────┘ └────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Memory Layer (Post-Deploy) │ │
│ │ │ │
│ │ ┌──────────────────┐ ┌──────────────────────────────┐ │ │
│ │ │ SEMANTIC │ │ SUMMARIZATION │ │ │
│ │ │ /users/{id}/ │ │ /summaries/{id}/{session}/ │ │ │
│ │ │ facts │ │ │ │ │
│ │ │ │ │ Compresses conversation │ │ │
│ │ │ Extracts cost │ │ history for long sessions │ │ │
│ │ │ baselines & │ │ │ │ │
│ │ │ anomaly facts │ │ │ │ │
│ │ └──────────────────┘ └──────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────┘

We built it in three phases, each one delivering a working, testable increment. Here's how.



Phase 1: The MVP — From Zero to "Talk to Your Data" in Minutes

Scaffolding the project

We started with the AgentCore CLI:
agentcore create --name BillExplainer --framework Strands \
--model-provider Bedrock --build CodeZip --memory none

This gave us a project skeleton with a Strands agent, Bedrock model integration, and a deploy pipeline — all wired up. The key file is  app/BillExplainer/main.py , which defines the agent's entry point.

Generating realistic billing data

An agent is only as useful as the data it can work with. Rather than connecting to a real AWS billing account (which requires organization-level access and CUR setup), we generated synthetic Cost & Usage Report data that mirrors the real thing.
The data generator ( generate_data.py ) creates a realistic multi-account AWS environment:
Account
Name
Purpose
111111111111
Production
Largest spender — EC2, RDS, ECS, CloudFront
222222222222
Development
Small footprint — but with an idle RDS instance
333333333333
Staging
Mirrors production at ~40% scale
444444444444
DataAnalytics
Heavy S3 and compute usage
Across 4 months (May–August 2026), 8 AWS services, 3 regions, and 4 project tags, the generator produces ~5,700 daily line items with realistic cost patterns. Critically, it also embeds 5 deliberate anomalies for the agent to find:
  1. GPU instance spike — DataAnalytics account spins up r5.xlarge instances at 3.2x normal in August
  1. New GPU usage — Production account starts using p3.2xlarge instances in July (didn't exist before)
  1. S3 data transfer surge — DataAnalytics cross-region transfers increase 2.5x (a data-sharing initiative)
  1. Lambda invocation doubling — Production Lambda usage jumps 2.1x in August (new feature rollout)
  1. Idle RDS instance — Development account's db.t3.medium runs unchanged for 4 months with zero growth
The data lives in DuckDB — a fast, embedded analytical database that runs inside the agent's process. No infrastructure to manage, no database server to connect to.
DB_PATH = os.path.join(os.path.dirname(__file__), "data", "billing.duckdb")


Building the tools

Strands agents use Python functions decorated with  @tool  to interact with the world. We built three tools for Phase 1:
Tool 1:  get_billing_schema  — The agent's first move in any analysis. Returns the database schema, date ranges, available accounts, services, regions, and usage types. This gives the LLM the context it needs to write accurate SQL.
Tool 2:  query_billing_data  — The workhorse. Accepts any read-only SQL query and runs it against DuckDB. The tool includes safety guardrails:
@tool
def query_billing_data(sql_query: str) -> dict:
normalized = sql_query.strip().rstrip(";").upper()
if not normalized.startswith("SELECT") and not normalized.startswith("WITH"):
return {"error": "Only SELECT queries are allowed."}

for keyword in ["INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "CREATE", "TRUNCATE"]:
if keyword in normalized.split():
return {"error": f"Write operations ({keyword}) are not allowed."}
...

Only SELECT and WITH (CTE) queries are permitted. Any attempt to modify data is blocked at the tool level.
Tool 3:  get_optimization_recommendations  — A knowledge base of AWS cost optimization strategies, organized by service and finding type. When the agent identifies that EC2 GPU instances spiked, it calls this tool and receives targeted advice: "Consider SageMaker Training Jobs for burst ML workloads (pay only for training time)" and "Use Spot for training jobs with checkpointing (60–90% savings on GPU instances)."

The system prompt: Teaching the agent to be a FinOps analyst

The system prompt is where the real magic happens. Rather than telling the model to "analyze costs," we gave it a structured 8-step analysis workflow:
Step 1: Understand the data → call get_billing_schema
Step 2: Get the big picture → query total monthly spend trends
Step 3: Identify cost drivers → break down by service and account
Step 4: Find significant changes → compare month-over-month
Step 5: Run anomaly detection → call detect_cost_anomalies
Step 6: Investigate anomalies → drill down with targeted queries
Step 7: Generate recommendations → call get_optimization_recommendations
Step 8: Produce executive summary → synthesize findings

This workflow guides the agent through the same process an experienced FinOps engineer would follow — but it executes in seconds, not hours.

First run

agentcore dev
agentcore invoke "Why did our AWS bill go up this month?"

The agent came alive. It called  get_billing_schema , wrote SQL to compare monthly totals, identified the top cost drivers, and produced a structured analysis with dollar amounts and percentages. Phase 1 was complete.



Phase 2: Anomaly Detection and a Chat UI

Statistical anomaly detection with z-scores

Manual cost comparison is fine for obvious changes, but what about subtle shifts that accumulate over time? We added a  detect_cost_anomalies  tool that applies statistical analysis to every service and account combination.
The approach uses z-scores — a measure of how many standard deviations a value is from the mean. The tool runs three queries:
Query 1: Service-level anomalies. For each AWS service, it computes the average and standard deviation of monthly costs over a lookback period (default: 3 months), then flags the current month if its z-score exceeds the sensitivity threshold (default: 2.0).
WITH monthly AS (
SELECT line_item_product_code AS service,
DATE_TRUNC('month', line_item_usage_start_date) AS month,
ROUND(SUM(line_item_unblended_cost), 2) AS cost
FROM cost_and_usage
GROUP BY 1, 2
),
baseline AS (
SELECT m.service,
AVG(m.cost) AS avg_cost,
STDDEV_POP(m.cost) AS std_cost
FROM monthly m, latest l
WHERE m.month < l.latest_month
AND m.month >= l.latest_month - INTERVAL '3' MONTH
GROUP BY 1
),
current AS (
SELECT m.service, m.cost AS current_cost
FROM monthly m, latest l
WHERE m.month = l.latest_month
)
SELECT c.service, c.current_cost, b.avg_cost, b.std_cost,
(c.current_cost - b.avg_cost) / GREATEST(b.std_cost, 0.01) AS z_score
FROM current c JOIN baseline b ON c.service = b.service
WHERE ABS(z_score) > 2.0

Query 2: Account+service anomalies. The same analysis, but at a finer granularity — each account-service pair gets its own baseline.
Query 3: New usage types. Sometimes cost increases come from entirely new resource types. This query finds usage types in the current month that didn't appear in any prior month — like GPU instances that were just launched.
The result: the agent doesn't just compare totals — it scientifically identifies which changes are statistically significant versus normal variance.

Building the Streamlit chat UI

A CLI is great for testing, but stakeholders want a chat interface. We built one with Streamlit in a single file ( ui/app.py ):
┌─────────────────────────────────────────────────────────────┐
│ 💰 AWS Bill Explainer │
│ FinOps assistant powered by Amazon Bedrock AgentCore │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────┐ ┌────────────────────────────┐ │
│ │ Why did our AWS bill │ │ Which accounts are │ │
│ │ go up this month? │ │ spending the most? │ │
│ └───────────────────────┘ └────────────────────────────┘ │
│ ┌───────────────────────┐ ┌────────────────────────────┐ │
│ │ Run anomaly detection │ │ What are our top cost │ │
│ │ and show me anything │ │ optimization opportunities?│ │
│ │ unusual │ │ │ │
│ └───────────────────────┘ └────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Ask about your AWS bill... │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ Sidebar: │
│ ├── About │
│ ├── Capabilities │
│ ├── Exported Reports (download buttons) │
│ └── Session controls │
│ │
└─────────────────────────────────────────────────────────────┘

The UI connects to the agent via SSE (Server-Sent Events), streaming responses token by token. Starter prompts help new users understand what kinds of questions they can ask.
AGENT_URL = os.getenv("AGENT_URL", "http://localhost:8081")

def invoke_agent(prompt: str) -> str:
resp = requests.post(
f"{AGENT_URL}/invocations",
json={"prompt": prompt},
headers={"Content-Type": "application/json",
"x-session-id": st.session_state.session_id},
stream=True,
timeout=180,
)
full_text = ""
for line in resp.iter_lines(decode_unicode=True):
if line.startswith("data: "):
data = json.loads(line[6:])
text = data.get("event", {}).get("contentBlockDelta", {}) \
.get("delta", {}).get("text", "")
if text:
full_text += text
return full_text

Start it up:
streamlit run ui/app.py --server.port 8502 --server.address 0.0.0.0




Phase 3: Deploy, Memory, and Executive Summaries

Deploying to AgentCore

With the agent working locally, deploying to AWS was a single command:
agentcore deploy -y

Behind the scenes, AgentCore:
  1. Packages the Python code as a CodeZip artifact
  1. Creates a CDK stack with the runtime, IAM roles, and networking
  1. Deploys to a managed runtime environment
  1. Returns a REST endpoint for invocation
The deployed runtime runs on  PYTHON_3_14  with  PUBLIC  network mode, accessible via the AgentCore API or  agentcore invoke .

Adding cross-session memory

The most impactful Phase 3 addition was memory. Without it, every conversation starts from scratch. With memory, the agent accumulates institutional knowledge:
  • "Last analysis showed EC2 at $15,600 — it's now $16,200, a 3.8% increase"
  • "The idle RDS instance in Development that I flagged two weeks ago is still running"
  • "S3 data transfer anomaly in DataAnalytics has continued to grow since my first detection"
We configured two memory strategies in  agentcore.json :
"memories": [{
"name": "BillingMemory",
"eventExpiryDuration": 30,
"strategies": [
{
"type": "SEMANTIC",
"namespaceTemplates": ["/users/{actorId}/facts"]
},
{
"type": "SUMMARIZATION",
"namespaceTemplates": ["/summaries/{actorId}/{sessionId}"]
}
]
}]

SEMANTIC memory extracts discrete facts from conversations — cost baselines, anomalies found, recommendations given — and stores them in a per-user namespace. On subsequent invocations, the agent retrieves relevant facts based on semantic similarity to the current query.
SUMMARIZATION memory compresses long conversation histories into summaries, preventing context window overflow during extended analysis sessions.
The code gracefully handles the local-vs-deployed gap — memory is only available after deployment (the  MEMORY_BILLINGMEMORY_ID  environment variable is set by AgentCore). Locally, the agent runs without memory:
MEMORY_ID = os.getenv("MEMORY_BILLINGMEMORY_ID")

if MEMORY_ID:
from bedrock_agentcore.memory.integrations.strands.config import (
AgentCoreMemoryConfig, RetrievalConfig
)
from bedrock_agentcore.memory.integrations.strands.session_manager import (
AgentCoreMemorySessionManager
)


Executive summary export

The final tool lets the agent produce shareable reports. After completing an analysis, the agent can export its findings as:
  • Markdown — clean, portable, works in any documentation system
  • HTML — styled with AWS-themed CSS for executive presentations (dark headers, orange accents, print-friendly layout)
  • JSON — structured data for programmatic consumption
@tool
def export_executive_summary(title: str, summary_markdown: str, format: str = "markdown") -> dict:
"""Export the billing analysis as a downloadable executive summary."""
...

The HTML output includes responsive styling that looks professional in a browser and prints cleanly:
h1 { color: #232f3e; border-bottom: 3px solid #ff9900; padding-bottom: 10px; }
th { background: #232f3e; color: white; }
strong { color: #d13212; } /* AWS red for emphasis */

A lightweight file server ( export_server.py ) serves the generated reports, and the Streamlit sidebar shows download buttons for all exported files.



The Agent in Action

Here's what happens when you ask: "Why did our AWS bill go up this month?"
┌──────────────────────────────────────────────────────────────┐
│ Agent Execution Flow │
│ │
│ User: "Why did our AWS bill go up this month?" │
│ │
│ Step 1 ─── get_billing_schema() ────────────────────────── │
│ │ Discovers: 4 accounts, 8 services, 4 months │
│ │ Date range: May–August 2026 │
│ ▼ │
│ Step 2 ─── query_billing_data() ────────────────────────── │
│ │ SQL: Monthly totals → May: $18.2K, Jun: $19.1K, │
│ │ Jul: $21.4K, Aug: $25.8K (+20.6% MoM) │
│ ▼ │
│ Step 3 ─── query_billing_data() ────────────────────────── │
│ │ SQL: Cost by service → EC2 #1, S3 #2, RDS #3 │
│ │ SQL: Cost by account → Production #1 │
│ ▼ │
│ Step 4 ─── query_billing_data() ────────────────────────── │
│ │ SQL: MoM change by service │
│ │ EC2: +$2,100 (+28%), Lambda: +$380 (+110%) │
│ ▼ │
│ Step 5 ─── detect_cost_anomalies() ─────────────────────── │
│ │ 3 service anomalies (z > 2.0) │
│ │ 5 account-service anomalies │
│ │ 2 new usage types │
│ ▼ │
│ Step 6 ─── query_billing_data() (×3) ───────────────────── │
│ │ Drill into each anomaly: │
│ │ • DataAnalytics EC2 → r5.xlarge at 3.2x │
│ │ • Production EC2 → new p3.2xlarge GPU instances │
│ │ • DataAnalytics S3 → cross-region transfer 2.5x │
│ ▼ │
│ Step 7 ─── get_optimization_recommendations() (×3) ─────── │
│ │ EC2 GPU: Spot instances, SageMaker, rightsizing │
│ │ S3 Transfer: VPC endpoints, CloudFront │
│ │ Lambda: Graviton, batching, memory tuning │
│ ▼ │
│ Step 8 ─── Synthesize findings ──────────────────────────── │
│ │ │
│ ▼ "Your AWS bill increased from $21,400 to $25,800 │
│ (+20.6%). The main drivers are: │
│ 1. DataAnalytics EC2 (+$2,100) — new ML training │
│ cluster running r5.xlarge at 3.2x baseline │
│ 2. Production EC2 (+$1,050) — p3.2xlarge GPU │
│ instances launched in July for the first time │
│ 3. DataAnalytics S3 transfer (+$620) — cross- │
│ region data sharing at 2.5x baseline │
│ ..." │
└──────────────────────────────────────────────────────────────┘

The entire analysis — 10+ tool calls, dozens of SQL queries, statistical analysis, and a structured report — completes in under 30 seconds.



Key Design Decisions

Why DuckDB instead of Athena or Redshift?

DuckDB runs embedded inside the agent process. No infrastructure to manage, no query costs, sub-second latency. For a billing dataset that fits in memory (most organizations' monthly CUR data does), it's the fastest path from "I have data" to "I have answers." The agent can run complex analytical queries — window functions, CTEs, statistical aggregations — without any external dependencies.

Why z-scores for anomaly detection?

Z-scores are simple to explain ("this value is 3.2 standard deviations above the mean"), don't require training data, and work well for time-series data with a short baseline. The sensitivity parameter lets users tune the threshold — a z-score of 2.0 catches ~95% of true anomalies, while 1.5 is more aggressive and 3.0 is more conservative.

Why both SEMANTIC and SUMMARIZATION memory?

They serve different purposes. SEMANTIC memory extracts and retrieves discrete facts ("EC2 baseline was $12,400 in July"). SUMMARIZATION memory compresses long conversations so the agent maintains context during extended analysis sessions without exceeding the context window. Together, they give the agent both long-term recall and in-session coherence.

Why CodeZip instead of Container?

CodeZip deploys faster (no Docker build), requires no local Docker installation, and is simpler to iterate on. For a Python agent with pip-installable dependencies (DuckDB, Strands, Bedrock SDK), there's no reason to use a container. If we needed custom system libraries or a non-Python runtime, Container would be the right choice.



Project Structure

BillExplainer/
├── agentcore/
│ ├── agentcore.json # Project config — runtime, memory, resources
│ └── aws-targets.json # AWS account + region for deployment
├── app/BillExplainer/
│ ├── main.py # Agent entry point — system prompt, tool wiring, memory
│ ├── billing_tools.py # 4 tools: schema, SQL query, anomaly detection, recommendations
│ ├── export_tool.py # Executive summary export (MD/HTML/JSON)
│ ├── export_server.py # Lightweight HTTP server for report downloads
│ ├── generate_data.py # Synthetic CUR data generator
│ ├── model/load.py # Bedrock model configuration (Claude Sonnet)
│ ├── data/billing.duckdb # Generated billing database
│ └── pyproject.toml # Python dependencies
└── ui/
└── app.py # Streamlit chat interface




Dependencies

The agent uses a minimal set of dependencies:
dependencies = [
"aws-opentelemetry-distro", # Tracing and observability
"bedrock-agentcore >= 1.9.1", # AgentCore runtime SDK + memory
"botocore[crt] >= 1.35.0", # AWS SDK
"duckdb >= 1.0.0", # Embedded analytical database
"mcp ~= 1.24.0", # Model Context Protocol
"strands-agents >= 1.15.0", # Agent framework
]

No heavyweight ML frameworks, no external databases, no complex infrastructure.



Deploying It Yourself

Prerequisites

  • AWS CLI configured with credentials
  • Amazon Bedrock access enabled (Claude Sonnet model)
  • AgentCore CLI installed ( npm install -g @aws/agentcore )
  • Python 3.10+ with  uv  for environment management

Steps

# 1. Create the project
agentcore create --name BillExplainer --framework Strands \
--model-provider Bedrock --build CodeZip --memory none

# 2. Add your tools (billing_tools.py, export_tool.py)
# 3. Generate synthetic data
cd app/BillExplainer
uv venv && source .venv/bin/activate
uv pip install -r requirements.txt
python generate_data.py

# 4. Test locally
agentcore dev
# In another terminal:
agentcore invoke "What does our billing look like?"

# 5. Add memory (optional)
agentcore add memory --name BillingMemory

# 6. Deploy
agentcore deploy -y

# 7. Invoke the deployed agent
agentcore invoke "Why did our bill go up?"


Running the UI

pip install streamlit requests
streamlit run ui/app.py --server.port 8502 --server.address 0.0.0.0




What We'd Add Next

This agent is production-ready for demo and internal use. To take it further:
  • Connect to real CUR data — Replace the DuckDB data generator with an S3-backed CUR export, or point at Athena for organizations with existing CUR pipelines
  • Scheduled analysis — Run the agent on a cron to produce weekly cost reports automatically
  • Slack/Teams integration — Deliver anomaly alerts directly to FinOps channels
  • Multi-org support — Extend memory namespaces for different teams and business units
  • Budget threshold alerts — Combine anomaly detection with AWS Budgets for proactive notification
  • Evaluation suite — Use AgentCore evaluators to measure analysis quality against known anomalies



Conclusion

The gap between "we have cost data" and "we understand our costs" has always been filled by human analysts spending hours in dashboards. With Amazon Bedrock AgentCore, we built an agent that closes that gap in seconds — one that queries data, applies statistical analysis, generates recommendations, remembers what it found last time, and produces executive-ready reports.
The total build time was under an hour. The agent runs on managed infrastructure with zero servers to maintain. And the next time someone asks "why did our bill go up?" — we just ask the agent.
Technologies used: Amazon Bedrock AgentCore, Strands Agents, DuckDB, Amazon Bedrock (Claude Sonnet), Streamlit, Python


Built during the Amazon Bedrock AgentCore Builder Workshop.
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