Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 15 additions & 31 deletions 01-tutorials/07-AgentCore-E2E/lab-04-agentcore-runtime.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,12 @@
"deployment with the agent entrypoint file (lab_helpers/lab4_runtime.py), enables automatic ECR repository creation, and sets up JWT-based authentication using \n",
"Cognito. The configuration specifies allowed client IDs and discovery URLs retrieved from SSM parameters, establishing secure access control for the \n",
"production agent deployment. This step automatically generates the Dockerfile and .bedrock_agentcore.yaml configuration files needed for \n",
"containerized deployment."
"containerized deployment.\n",
"\n",
"**Runtime Header Configuration** : Below code configures custom header allowlists for the deployed AgentCore Runtime. It extracts the runtime ID from the agent ARN, retrieves the \n",
"current runtime configuration to preserve existing settings, then updates the runtime with a request header allowlist that includes the Authorization\n",
"header (required for OAuth token propagation) and custom headers. This ensures JWT tokens and other necessary headers are properly forwarded from \n",
"client requests to the agent runtime code."
]
},
{
Expand Down Expand Up @@ -336,6 +341,13 @@
" ),\n",
" }\n",
" },\n",
" # Add custom header allowlist for Authorization and custom headers\n",
" request_header_configuration={\n",
" \"requestHeaderAllowlist\": [\n",
" \"Authorization\", # Required for OAuth propogation\n",
" \"X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1\", # Custom header\n",
" ]\n",
" },\n",
")\n",
"\n",
"print(\"Configuration completed:\", response)"
Expand Down Expand Up @@ -431,14 +443,7 @@
"\n",
"#### Using the AgentCore Starter Toolkit\n",
"\n",
"We can validate that the agent works using the AgentCore Starter Toolkit for invocation. The starter toolkit can automatically create a session id for us to query our agent. Alternatively, you can also pass the session id as a parameter during invocation. For demonstration purpose, we will create our own session id.\n",
"\n",
"#### Runtime Header Configuration\n",
"\n",
"Below code configures custom header allowlists for the deployed AgentCore Runtime. It extracts the runtime ID from the agent ARN, retrieves the \n",
"current runtime configuration to preserve existing settings, then updates the runtime with a request header allowlist that includes the Authorization\n",
"header (required for OAuth token propagation) and custom headers. This ensures JWT tokens and other necessary headers are properly forwarded from \n",
"client requests to the agent runtime code."
"We can validate that the agent works using the AgentCore Starter Toolkit for invocation. The starter toolkit can automatically create a session id for us to query our agent. Alternatively, you can also pass the session id as a parameter during invocation. For demonstration purpose, we will create our own session id.\n"
]
},
{
Expand All @@ -454,27 +459,7 @@
"# Extract runtime ID from the ARN (format: arn:aws:bedrock-agentcore:region:account:runtime/runtime-id)\n",
"runtime_id = launch_result.agent_arn.split(\":\")[-1].split(\"/\")[-1]\n",
"\n",
"print(f\"Runtime ID: {runtime_id}\")\n",
"\n",
"# Get current runtime configuration to preserve existing settings\n",
"current_config = client.get_agent_runtime(agentRuntimeId=runtime_id)\n",
"\n",
"# Update runtime with custom header configuration while preserving existing settings\n",
"client.update_agent_runtime(\n",
" agentRuntimeId=runtime_id,\n",
" # Preserve existing configuration\n",
" agentRuntimeArtifact=current_config[\"agentRuntimeArtifact\"],\n",
" roleArn=current_config[\"roleArn\"],\n",
" networkConfiguration=current_config[\"networkConfiguration\"],\n",
" authorizerConfiguration=current_config.get(\"authorizerConfiguration\"),\n",
" # Add custom header allowlist for Authorization and custom headers\n",
" requestHeaderConfiguration={\n",
" \"requestHeaderAllowlist\": [\n",
" \"Authorization\", # Required for OAuth propogation\n",
" \"X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1\", # Custom header\n",
" ]\n",
" },\n",
")"
"print(f\"Runtime ID: {runtime_id}\")"
]
},
{
Expand All @@ -494,7 +479,6 @@
"\n",
"response = agentcore_runtime.invoke(\n",
" {\"prompt\": user_query},\n",
" # bearer_token=f\"Bearer {access_token['bearer_token']}\",\n",
" bearer_token=access_token[\"bearer_token\"],\n",
" session_id=str(session_id),\n",
")\n",
Expand Down
7 changes: 4 additions & 3 deletions 01-tutorials/07-AgentCore-E2E/lab-06-cleanup.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
" runtime_resource_cleanup,\n",
" delete_observability_resources,\n",
" local_file_cleanup,\n",
" get_ssm_parameter\n",
")\n",
"\n",
"print(\"✅ Dependencies imported successfully\")\n",
Expand All @@ -78,7 +79,7 @@
"outputs": [],
"source": [
"print(\"🧠 Starting Memory cleanup...\")\n",
"agentcore_memory_cleanup()"
"agentcore_memory_cleanup(get_ssm_parameter(\"/app/customersupport/agentcore/memory_id\"))"
]
},
{
Expand All @@ -99,7 +100,7 @@
"outputs": [],
"source": [
"print(\"🚀 Starting Runtime cleanup...\")\n",
"runtime_resource_cleanup()"
"runtime_resource_cleanup(get_ssm_parameter(\"/app/customersupport/agentcore/runtime_arn\"))"
]
},
{
Expand All @@ -119,7 +120,7 @@
"outputs": [],
"source": [
"print(\"⚙️ Starting Gateway Cleanup...\")\n",
"gateway_target_cleanup()"
"gateway_target_cleanup(get_ssm_parameter(\"/app/customersupport/agentcore/gateway_id\"))"
]
},
{
Expand Down
114 changes: 62 additions & 52 deletions 01-tutorials/07-AgentCore-E2E/lab_helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,54 +605,57 @@
print(f"❌ Error during cleanup: {str(e)}")


def agentcore_memory_cleanup():
control_client = boto3.client("bedrock-agentcore-control", region_name=REGION)

def agentcore_memory_cleanup(memory_id: str = None):
"""List all memories and their associated strategies"""
next_token = None
control_client = boto3.client("bedrock-agentcore-control", region_name=REGION)
if memory_id:
response = control_client.delete_memory(memoryId=memory_id)
print(f"✅ Successfully deleted memory: {memory_id}")
else:
next_token = None
while True:
# Build request parameters
params = {}
if next_token:
params["nextToken"] = next_token

# List memories
try:
response = control_client.list_memories(**params)

while True:
# Build request parameters
params = {}
if next_token:
params["nextToken"] = next_token
# Process each memory
for memory in response.get("memories", []):
memory_id = memory.get("id")
print(f"\nMemory ID: {memory_id}")
print(f"Status: {memory.get('status')}")
response = control_client.delete_memory(memoryId=memory_id)
response = control_client.list_memories(**params)
print(f"✅ Successfully deleted memory: {memory_id}")

# List memories
try:
response = control_client.list_memories(**params)

# Process each memory
for memory in response.get("memories", []):
memory_id = memory.get("id")
print(f"\nMemory ID: {memory_id}")
print(f"Status: {memory.get('status')}")
response = control_client.delete_memory(memoryId=memory_id)
response = control_client.list_memories(**params)
print(f"✅ Successfully deleted memory: {memory_id}")
# Process each memory status
for memory in response.get("memories", []):
memory_id = memory.get("id")
print(f"\nMemory ID: {memory_id}")
print(f"Status: {memory.get('status')}")

response = control_client.list_memories(**params)
# Process each memory status
for memory in response.get("memories", []):
memory_id = memory.get("id")
print(f"\nMemory ID: {memory_id}")
print(f"Status: {memory.get('status')}")

except Exception as e:
print(f"⚠️ Error getting memory details: {e}")
except Exception as e:
print(f"⚠️ Error getting memory details: {e}")
# Check for more results
next_token = response.get("nextToken")
if not next_token:
break

# Check for more results
next_token = response.get("nextToken")
if not next_token:
break

def gateway_target_cleanup(gateway_id: str = None):

def gateway_target_cleanup():
gateway_client = boto3.client(
"bedrock-agentcore-control",
region_name=REGION,
)
response = gateway_client.list_gateways()
gateway_id = response["items"][0]["gatewayId"]
if not gateway_id:
gateway_client = boto3.client(
"bedrock-agentcore-control",
region_name=REGION,
)
response = gateway_client.list_gateways()
gateway_id = response["items"][0]["gatewayId"]
print(f"🗑️ Deleting all targets for gateway: {gateway_id}")

# List and delete all targets
Expand All @@ -674,22 +677,29 @@
print(f"✅ Gateway {gateway_id} deleted successfully")


def runtime_resource_cleanup():
def runtime_resource_cleanup(runtime_arn: str = None):
try:
# Initialize AWS clients
agentcore_control_client = boto3.client(
"bedrock-agentcore-control", region_name=REGION
)
ecr_client = boto3.client("ecr", region_name=REGION)

# Delete the AgentCore Runtime
# print(" 🗑️ Deleting AgentCore Runtime...")
runtimes = agentcore_control_client.list_agent_runtimes()
for runtime in runtimes["agentRuntimes"]:
if runtime_arn:
runtime_id = runtime_arn.split(":")[-1].split("/")[-1]
response = agentcore_control_client.delete_agent_runtime(

Check failure on line 684 in 01-tutorials/07-AgentCore-E2E/lab_helpers/utils.py

View workflow job for this annotation

GitHub Actions / python-lint

Ruff (F821)

01-tutorials/07-AgentCore-E2E/lab_helpers/utils.py:684:24: F821 Undefined name `agentcore_control_client`
agentRuntimeId=runtime["agentRuntimeId"]
agentRuntimeId=runtime_id
)
print(f" ✅ Agent runtime deleted: {response['status']}")
else:
# Initialize AWS clients
agentcore_control_client = boto3.client(
"bedrock-agentcore-control", region_name=REGION
)
ecr_client = boto3.client("ecr", region_name=REGION)

# Delete the AgentCore Runtime
# print(" 🗑️ Deleting AgentCore Runtime...")
runtimes = agentcore_control_client.list_agent_runtimes()
for runtime in runtimes["agentRuntimes"]:
response = agentcore_control_client.delete_agent_runtime(
agentRuntimeId=runtime["agentRuntimeId"]
)
print(f" ✅ Agent runtime deleted: {response['status']}")

# Delete the ECR repository
print(" 🗑️ Deleting ECR repository...")
Expand Down
2 changes: 1 addition & 1 deletion 01-tutorials/07-AgentCore-E2E/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ strands-agents-tools
boto3==1.40.47
botocore==1.40.47
bedrock-agentcore==0.1.7
bedrock-agentcore-starter-toolkit==0.1.20
bedrock-agentcore-starter-toolkit==0.1.22
aws-opentelemetry-distro
ddgs
aws-opentelemetry-distro~=0.10.1
Expand Down
Loading