17. Agentic AI on AWS (Weekend Sessions)#
A fast, conceptual revision guide for 01-weekend-sessions covering the full lifecycle of production AI agents on AWS — from a first Strands/LangGraph agent and tool design to memory, multi-agent architectures, MCP/A2A protocols, cloud deployment, and evaluation, observability, and governance.
Your First AI Agent: From Plain LLMs to the Agentic Loop#
Revision Notes#
Reference files: weekend-sessions-notes/01-Your First AI Agent.html, section-01-your-first-agent/01_hello_agent.ipynb, hello_agent.py, hello_langgraph_agent.py (plus *_groq twins)
Concept#
A standalone LLM is like a brilliant student locked inside an exam hall: its knowledge is frozen at training time, it cannot see your private company data, it guesses when uncertain, and it can only output text — never take action. Retraining or fine-tuning is slow, expensive, and goes stale immediately. Two lighter patterns break the model out without retraining:
- RAG (Retrieval Augmented Generation) — "Slipping the right pages under the door." Before answering, retrieve relevant facts from external documents and inject them into the prompt so the model knows more.
- AI Agents — "Giving the student a phone, laptop, and permission to act." Pair an LLM with tools and a reasoning loop so it can plan, act, observe results, and iterate until the goal is achieved.
How It Works#
Instead of answering in a single frozen pass, the Strands coordinator loops between Amazon Bedrock reasoning and Python @tool execution until stop_reason signals end_turn.
Key Mental Models#
- The 7-step RAG pipeline: Ingest documents → Chunk into manageable pieces → Embed into vectors (meaning as distance) → Store in a vector database → Retrieve top matches → Filter/rerank (optional) → Generate grounded answer.
- Six-stage evolution of agentic systems:
- Stage 1 — Plain LLM: Single prompt in, text out.
- Stage 2 — LLM + RAG (and Agentic RAG): Traditional RAG always retrieves once; Agentic RAG lets the model decide whether, what, and how many times to retrieve.
- Stage 3 — Augmented LLM: Model enhanced with retrieval, tools, and memory.
- Stage 4 — Agentic Workflow: Model follows developer-defined control paths (deterministic orchestration).
- Stage 5 — Autonomous Agent: Model dynamically decides its own next tool calls in a loop until done.
- Stage 6 — Multi-Agent Collaboration: Specialized agents coordinate to tackle complex tasks.
- The AWS agentic stack (3 tiers):
- Agentic applications: Ready-to-use SaaS/AWS apps.
- Managed solutions: Amazon Bedrock, Bedrock Knowledge Bases, and Amazon Bedrock AgentCore (serverless model access + agent infrastructure).
- Do-it-yourself (DIY): Amazon SageMaker AI when you need custom model training, specialized hosting, or full infrastructure control.
- Choosing a framework (Strands vs. LangChain vs. LangGraph):
- Strands Agents SDK (
Agent(model, tools, system_prompt)): Agent-first, minimal boilerplate, AWS-native, built-in agent loop and session/memory hooks. - LangChain: Rich library of modular building blocks (loaders, parsers, prompts, integrations) for RAG pipelines and chains.
- LangGraph (
create_agent): Explicit stateful graph orchestration with built-in checkpointers, ideal for complex branching, loops, and human-in-the-loop flows.
- Strands Agents SDK (
- Model routing & portability: Bedrock uses cross-Region inference profiles (e.g.,
global.anthropic.claude-sonnet-4-6,global.anthropic.claude-haiku-4-5-20251001-v1:0) for automatic routing. Because Strands supportsOpenAIModel, swapping Bedrock for Groq (*_groqtwins) or local Ollama changes only the model configuration — the agent and tool code stay identical.
Code Reference#
import os
# Cross-region inference profile ID ("global.*") lets Bedrock route traffic across
# regions automatically for higher availability and throughput.
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
os.environ.setdefault("AWS_REGION", REGION)
print(f"Model : {MODEL_ID}")
print(f"Region: {REGION}")
# --- next cell ---
from strands import Agent
from strands.models.bedrock import BedrockModel
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
# Minimal Strands agent: wraps the model in an agentic loop that can optionally
# invoke tools and preserve multi-turn conversation state.
agent = Agent(model=model)
response = agent("Explain Amazon Bedrock AgentCore in three sentences.")
# -> AgentResult(stop_reason='end_turn',
# message={'role': 'assistant', 'content': [{'text': 'Amazon Bedrock AgentCore is ...'}]},
# metrics=EventLoopMetrics(accumulated_usage={'inputTokens': 24, 'outputTokens': 61, 'totalTokens': 85}))
# --- next cell ---
# Inspecting stop_reason and token usage verifies whether the model finished cleanly
# ("end_turn") vs. hit max_tokens, and lets you estimate Bedrock call cost.
print("Stop reason:", response.stop_reason)
print("Tokens used:", response.metrics.accumulated_usage)
# --- next cell ---
from datetime import datetime
from zoneinfo import ZoneInfo
from strands import tool
# @tool converts a Python function into a Bedrock tool spec using its type hints
# and docstring Args section so the LLM knows when and how to call it.
@tool
def current_time(timezone: str = "Asia/Kolkata") -> str:
"""Get the current date and time in a given IANA timezone.
Args:
timezone: IANA timezone name, for example "Asia/Kolkata" or "America/New_York".
"""
return datetime.now(ZoneInfo(timezone)).strftime("%A, %d %B %Y %I:%M %p %Z")
# Giving the agent real-time tools overcomes the LLM's static training cutoff.
agent = Agent(model=model, tools=[current_time])
agent("What time is it right now in Bangalore and in New York?")
# -> dispatches current_time('Asia/Kolkata') & current_time('America/New_York')
# -> 'Saturday, 14 March 2026 07:30 PM IST' & 'Saturday, 14 March 2026 10:00 AM EDT'
# --- next cell ---
# Built-in community tools (strands_tools) can be mixed freely with custom @tool functions.
from strands_tools import calculator
agent = Agent(model=model, tools=[calculator, current_time])
agent("What is 18% GST on a laptop that costs Rs 84,999? Give me the final price too.")
# -> dispatches calculator('84999 * 0.18') -> 15299.82, then calculator('84999 + 15299.82') -> 100298.82
# --- next cell ---
agent = Agent(
model=model,
# ... (see full file: 01_hello_agent.ipynb)
Model : global.anthropic.claude-sonnet-4-6
Region: us-east-1
Amazon Bedrock AgentCore is a managed platform for deploying, scaling, and operating AI agents securely in production. It provides modular services including serverless Runtime, persistent Memory, Gateway for tools/MCP, Identity, and Observability. Together, they let teams move Strands or LangGraph prototypes to enterprise production without managing infrastructure.
Stop reason: end_turn
Tokens used: {'inputTokens': 24, 'outputTokens': 61, 'totalTokens': 85}
Tool #1: current_time({'timezone': 'Asia/Kolkata'})
Tool #2: current_time({'timezone': 'America/New_York'})
Right now it is Saturday, 14 March 2026 07:30 PM IST in Bangalore and Saturday, 14 March 2026 10:00 AM EDT in New York.
Tool #1: calculator({'expression': '84999 * 0.18'})
Tool #2: calculator({'expression': '84999 + 15299.82'})
18% GST on ₹84,999 is ₹15,299.82, bringing the final price to ₹100,298.82.
"""Section 1: Hello World agent with the Strands Agents SDK on Amazon Bedrock.
Run:
python hello_agent.py
"""
import os
from strands import Agent
from strands.models.bedrock import BedrockModel
# Reading model and region from env vars keeps secrets/config out of source control
# and lets you swap models (e.g., Haiku for lower cost) without editing code:
# export BEDROCK_MODEL_ID=global.anthropic.claude-haiku-4-5-20251001-v1:0
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
# BedrockModel authenticates via the standard AWS credential chain (env, ~/.aws, IAM role).
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
agent = Agent(model=model)
# Strands streams tokens to stdout by default during agent(...), and returns an
# AgentResult whose __str__ gives the final assembled response text.
response = agent("Hello! Tell me a fun fact about AI agents.")
print()
print("-" * 60)
print(response)
Here's a fun fact: the term "agent" in AI dates back to the 1950s–1990s (long before LLMs), defined as any system that perceives its environment through sensors and acts on it through actuators!
------------------------------------------------------------
Here's a fun fact: the term "agent" in AI dates back to the 1950s–1990s (long before LLMs), defined as any system that perceives its environment through sensors and acts on it through actuators!
Giving Agents Tools: Custom, Prebuilt, AWS, and Advanced Patterns#
Revision Notes#
Reference files: weekend-sessions-notes/02-Giving Agents Tools.html, section-02-agent-tools/01_building_tools.ipynb, 02_prebuilt_and_aws_tools.ipynb, 03_advanced_tool_patterns.ipynb
Concept#
Tools turn a model from a passive talker into an active operator. In the Brain – Coordinator – Hands model, the LLM is the brain (understands intent and chooses actions), the agent framework is the coordinator (runs the loop and executes functions), and tools are the hands (fetch live data, run exact math, mutate state, or call cloud APIs).
Key Mental Models#
- The three ingredients of
@tool: Decorating a Python function exposes a schema to the LLM built from three essential parts:- Function name — Identifies the capability (e.g.,
calculate_tip). - Type hints & defaults — Tells the model exact parameter types and optional arguments (e.g.,
timezone: str = "Asia/Kolkata"). - Docstring — Tells the model when to invoke the tool and what each argument means. Removing any of these three degrades tool selection or argument extraction.
- Function name — Identifies the capability (e.g.,
- Why agents beat regex chatbots: A regex chatbot breaks on phrasing variations ("how many laptops left?" vs. "check stock for SKU-101"). A tool-using agent interprets natural-language intent, extracts structured arguments, calls the tool, and formats a helpful reply.
- Prebuilt & AWS-native tools (
strands-agents-tools):- Community prebuilt tools:
calculator,http_request,file_write,current_timelet you compose multi-tool workflows without reinventing basics. use_aws: Gives an agent controlled access to AWS services via boto3 — demonstrated across S3 (data analysis), DynamoDB (customer lookups), and Lambda (workflow orchestration) directly from plain-English requests.
- Community prebuilt tools:
- Advanced tool patterns when plain functions aren't enough:
- Class-based tools (the DB connection problem): Plain stateless functions open and close a fresh database connection on every tool call. Wrapping tools inside a class lets you initialize a shared connection pool once in
__init__and reuse it safely across calls. - Async tools (concurrent I/O): Synchronous tools run one after another (total time = sum of calls). Defining
async deftools allows the framework to execute independent I/O calls (such as querying three warehouses) concurrently so total latency equals only the slowest call.
- Class-based tools (the DB connection problem): Plain stateless functions open and close a fresh database connection on every tool call. Wrapping tools inside a class lets you initialize a shared connection pool once in
- Strands Agent Builder: An interactive meta-agent that can scaffold, test, and iterate on custom tools and agents directly from natural-language descriptions.
Trade-Offs & Pitfalls#
- Model-specific tool quirks: Not all LLMs emit parallel tool calls reliably (for example, some smaller models request one tool per turn instead of batching async calls, or invent default parameters like
profile_name="default"foruse_awsunless constrained). - Always unit-test tools in isolation: Verify a
@toolfunction directly in Python before handing it to an agent so you separate tool bugs from LLM reasoning bugs.
Code Reference#
import os
from strands.models.bedrock import BedrockModel
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
os.environ.setdefault("AWS_REGION", REGION)
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
print(f"Using {MODEL_ID} in {REGION}")
# --- next cell ---
import requests
# Plain Python function first: always verify tool logic independently before exposing
# it to an LLM so network or parsing bugs aren't confused with prompt issues.
def check_server_status_plain(server_url):
"""Check if a server is responding."""
try:
# Always set a timeout so a hung endpoint cannot stall the agent loop forever.
response = requests.get(server_url, timeout=5)
return f"Server is up. Status code: {response.status_code}"
except requests.exceptions.RequestException:
# Returning a readable string instead of raising lets the LLM explain the outage.
return "Server is down or unreachable"
print(check_server_status_plain("https://httpbin.org/get"))
# --- next cell ---
from strands import Agent, tool
# Promoting the function to an agent tool requires three things:
# 1. @tool decorator, 2. explicit type hints, 3. a docstring describing Args/Returns.
@tool # Decorator
def check_server_status(server_url: str) -> str: # Type hints
"""Check if a server is responding by making an HTTP request.
Args:
server_url: The URL of the server to check
Returns:
A message indicating whether the server is up or down
"""
try:
response = requests.get(server_url, timeout=5)
return f"Server is up. Status code: {response.status_code}"
except requests.exceptions.RequestException:
return "Server is down or unreachable"
# --- next cell ---
# The LLM extracts the URL from natural language, invokes check_server_status,
# reads the returned string, and synthesizes a user-friendly status report.
agent = Agent(model=model, tools=[check_server_status])
response = agent("Is the staging server running? Check https://httpbin.org/get")
# -> dispatches check_server_status({'server_url': 'https://httpbin.org/get'})
# -> 'Server is up. Status code: 200' -> AgentResult(stop_reason='end_turn', ...)
# --- next cell ---
@tool
def calculate_tip(bill_amount: float, tip_percentage: float, num_people: int = 1) -> dict:
"""Calculate tip and split the bill among people.
# ... (see full file: 01_building_tools.ipynb)
Using global.anthropic.claude-sonnet-4-6 in us-east-1
Server is up. Status code: 200
Tool #1: check_server_status({'server_url': 'https://httpbin.org/get'})
Yes, the staging server at https://httpbin.org/get is up and responding with HTTP status code 200.
import os
from strands.models.bedrock import BedrockModel
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
os.environ.setdefault("AWS_REGION", REGION)
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
print(f"Using {MODEL_ID} in {REGION}")
# --- next cell ---
from strands import Agent
from strands_tools import calculator
# strands_tools.calculator uses SymPy under the hood, handling exact big-integer
# powers, algebraic equation solving, and symbolic calculus reliably.
agent = Agent(model=model, tools=[calculator], system_prompt="You are a helpful math assistant.")
agent("What's 42 raised to the power of 9?")
# -> calculator({'expression': '42**9'}) -> 406671383849472
agent("Solve the equation x^2 + 5x + 6 = 0")
# -> calculator({'expression': 'x^2 + 5*x + 6', 'mode': 'solve'}) -> [-3, -2]
agent("What's the derivative of sin(x) * cos(x)?")
# -> calculator({'expression': 'sin(x) * cos(x)', 'mode': 'derive'}) -> cos(x)^2 - sin(x)^2
# --- next cell ---
from strands_tools import file_write, http_request
# file_write prompts for interactive stdin confirmation by default as a safety guard;
# setting BYPASS_TOOL_CONSENT="true" allows unattended notebook execution.
os.environ["BYPASS_TOOL_CONSENT"] = "true"
# Chaining 3 prebuilt tools (fetch -> compute -> persist) shows how an agent plans
# a multi-step data pipeline autonomously from a single natural-language goal.
agent = Agent(
model=model,
tools=[http_request, calculator, file_write],
system_prompt="You help with data analysis tasks.",
)
agent("""
Fetch the 7-day forecast from
https://api.open-meteo.com/v1/forecast?latitude=12.97&longitude=77.59&daily=temperature_2m_max,temperature_2m_min&timezone=Asia/Kolkata
extract the daily maximum temperatures for Bangalore,
calculate the average maximum temperature over the period,
and save a short summary to weather_summary.txt
""")
# -> chains: http_request(GET open-meteo) -> calculator('(32.4+...+32.7)/7') = 32.63
# -> file_write(path='weather_summary.txt', content='Bangalore 7-Day Forecast Summary...')
# --- next cell ---
if os.path.exists("weather_summary.txt"):
print(open("weather_summary.txt").read())
else:
print("No weather_summary.txt yet — scroll up to see which tools the agent called.")
# --- next cell ---
import csv
import io
import json
import time
import zipfile
import boto3
# ... (see full file: 02_prebuilt_and_aws_tools.ipynb)
Using global.anthropic.claude-sonnet-4-6 in us-east-1
Tool #1: calculator({'expression': '42**9'})
42^9 = 406,671,383,849,472
Tool #2: calculator({'expression': 'x^2 + 5*x + 6', 'mode': 'solve'})
The solutions are x = -3 and x = -2.
Tool #3: calculator({'expression': 'sin(x) * cos(x)', 'mode': 'derive'})
The derivative is cos(x)^2 - sin(x)^2 (equivalently, cos(2x)).
Tool #1: http_request({'method': 'GET', 'url': 'https://api.open-meteo.com/v1/forecast?...'})
Tool #2: calculator({'expression': '(32.4 + 33.1 + 32.8 + 31.9 + 32.5 + 33.0 + 32.7) / 7'})
Tool #3: file_write({'path': 'weather_summary.txt', 'content': '...'})
Bangalore 7-Day Forecast Summary
Daily Max Temperatures (°C): 32.4, 33.1, 32.8, 31.9, 32.5, 33.0, 32.7
Average Maximum Temperature: 32.63°C
Agents That Remember: Memory, Context Management, and AgentCore Memory#
Revision Notes#
Reference files: weekend-sessions-notes/03-Agents That Remember.html, section-03-agent-memory/01_personalized_memory_mem0.ipynb, 02-langgraph-agentcore-memory/math_agent_with_checkpointing.ipynb
Concept#
Without memory, every prompt starts from zero — the agent forgets what you said two turns ago, ignores user preferences, and repeats mistakes. Memory gives an agent contextual intelligence, personalization, and knowledge retention, turning isolated Q&A turns into continuous, evolving relationships.
How It Works#
Key Mental Models#
- Short-term vs. long-term memory:
- Short-term (working) memory: Recent conversation turns and intermediate tool states scoped to a single session. Fast, but bounded by the context window.
- Long-term memory: Persists across sessions and restarts, divided into three types:
- Episodic: Specific past events and interactions ("last Tuesday the user asked for a refund").
- Semantic: Distilled facts and user preferences ("Mona is vegetarian and prefers aisle seats").
- Procedural: Learned workflows, rules, and how-to instructions that guide future behavior.
- Why memory is hard: Production memory must solve six challenges simultaneously — storage scalability, refreshing stale/contradictory facts, integration across stores, strict privacy/isolation, retrieval accuracy, and observability into what was recalled.
- Personalized memory with Mem0 & hard isolation:
Mem0MemoryTool(user_id=...)extracts structured facts from conversation using an LLM, embeds them into a vector store (e.g., local FAISS + Titan v2 or local fastembed), and retrieves relevant memories on future turns.- Security boundary in code, not prompts: Binding
user_idinside the Python tool constructor guarantees User A can never read User B's memories — even under prompt injection. Cross-user access belongs only in a separate, explicitly privileged admin "super-agent."
- Context management & memory optimization strategies:
- Sequential (keep all): Simple, but hits token limits and degrades accuracy (context rot).
- Sliding window: Keeps only the last N turns; predictable cost, but forgets early instructions.
- Compaction / Summarization: Periodically condenses older turns into a concise summary.
- Structured note-taking: Agent writes explicit scratchpad/key-value notes outside the chat log.
- Retrieval-based (RAG) & Strategic forgetting: Fetch only relevant past memories on demand and decay or overwrite outdated facts.
- Sub-agent isolation: Offload noisy sub-tasks to sub-agents so only clean results enter the main context.
- Amazon Bedrock AgentCore Memory:
- Core hierarchy: Actors (whose memory) → Sessions (conversations) → Events (raw turns saved to short-term memory).
- Async LTM pipeline: Raw STM events trigger an Extraction module → Consolidation (merging/updating existing facts) → Embedding & Indexing into scoped Namespaces using built-in, overridden, or self-managed memory strategies.
- LangGraph checkpointer integration:
AgentCoreMemorySaver(memory_id, ...)plugs directly into LangGraph as a managed cloud checkpointer. Graph state is automatically saved/loaded at every step, surviving kernel/process restarts while keeping differentthread_id/ session IDs completely isolated.
Code Reference#
import os
import re
import shutil
import warnings
warnings.filterwarnings("ignore")
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
os.environ["AWS_REGION"] = REGION
# Mem0 calls Bedrock twice: an embedding model to index memories, and a small LLM
# (Haiku) that extracts/deduplicates facts from user turns at low cost.
os.environ.setdefault("MEM0_LLM_MODEL", "global.anthropic.claude-haiku-4-5-20251001-v1:0")
os.environ.setdefault("MEM0_EMBEDDER_MODEL", "amazon.titan-embed-text-v2:0")
# Skip the interactive "are you sure?" prompt when the agent stores memories
os.environ["BYPASS_TOOL_CONSENT"] = "true"
# Turn off Mem0's anonymous usage telemetry
os.environ["MEM0_TELEMETRY"] = "False"
# Keep Mem0's SQLite history database inside this course folder for easy cleanup
os.environ["MEM0_DIR"] = os.path.abspath(".mem0_course")
# Start from a clean slate: wipe the local FAISS vector index and Mem0 history
shutil.rmtree("/tmp/mem0_384_faiss", ignore_errors=True)
shutil.rmtree(os.environ["MEM0_DIR"], ignore_errors=True)
# Recreate the folder right away. Mem0 only creates it when it is first imported,
# so without this line, re-running this cell in the same kernel would leave Mem0
# with nowhere to put history.db ("unable to open database file").
os.makedirs(os.environ["MEM0_DIR"], exist_ok=True)
print("Ready")
# --- next cell ---
from ddgs import DDGS
from strands import Agent, tool
from strands.models.bedrock import BedrockModel
from strands.tools.executors import SequentialToolExecutor
from strands.tools.tools import PythonAgentTool
from strands_tools.mem0_memory import TOOL_SPEC as MEM0_TOOL_SPEC
from strands_tools.mem0_memory import Mem0MemoryTool, Mem0ServiceClient
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
# --- next cell ---
import importlib
import mem0.llms.aws_bedrock as mem0_bedrock
# Reload Mem0's Bedrock module first so any monkey-patch always wraps the ORIGINAL
# method. This makes the cell idempotent across re-runs and prevents recursive wrapping
# ("maximum recursion depth exceeded") in a live Jupyter kernel.
mem0_bedrock = importlib.reload(mem0_bedrock)
BedrockLLM = mem0_bedrock.AWSBedrockLLM
original_init_client = BedrockLLM._initialize_aws_client
# ... (see full file: 01_personalized_memory_mem0.ipynb)
Ready
# After patching AWSBedrockLLM and running the personalized Strands agent:
Tool #1: mem0_memory({'action': 'store', 'user_id': 'pankaj', 'content': 'Prefers vegetarian food and aisle seats'})
Stored memory successfully.
Tool #2: mem0_memory({'action': 'retrieve', 'user_id': 'pankaj', 'query': 'travel and food preferences'})
Retrieved: ["Prefers vegetarian food and aisle seats"]
import os
from bedrock_agentcore.memory import MemoryClient
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langgraph_checkpoint_aws import AgentCoreMemorySaver
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-haiku-4-5-20251001-v1:0")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
print(f"Model: {MODEL_ID} | Region: {REGION}")
# --- next cell ---
# Provision (or reuse) a managed AgentCore Memory store in AWS so conversation
# checkpoints persist outside the local Python process.
client = MemoryClient(region_name=REGION)
memory = client.create_or_get_memory(
name="MathLanggraphAgent",
description="Short-term memory for the LangGraph math agent",
)
# -> {'id': 'MathLanggraphAgent-9f3a2c1b', 'name': 'MathLanggraphAgent', 'status': 'ACTIVE', ...}
memory_id = memory["id"]
print("Memory ID:", memory_id, "| status:", memory.get("status"))
# --- next cell ---
# AgentCoreMemorySaver implements LangGraph's BaseCheckpointSaver interface,
# turning every graph state transition into a durable AgentCore Memory event.
checkpointer = AgentCoreMemorySaver(memory_id, region_name=REGION)
# "bedrock_converse" uses the unified Bedrock Converse API with native tool calling.
llm = init_chat_model(MODEL_ID, model_provider="bedrock_converse", region_name=REGION)
# --- next cell ---
@tool
def add(a: int, b: int) -> int:
"""Add two integers and return the result."""
return a + b
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers and return the result."""
return a * b
tools = [add, multiply]
# --- next cell ---
# Attaching checkpointer enables multi-turn memory and resumable execution per thread_id.
graph = create_agent(
model=llm,
tools=tools,
system_prompt="You are a helpful assistant. Use the tools for every calculation.",
checkpointer=checkpointer,
)
# -> CompiledStateGraph (persists each turn's messages & tool calls under thread_id in AgentCore Memory)
graph
# --- next cell ---
config = {
"configurable": {
"thread_id": "session-1", # REQUIRED: maps to AgentCore session_id
# ... (see full file: math_agent_with_checkpointing.ipynb)
Model: global.anthropic.claude-haiku-4-5-20251001-v1:0 | Region: us-east-1
Memory ID: MathLanggraphAgent-9f3a2c1b | status: ACTIVE
# Turn 1 (thread_id="session-1"): "Add 14 and 28"
-> Tool call: add(14, 28) = 42
-> Assistant: 14 + 28 = 42.
# Turn 2 (same thread_id="session-1"): "Now multiply that by 3"
-> Restored checkpoint from AgentCore Memory; Tool call: multiply(42, 3) = 126
-> Assistant: Multiplying 42 by 3 gives 126.
Multi-Agent Patterns: Designing Teams of Specialist Agents#
Revision Notes#
Reference files: weekend-sessions-notes/04-Agents That Work Together.html, section-04-multi-agent-patterns/01_supervisor_worker.ipynb, 02_agent_as_tool.ipynb, 03_graph_pattern.ipynb, 04_swarm_pattern.ipynb
Concept#
Stuffing every role, prompt rule, and tool into a single monolithic agent leads to context overload (context rot), diluted instructions ("jack of all trades, master of none"), sequential bottlenecks, and painful debugging. Multi-agent patterns split work across focused specialists with clear boundaries for who talks to whom, who controls execution order, and how outputs combine.
Key Mental Models#
- Three communication modes:
- Sequential: Agents run one after another (
A → B → C). Total latency = sum of all steps. - Parallel: Independent agents run concurrently. Total latency = slowest agent. Parallelism can also be used for voting/consensus, provided agents use diverse models, prompts, or data — five identical agents tend to make the exact same mistakes together.
- Collaborative: Agents critique and negotiate back and forth until constraints are met (e.g., code review loops).
- Sequential: Agents run one after another (
- The four core orchestration patterns:
- Supervisor–Worker (
01_supervisor_worker.ipynb): One central supervisor delegates subtasks to specialist workers (e.g., News, Financial, and Sentiment agents for market research) and synthesizes one final report. Workers stay independent and never talk directly to each other.- Trade-offs: Easy to debug and extend, but the supervisor is a latency bottleneck and a single point of failure.
- Agent as Tool (
02_agent_as_tool.ipynb): Wrap specialist agents (e.g.,math_tutor,writing_coach,science_helper) as callable tools for an orchestrator (teacher). Each specialist'snameanddescriptionbecome the tool schema the orchestrator reads.- Why it shines: Adding a new
history_tutorrequires zero changes to routingif-statements or other tutors — just register the new agent in the orchestrator's tool list.
- Why it shines: Adding a new
- Graph (
03_graph_pattern.ipynb): Developer explicitly defines nodes (agents/steps) and conditional edges (guard functions inspectingstate.results, e.g., via regex) in code. Demonstrated with e-commerce order processing (high-value → manual review; suspicious → fraud check; low-risk → fast-track; all converging on inventory → shipping or refund).- Why it shines: Deterministic, auditable, and provable for compliance (e.g., guaranteeing high-value orders always pass manual review). DAGs prevent infinite loops.
- Swarm (
04_swarm_pattern.ipynb): Decentralized, peer-to-peer handoffs with no central supervisor (e.g., four game-level-design specialists). Each agent sees the original task, shared history, and available peers, and either hands off control or finishes the run by completing its turn without handing off.- Guardrails: Prevent infinite "ping-pong" handoffs using
repetitive_handoff_detection_windowandrepetitive_handoff_min_unique_agents.
- Guardrails: Prevent infinite "ping-pong" handoffs using
- Supervisor–Worker (
Trade-Offs & Pitfalls#
- When multi-agent is NOT the answer: Do not default to a multi-agent team if a single well-prompted agent with 3–5 tools can solve the task cleanly. Reach for multi-agent only when the context window overflows, you need true parallelism, strict compliance routing is required, or distinct domains genuinely conflict in one prompt.
Code Reference#
import os
from strands.models.bedrock import BedrockModel
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
os.environ.setdefault("AWS_REGION", REGION)
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
print(f"Using {MODEL_ID} in {REGION}")
# --- next cell ---
from dotenv import load_dotenv
# Fail-soft configuration check: tells the learner upfront which external APIs
# are live vs. falling back to free yfinance data before running the multi-agent graph.
load_dotenv() # reads TAVILY_API_KEY (and ALPHA_VANTAGE_API_KEY) from a .env file, if present
# os.environ["TAVILY_API_KEY"] = "tvly-..."
# os.environ["ALPHA_VANTAGE_API_KEY"] = "..."
if not os.getenv("TAVILY_API_KEY"):
print("⚠️ TAVILY_API_KEY not set — the news and sentiment agents cannot search the web.")
else:
print("✓ TAVILY_API_KEY is configured")
if not os.getenv("ALPHA_VANTAGE_API_KEY"):
print("ℹ️ ALPHA_VANTAGE_API_KEY not set — financial data comes from yfinance (free, no key).")
else:
print("✓ ALPHA_VANTAGE_API_KEY is configured")
# --- next cell ---
import yfinance as yf
from strands import Agent, tool
from strands_tools.tavily import tavily_search
# --- next cell ---
def _num(value, money=False, pct=False):
"""Format numbers safely — Yahoo sometimes leaves fields empty."""
# Guarding against None/missing keys prevents TypeError crashes mid-tool-call.
if not isinstance(value, (int, float)):
return "N/A"
if pct:
return f"{value * 100:.2f}%"
return f"${value:,.2f}" if money else f"{value:,.2f}"
# Worker tool dedicated to structured market quotes; the supervisor delegates
# financial lookups to a specialist worker equipped with this tool.
@tool
def get_stock_price(symbol: str) -> str:
"""Get the current stock price and key metrics using Yahoo Finance.
Args:
symbol: Stock ticker symbol (e.g., 'AAPL', 'TSLA', 'MSFT')
"""
try:
info = yf.Ticker(symbol).info
# -> {'currentPrice': 228.45, 'marketCap': 3480120000000, 'fiftyTwoWeekHigh': 237.23, ...} (for 'AAPL')
return (
f"Stock: {symbol}\n"
f"Current Price: {_num(info.get('currentPrice') or info.get('regularMarketPrice'), money=True)}\n"
f"Market Cap: {_num(info.get('marketCap'), money=True)}\n"
# ... (see full file: 01_supervisor_worker.ipynb)
Using global.anthropic.claude-sonnet-4-6 in us-east-1
✓ TAVILY_API_KEY is configured
ℹ️ ALPHA_VANTAGE_API_KEY not set — financial data comes from yfinance (free, no key).
# Example output from get_stock_price("AAPL") called by the financial worker:
Stock: AAPL
Current Price: $228.45
Market Cap: $3,480,120,000,000.00
52-Week High: $237.23
import os
from strands.models.bedrock import BedrockModel
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
os.environ.setdefault("AWS_REGION", REGION)
model = BedrockModel(model_id=MODEL_ID, region_name=REGION)
print(f"Using {MODEL_ID} in {REGION}")
# --- next cell ---
from strands import Agent
# --- next cell ---
# Each specialist agent defines `name` and `description` so the parent orchestrator
# can treat it as a callable tool. callback_handler=None suppresses duplicate stdout
# streaming from sub-agents so only the teacher's final response is printed.
math_tutor = Agent(
name="math_tutor",
description="Solves mathematical equations and explains math concepts step by step",
model=model,
system_prompt="You are a math tutor. Solve math problems and explain your solutions clearly, step by step.",
callback_handler=None,
)
writing_coach = Agent(
name="writing_coach",
description="Helps with writing, grammar, and essay structure",
model=model,
system_prompt="You are a writing coach. Help with writing, grammar, and essay structure. Provide constructive feedback.",
callback_handler=None,
)
science_helper = Agent(
name="science_helper",
description="Explains scientific concepts and principles in simple terms",
model=model,
system_prompt="You are a science tutor. Explain scientific concepts clearly using simple language and real-world examples.",
callback_handler=None,
)
# --- next cell ---
# Agent-as-Tool pattern: passing specialist Agent instances directly in tools=[...]
# lets the router delegate cleanly while keeping each specialist's context isolated.
teacher = Agent(
model=model,
system_prompt="""You are a teacher who helps students by delegating to specialist tutors.
Never solve problems yourself. Always delegate to the appropriate specialist:
- math_tutor: for math problems and equations
- writing_coach: for writing, grammar, and essays
- science_helper: for science questions
After receiving the specialist's response, present it to the student in a friendly way.""",
tools=[math_tutor, writing_coach, science_helper],
)
# --- next cell ---
# Math → math_tutor
response = teacher("Can you help me solve this quadratic equation: x^2 + 5x + 6 = 0?")
# -> teacher delegates via tool call:
# math_tutor({'query': 'Solve the quadratic equation x^2 + 5x + 6 = 0 step by step.'})
# -> returns factored solution (x = -2 or x = -3) for teacher to present
# ... (see full file: 02_agent_as_tool.ipynb)
Using global.anthropic.claude-sonnet-4-6 in us-east-1
Tool #1: math_tutor({'query': 'Solve the quadratic equation x^2 + 5x + 6 = 0 step by step.'})
Great question! Here's how to solve x² + 5x + 6 = 0 step by step:
1. Find two numbers that multiply to 6 and add to 5: 2 and 3.
2. Factor the equation: (x + 2)(x + 3) = 0.
3. Set each factor to zero: x = -2 or x = -3.
How Agents Talk: MCP and A2A Protocols#
Revision Notes#
Reference files: weekend-sessions-notes/05-How Agents Talk.html, section-05-mcp-and-a2a/mcp-basics/, mcp-with-strands-agent/, a2a-travel-agents/
Concept#
Without open standards, connecting N agent applications to M tools or partner agents requires N × M custom integrations. Two complementary open protocols solve this at two different layers — "A2A outside, MCP inside":
- MCP (Model Context Protocol) — Standardized "USB port" connecting an LLM/agent to external tools, data resources, and prompt templates.
- A2A (Agent-to-Agent Protocol) — Standardized "email/contract" allowing independent agents (each with its own LLM, tools, and private internals) to discover and collaborate with one another across process or organizational boundaries.
How It Works#
A2A connects independent LLM-powered agents across team boundaries via Agent Cards and Tasks, while MCP standardizes how each agent internally discovers and invokes tools.
Key Mental Models#
- MCP architecture & roles:
- Host: The user-facing application (IDE, chat app, or Strands agent process) that owns the LLM and security boundaries.
- MCP Client: The protocol connector living inside the host (1-to-1 per server connection).
- MCP Server: Exposes capabilities over stdio (local subprocess) or Streamable HTTP (remote service) through a strict 3-phase lifecycle: Initialisation → Operation → Shutdown.
- MCP primitives:
- Server features: Tools (model-controlled actions), Resources & Resource Templates (read-only data/context addressed by URI), and Prompt Templates (reusable user-invoked workflows).
- Client features: Roots (declares which directories/URIs the server is allowed to touch), Sampling (server asks the host's LLM for a completion), and Elicitation (server requests structured input from the user).
FastMCPvs.FastAPI: FastAPI serves human/app REST endpoints; FastMCP exposes self-describing MCP primitives that any MCP client (MCPClientin Strands) can dynamically discover vialist_tools_sync()— whether it is your localserver.pyor a prebuilt server like the AWS Documentation MCP Server.
- A2A architecture & data model:
- Discovery: Every A2A server publishes an Agent Card at
/.well-known/agent-card.jsonadvertising its skills, URL, authentication, and supported modes (e.g., streaming). - Core objects: Messages (turns exchanged), Tasks (tracked units of work queried via
GetTask), and Artifacts (final structured/text deliverables). - Four communication styles: Synchronous request/response, Asynchronous polling, Streaming (SSE) for real-time progress, and Push notifications (webhooks) for long-running jobs.
- Discovery: Every A2A server publishes an Agent Card at
- MCP vs. A2A — why not just wrap every remote agent as an MCP tool?
- Who has the LLM: In MCP, only the client side has the LLM; in A2A, both sides are autonomous agents with their own LLMs, memory, and private tools.
- Interaction style: MCP is for structured function calls (
tool_name+ JSON args); A2A supports natural-language delegation, multi-turn negotiation, and stateful long-running tasks while keeping each agent's internals opaque.
Code Reference#
import json
# FastMCP: high-level helper for building MCP servers. It handles JSON-RPC
# parsing, registration of tools/resources/prompts, and the transport.
from mcp.server.fastmcp import Context, FastMCP
# The server name is returned during the MCP initialize handshake; WARNING avoids
# polluting stdio/stderr with per-request INFO logs.
mcp = FastMCP("WeatherServer", log_level="WARNING")
# --- Tool: get_weather ---------------------------------------------------
# Tools are model-controlled actions. @mcp.tool() exposes the function in list_tools()
# and generates its JSON Schema from type annotations and the docstring.
@mcp.tool()
def get_weather(city: str) -> str:
"""Get the current weather for a given city."""
# Fake data for demo purposes — a real server would call a weather API
fake_weather = {
"london": "15°C, cloudy",
"paris": "18°C, sunny",
"tokyo": "22°C, humid",
"new york": "12°C, windy",
"bangalore": "26°C, pleasant with light showers",
}
result = fake_weather.get(city.lower())
# -> '26°C, pleasant with light showers' (for city='Bangalore')
if result:
return f"Weather in {city}: {result}"
return f"Sorry, no weather data available for '{city}'."
# --- Tool that uses a client capability: roots ---------------------------
# Injecting `ctx: Context` lets a tool make reverse requests back to the MCP client,
# such as discovering which workspace directories (roots) the client authorized.
@mcp.tool()
async def list_client_roots(ctx: Context) -> str:
"""List the workspace roots the connected client has shared with this server."""
result = await ctx.session.list_roots()
# -> ListRootsResult(roots=[Root(uri='file:///home/user/workspace', name='workspace')])
if not result.roots:
return "The client did not share any roots."
return "\n".join(f"{root.name}: {root.uri}" for root in result.roots)
# --- Resource: greeting ---------------------------------------------------
# Resources are application-controlled read-only data (analogous to HTTP GET).
# "greeting://{name}" is a URI template; use resources for data and tools for actions.
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Return a personalized greeting."""
return f"Hello, {name}! Welcome to the WeatherServer."
# --- Resource: course directory (structured JSON) -------------------------
# A fixed URI with a MIME type tells the client how to interpret the content.
# ... (see full file: server.py)
# Start server (typically spawned by an MCP client over stdio):
$ python server.py
# Example MCP client calls against WeatherServer:
call_tool("get_weather", {"city": "Bangalore"})
-> "Weather in Bangalore: 26°C, pleasant with light showers"
read_resource("greeting://Developer")
-> "Hello, Developer! Welcome to the WeatherServer."
Shipping Agents to Production: Lambda, ECS Fargate, and AgentCore#
Revision Notes#
Reference files: weekend-sessions-notes/06-Shipping Agents to Production.html, section-06-production-deployment/lambda/, ecs-fargate/, agentcore-runtime/, agentcore-gateway/, multi-agent-on-agentcore/, setup_cognito.sh
Concept#
Running an agent in a local Jupyter notebook proves logic, not production readiness. Production introduces strict reliability, real security (auth, least-privilege IAM, secret isolation), multi-user concurrency, cost control, and distributed debugging. AWS provides three primary compute targets plus managed gateway and identity layers purpose-built for agents.
Key Mental Models#
- Choosing a compute target:
- AWS Lambda (
lambda/): Serverless, event-driven behind API Gateway, packaged as a container image via SAM (avoiding zip size limits). Best for short, bursty, stateless tasks (e.g., single-shot contract analysis).- Design constraints: Stateless (create a fresh agent per request or externalize state), cold starts (keep heavy client init outside the handler), and the 15-minute execution ceiling.
- Amazon ECS on Fargate (
ecs-fargate/): Always-on containerized web server behind an Application Load Balancer (/health,/,POST /schedule, demonstrated with a hospital scheduling agent). Best when you need custom web UIs, WebSockets, VPC networking, or steady traffic.- Design constraint: Because multiple container replicas sit behind an ALB, conversation state cannot live only in process memory — store it externally (e.g., DynamoDB, Redis, or AgentCore Memory).
- Amazon Bedrock AgentCore Runtime (
agentcore-runtime/): Purpose-built serverless runtime for AI agents. Wraps any framework (Strands, LangGraph, CrewAI) withBedrockAgentCoreAppand exposesinvoke_agent_runtimekeyed byruntimeSessionId.- Key advantages: Isolated microVM per session, pay only for active compute (idle wait time is free while session state stays warm), and support for long-running sessions up to 8 hours.
- AWS Lambda (
- AgentCore Gateway & Semantic Tool Search (
agentcore-gateway/):- Targets: Turns existing REST APIs (via an OpenAPI spec in S3) or Lambda functions into standardized MCP tools without writing custom wrapper servers.
- Semantic search: Dumping 200 tool schemas into an LLM's context wastes tokens and ruins tool-selection accuracy. AgentCore Gateway lets the agent search for only the top-K relevant tools per query.
- Dual authentication: Enforces inbound auth (Cognito OAuth/JWT or AWS IAM — never
NONEin production) and manages outbound auth via AgentCore Identity, injecting API keys or OAuth tokens at call time so credentials never touch agent code or prompts.
- Production Multi-Agent Topology on AgentCore (
multi-agent-on-agentcore/):- Deploys three independent services to AgentCore Runtime behind Cognito OAuth: Finance Orchestrator → calls Stock A2A Agent (over A2A) → calls Stock MCP Server (over MCP). Each tier scales, deploys, and authenticates independently.
- Enterprise integration patterns:
- Databases: Use connection pooling (never open one DB connection per user/tool call).
- External APIs: Implement timeouts, retries with backoff, and circuit breakers so flaky downstream APIs don't hang agent sessions.
- Sync vs. Async: Use synchronous responses for fast interactive chats; use event-driven queues/webhooks for multi-minute background workflows.
Production AWS agents pair workload-matched compute (Lambda, Fargate, or 8-hour AgentCore microVMs) with Gateway semantic tool search, isolated Memory, and deterministic Cedar policies.
Code Reference#
"""Document analysis agent for Amazon Bedrock AgentCore Runtime.
Compared with a plain Strands agent, only four things are added:
1. import BedrockAgentCoreApp
2. app = BedrockAgentCoreApp()
3. @app.entrypoint on the handler
4. app.run() in __main__
Local test:
python agent.py
curl -X POST http://localhost:8080/invocations -H "Content-Type: application/json" \
-d '{"prompt": "What are the key clauses in a standard NDA?"}'
"""
import os
from bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent, tool
from strands.models.bedrock import BedrockModel
# BedrockAgentCoreApp wraps the agent in an HTTP server exposing /invocations and /ping
# required by the managed AgentCore Runtime container contract.
app = BedrockAgentCoreApp()
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
@tool
def extract_clauses(text: str) -> dict:
"""Extract key clauses from contract text."""
# In production this would call an NLP pipeline or clause-classification service.
return {"clauses": ["termination", "liability", "indemnification"]}
model = BedrockModel(model_id=MODEL_ID)
agent = Agent(
model=model,
tools=[extract_clauses],
system_prompt="You are a document analysis assistant. Extract and summarize key contract clauses.",
)
# @app.entrypoint registers the function invoked on POST /invocations with the JSON payload.
@app.entrypoint
def handle(payload):
# payload -> {'prompt': 'What are the key clauses in a standard NDA?'}
response = agent(payload.get("prompt"))
# -> AgentResult(message={'role': 'assistant', 'content': [{'text': 'A standard NDA typically ...'}]})
return response.message["content"][0]["text"]
if __name__ == "__main__":
# Listens on port 8080 locally and inside the AgentCore Runtime microVM.
app.run()
$ python agent.py
INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
$ curl -X POST http://localhost:8080/invocations -H "Content-Type: application/json" \
-d '{"prompt": "What are the key clauses in a standard NDA?"}'
"A standard NDA typically centers on: (1) Definition of Confidential Information, (2) Obligations & Permitted Use, (3) Exclusions, (4) Term & Termination, and (5) Remedies / Liability."
import json
import os
from strands import Agent
from strands.models.bedrock import BedrockModel
MODEL_ID = os.environ.get("MODEL_ID") or os.environ.get("BEDROCK_MODEL_ID") or "global.anthropic.claude-sonnet-4-6"
SYSTEM_PROMPT = """You are a document analysis assistant.
When given a contract or document, you:
1. Extract key terms and parties involved
2. Flag any risky or unusual clauses
3. Provide a clear summary
Be concise and specific. Cite the exact language from the document when flagging risks."""
# Initialize the BedrockModel at module scope so the boto3 client and TCP connection pool
# are reused across warm Lambda invocations, cutting cold-start latency.
model = BedrockModel(model_id=MODEL_ID)
def lambda_handler(event, context):
"""Handle API Gateway POST requests."""
# API Gateway proxy events pass JSON as a string in event["body"], whereas direct
# Lambda test invokes often pass a plain dict—handling both simplifies local testing.
if isinstance(event.get("body"), str):
body = json.loads(event["body"])
# -> {'document_text': 'Auto-renews annually unless cancelled 90 days prior. Liability capped at $0.'}
else:
body = event.get("body") or event
document_text = body.get("document_text", "")
if not document_text:
return {
"statusCode": 400,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"error": "Missing 'document_text' in request body"}),
}
# Instantiate a fresh Agent per request so one caller's conversation history never
# leaks into another caller's response on a reused warm Lambda container.
# callback_handler=None avoids cluttering CloudWatch Logs with token-by-token prints.
agent = Agent(model=model, system_prompt=SYSTEM_PROMPT, callback_handler=None)
result = agent(f"Analyze this contract:\n\n{document_text}")
# -> AgentResult; str(result) -> "**Key Terms**: Annual auto-renewal with 90-day notice window.\n**Risks**: ..."
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"analysis": str(result)}),
}
# Invoking lambda_handler with an API Gateway proxy event:
event = {"body": json.dumps({"document_text": "Auto-renews annually unless cancelled 90 days prior. Liability capped at $0."})}
resp = lambda_handler(event, None)
# Returned API Gateway response:
{
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": "{"analysis": "**Key Terms**: Annual auto-renewal with 90-day notice window.\n**Risks**: (1) 'Liability capped at $0' eliminates vendor accountability; (2) 90-day cancellation window is unusually long."}"
}
Evals, Observability, and Governance: Making Agents Trustworthy#
Revision Notes#
Reference files: weekend-sessions-notes/07-Evals, Observability and Governance.html, section-07-evals-observability-governance/agent-evaluation/, agent-observability/, ai-governance/, governance_checklist.md
Concept#
Deployed is not the same as trusted. Unlike deterministic software, agents make probabilistic decisions across multi-step tool loops. Production trust requires three reinforcing pillars: Evaluations (measuring quality systematically), Observability (seeing every step, latency, and token cost), and Governance (enforcing hard safety, business, and human accountability boundaries).
Key Mental Models#
- Pillar 1 — Agent Evaluations (
agent-evaluation/):- The four checks: Tool selection (picked the right tool?), Parameter check (extracted valid args?), Context accuracy (grounded in retrieved/tool data?), and Response quality (helpful, in-scope, accurate?).
- Telemetry hierarchy: Evaluation runs on recorded telemetry at three levels:
- Session: Entire multi-turn conversation (e.g., built-in
GoalSuccessRate). - Trace: One end-to-end request/run (e.g., built-in
Correctness,Helpfulness, and custom LLM-as-judge rubrics liketravel_quality_metric.json, which scores out-of-scope Python answers as0.0). - Span: One atomic operation — a single LLM call or tool execution.
- Session: Entire multi-turn conversation (e.g., built-in
- On-demand vs. Online evaluation: Run on-demand evals against fixed test suites before shipping (CI/CD); run online evals continuously on sampled live traffic to catch drift. Every production incident should become a permanent regression test case.
- Pillar 2 — Observability with OpenTelemetry (
agent-observability/):- Why stdout logs fail: Flat logs cannot explain why a "slow loan agent" took 20 seconds. Nested waterfall traces immediately expose which span (LLM reasoning vs. slow API tool vs. retry loop) caused the latency or error.
- Four telemetry layers: Infrastructure metrics → Request-level telemetry → Agent execution traces (spans, prompts, tool args, tokens) → Behavioral analytics (cost, failure patterns).
- Instrument once, export anywhere: Strands emits standard OpenTelemetry/OpenInference spans (
invoke_agent,execute_event_loop_cycle,chat,execute_tool). Without changing agent code, you can route spans to Console, Jaeger (local waterfall UI), Langfuse (open-source, self-hostable in your AWS VPC for data ownership & cost tracking), LangSmith (prompt iteration, datasets, annotation queues), CloudWatch GenAI Observability (via ADOT + Transaction Search), or an OTel Collector fanning out to multiple backends simultaneously (e.g., Datadog + Langfuse). - Four anti-patterns to avoid: Treating
stdoutprints as observability; monitoring only the happy path; ignoring token costs until the bill arrives; bolting on observability after launch.
- Pillar 3 — AI Governance in Three Layers (
ai-governance/):- **Layer 1 — Bedrock Guardrails (controls what the agent says)**: Filters harmful content, blocks denied topics, and redacts PII on model inputs/outputs. Crucial limitation: Guardrails are probabilistic text filters — they cannot reliably enforce deterministic business rules on tool execution (e.g., stopping a \$50,000 refund call).
- **Layer 2 — AgentCore Policy + Cedar (controls what the agent does): Deterministic authorization rules evaluated outside the LLM** at AgentCore Gateway on every tool call, making them immune to prompt injection.
- Core semantics: Default deny (nothing runs without a matching
permit) and Forbid wins (any matchingforbidoverrides everypermit). - Rollout pattern: Always deploy new policies in
LOG_ONLYmode first to verify behavior, then switch toENFORCE. - Context- & identity-aware rules: Inspect the tool
action, gatewayresource, tool arguments (context.input), and verified caller identity (AgentCore::OAuthUserJWT claims orAgentCore::IamEntity) — enabling rules like allowing \$500 refunds while forbidding >\$1,000, restricting patient records to same-department physicians, and enforcing multi-tenant org boundaries.
- Core semantics: Default deny (nothing runs without a matching
- Layer 3 — Human & Organizational Governance (
governance_checklist.md):- Agent Card: Versioned documentation kept next to the code (owner, purpose, out-of-scope limits, models, tools, guardrails, Cedar policies, eval thresholds) updated in the same PR as any change.
- Audit Trails: Retained CloudWatch traces plus immutable long-term archives in S3 with Object Lock (WORM) to answer "show me everything the agent did for customer X on date Y."
- Incident Response (5 steps): Contain (disable Runtime endpoint / set Lambda concurrency to 0 / scale ECS to 0) → Investigate (filter traces + recent changes) → Fix → Communicate (respect regulatory windows like GDPR 72h / HIPAA 60d) → Learn (blameless postmortem + new eval test case).
Code Reference#
import os
from strands import Agent, tool
from strands.models import BedrockModel
from bedrock_agentcore.runtime import BedrockAgentCoreApp
# AgentCore Runtime app exposing a travel assistant whose tool calls and final
# responses can be scored offline/online by AgentCore Evaluations.
app = BedrockAgentCoreApp()
# Deterministic fixture data ensures evaluation test cases are reproducible—scoring
# measures agent reasoning and tool selection, not live API flakiness.
@tool
def get_flight_info(origin: str, destination: str) -> str:
"""Get flight information between two cities."""
flights = {
("new york", "london"): "Flight AA100 departs JFK at 22:00, arrives LHR at 10:00+1. Duration: 7h. Price: $650.",
("london", "new york"): "Flight BA178 departs LHR at 11:00, arrives JFK at 14:00. Duration: 8h. Price: $720.",
("new york", "paris"): "Flight AF007 departs JFK at 19:30, arrives CDG at 09:15+1. Duration: 7h45m. Price: $580.",
("paris", "new york"): "Flight AF008 departs CDG at 10:45, arrives JFK at 12:30. Duration: 8h45m. Price: $610.",
("london", "paris"): "Flight BA304 departs LHR at 08:00, arrives CDG at 10:15. Duration: 1h15m. Price: $120.",
}
key = (origin.lower(), destination.lower())
return flights.get(key, f"No direct flights found from {origin} to {destination}. Please check connecting options.")
# -> "Flight BA304 departs LHR at 08:00, arrives CDG at 10:15. Duration: 1h15m. Price: $120." (('london', 'paris'))
@tool
def get_hotel_recommendations(city: str, budget: str = "medium") -> str:
"""Get hotel recommendations for a city within a budget range (low/medium/high)."""
hotels = {
"london": {
"low": "Premier Inn London City (£80/night) - Clean, central, great transport links.",
"medium": "The Hoxton Shoreditch (£150/night) - Trendy area, rooftop bar, free mini-bar.",
"high": "The Savoy (£500/night) - Iconic luxury on the Thames, butler service.",
},
"paris": {
"low": "Generator Paris (€60/night) - Modern hostel with private rooms near Canal Saint-Martin.",
"medium": "Hotel des Grands Boulevards (€180/night) - Boutique hotel, rooftop terrace, great location.",
"high": "Le Bristol Paris (€800/night) - Palace hotel, Michelin-starred restaurant, garden pool.",
},
"new york": {
"low": "Pod 51 Hotel ($120/night) - Compact rooms, great Midtown location.",
"medium": "The Arlo NoMad ($220/night) - Rooftop bar, stylish rooms, central location.",
"high": "The Plaza Hotel ($700/night) - Iconic landmark, Central Park views, luxury suites.",
},
}
city_hotels = hotels.get(city.lower())
if not city_hotels:
return f"No hotel recommendations available for {city}."
# Graceful fallback to "medium" if the LLM supplies an unexpected budget tier string.
return city_hotels.get(budget.lower(), city_hotels["medium"])
# -> "Hotel des Grands Boulevards (€180/night) - Boutique hotel, rooftop terrace, great location."
@tool
def get_weather_forecast(city: str) -> str:
"""Get a simple weather forecast for a city."""
forecasts = {
"london": "Partly cloudy, 15°C (59°F). Light rain expected in the afternoon. Bring an umbrella.",
"paris": "Sunny with light clouds, 22°C (72°F). Perfect weather for sightseeing.",
"new york": "Clear skies, 18°C (64°F). Great day to explore Central Park.",
}
return forecasts.get(city.lower(), f"Weather data not available for {city}.")
# ... (see full file: agent_app.py)
# POST /invocations {"prompt": "Plan a medium-budget trip from London to Paris and check the weather."}
Tool #1: get_flight_info({'origin': 'London', 'destination': 'Paris'})
-> "Flight BA304 departs LHR at 08:00, arrives CDG at 10:15. Duration: 1h15m. Price: $120."
Tool #2: get_hotel_recommendations({'city': 'Paris', 'budget': 'medium'})
-> "Hotel des Grands Boulevards (€180/night) - Boutique hotel, rooftop terrace, great location."
Tool #3: get_weather_forecast({'city': 'Paris'})
-> "Sunny with light clouds, 22°C (72°F). Perfect weather for sightseeing."
Response: Fly BA304 (LHR 08:00 -> CDG 10:15, $120), stay at Hotel des Grands Boulevards (€180/night), and expect sunny 22°C weather.
"""Customer account agent used by the CloudWatch / ADOT tracing notebook.
The notebook runs it with `opentelemetry-instrument python agentcore_agent.py`
so the AWS Distro for OpenTelemetry can capture traces at the process level.
"""
import os
from strands import Agent, tool
from strands.models import BedrockModel
MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "global.anthropic.claude-sonnet-4-6")
# Two-step tool dependency: the agent must first call lookup_account to discover
# the customer's tier ("Enterprise") before passing that tier into calculate_discount.
# ADOT captures each LLM turn and tool call as nested OpenTelemetry spans in CloudWatch.
@tool
def lookup_account(account_id: str) -> str:
"""Look up account details by account ID."""
# Simulated account data
accounts = {
"ACC-001": {"name": "Acme Corp", "tier": "Enterprise", "balance": 142500.00},
"ACC-002": {"name": "Startup Inc", "tier": "Growth", "balance": 28750.00},
}
account = accounts.get(account_id)
if account:
return f"Account {account_id}: {account['name']}, Tier: {account['tier']}, Balance: ${account['balance']:,.2f}"
# -> "Account ACC-001: Acme Corp, Tier: Enterprise, Balance: $142,500.00"
return f"Account {account_id} not found."
@tool
def calculate_discount(amount: float, tier: str) -> str:
"""Calculate discount based on customer tier."""
rates = {"Enterprise": 0.15, "Growth": 0.10, "Starter": 0.05}
rate = rates.get(tier, 0.0)
discount = amount * rate
return f"{tier} tier discount: {rate * 100:.0f}% off ${amount:,.2f} = ${discount:,.2f} savings"
# -> "Enterprise tier discount: 15% off $50,000.00 = $7,500.00 savings"
model = BedrockModel(model_id=MODEL_ID)
# Zero tracing boilerplate in app code: Strands emits OpenTelemetry GenAI semantic
# conventions automatically when launched under `opentelemetry-instrument`.
agent = Agent(
model=model,
system_prompt="You are a customer account assistant. Use the available tools to help with account inquiries.",
tools=[lookup_account, calculate_discount],
)
response = agent("Look up account ACC-001 and calculate what discount they would get on a $50,000 purchase.")
# -> Span 1: lookup_account({'account_id': 'ACC-001'}) -> discovers tier='Enterprise'
# -> Span 2: calculate_discount({'amount': 50000, 'tier': 'Enterprise'}) -> '$7,500.00 savings'
print(response)
$ opentelemetry-instrument python agentcore_agent.py
Tool #1: lookup_account({'account_id': 'ACC-001'})
Tool #2: calculate_discount({'amount': 50000, 'tier': 'Enterprise'})
Account ACC-001 belongs to Acme Corp (Enterprise tier, balance $142,500.00).
On a $50,000 purchase, their 15% Enterprise discount saves $7,500.00 (net total: $42,500.00).
How All Building Blocks Connect#
Revision Notes#
The seven weekend sessions form a single progressive architecture from prototype to governed enterprise system:
- Core Brain & Loop (Section 1): Start with an LLM on Amazon Bedrock (or Groq) inside a Strands or LangGraph ReAct loop.
- Capabilities (Section 2): Give the agent
@toolfunctions, prebuilt/use_awstools, class-based connection pools, andasyncconcurrent I/O. - Continuity (Section 3): Add short-term checkpointing (
AgentCoreMemorySaver) and user-isolated long-term memory (Mem0 / AgentCore Memory) while actively managing context rot. - Scale of Reasoning (Section 4): Split overloaded agents into specialist teams using Supervisor–Worker, Agent-as-Tool, deterministic Graphs, or decentralized Swarms.
- Interoperability (Section 5): Decouple agents from tools via MCP ("inside") and connect independent agents across boundaries via A2A ("outside").
- Production Hosting (Section 6): Deploy onto Lambda, ECS Fargate, or AgentCore Runtime, fronting enterprise APIs with AgentCore Gateway (semantic search + OAuth/IAM + AgentCore Identity).
- Production Trust (Section 7): Wrap the deployed system in OpenTelemetry tracing, AgentCore Evaluations (built-in + custom judges), Bedrock Guardrails (speech), AgentCore Policy / Cedar (actions), and human governance (Agent Cards, WORM audits, incident response).
Quick Self-Check Questions#
Self-Check Questions#
What is the core difference between RAG and an AI Agent?
RAG retrieves external facts and injects them into the prompt so the model knows more (passive knowledge retrieval). An agent pairs the model with tools and a reasoning loop so it can plan, call tools, observe results, and take action in external systems.
Why should a database-backed tool be implemented as a class-based tool rather than a plain standalone @tool function?
A plain function opens and tears down a new database connection on every tool invocation, which fails under concurrency. A class-based tool initializes a reusable connection pool once and shares it across calls.
In a multi-user Mem0 setup, why should user_id be bound in Python code rather than passed as a tool parameter chosen by the LLM?
Binding user_id in code enforces a hard tenant-isolation boundary that cannot be bypassed by prompt injection; letting the LLM choose user_id risks leaking another user's private memories.
When should you choose a Graph pattern over a Swarm pattern in a multi-agent system?
Choose a Graph when you need deterministic, auditable, compliance-critical routing (e.g., guaranteeing every high-value order goes through manual review). Choose a Swarm for open-ended, creative collaboration where specialists dynamically hand off work without a rigid workflow.
How do MCP and A2A differ, and how do they work together?
MCP connects an LLM/agent to tools, resources, and prompts (LLM is on the client side; structured tool calls). A2A connects autonomous agents to other autonomous agents via Agent Cards, messages, tasks, and artifacts (both sides have LLMs and private internals). In production, they compose as A2A outside, MCP inside.
Why is Amazon Bedrock AgentCore Runtime often a better fit for interactive agents than AWS Lambda?
Lambda is stateless, suffers from cold starts, and has a hard 15-minute execution ceiling. AgentCore Runtime provides isolated per-session microVMs that stay warm for up to 8 hours while charging only for active compute time.
Why do you need AgentCore Policy (Cedar) if you already attached Bedrock Guardrails to your agent?
Bedrock Guardrails filter what the model says (content safety, denied topics, PII), but cannot reliably enforce deterministic business rules on tool calls. AgentCore Policy evaluates Cedar rules outside the model at the Gateway (default deny, forbid wins), deterministically blocking unauthorized actions like refunds over \$1,000 even under prompt injection.
What is the difference between a Session, a Trace, and a Span in agent observability and evaluation?
A Session is the entire multi-turn conversation (evaluated for GoalSuccessRate), a Trace is one end-to-end request/run (evaluated for Correctness and Helpfulness), and a Span is one atomic operation inside a trace (a single model call or tool execution).