mirror of
https://github.com/awslabs/amazon-bedrock-agentcore-samples.git
synced 2025-09-08 20:50:46 +00:00
* Add missing credential_provider_name parameter to config.yaml.example * Fix get_config function to properly parse YAML values with inline comments * Enhanced get_config to prevent copy-paste whitespace errors in AWS identifiers * Improve LLM provider configuration and error handling with bedrock as default * Add OpenAPI templating system and fix hardcoded regions * Add backend template build to Readme * delete old yaml files * Fix Cognito setup with automation script and missing domain creation steps * docs: Add EC2 instance port configuration documentation - Document required inbound ports (443, 8011-8014) - Include SSL/TLS security requirements - Add AWS security group best practices - Provide port usage summary table * docs: Add hyperlinks to prerequisites in README - Link EC2 port configuration documentation - Link IAM role authentication setup - Improve navigation to detailed setup instructions * docs: Add BACKEND_API_KEY to configuration documentation - Document gateway environment variables section - Add BACKEND_API_KEY requirement for credential provider - Include example .env file format for gateway directory - Explain usage in create_gateway.sh script * docs: Add BACKEND_API_KEY to deployment guide environment variables - Include BACKEND_API_KEY in environment variables reference table - Mark as required for gateway setup - Provide quick reference alongside other required variables * docs: Add BedrockAgentCoreFullAccess policy and trust policy documentation - Document AWS managed policy BedrockAgentCoreFullAccess - Add trust policy requirements for bedrock-agentcore.amazonaws.com - Reorganize IAM permissions for better clarity - Remove duplicate trust policy section - Add IAM role requirement to deployment prerequisites * docs: Document role_name field in gateway config example - Explain that role_name is used to create and manage the gateway - Specify BedrockAgentCoreFullAccess policy requirement - Note trust policy requirement for bedrock-agentcore.amazonaws.com - Improve clarity for gateway configuration setup * docs: Add AWS IP address ranges for production security enhancement - Document AWS IP ranges JSON download for restricting access - Reference official AWS documentation for IP address ranges - Provide security alternatives to 0.0.0.0/0 for production - Include examples of restricted security group configurations - Enable egress filtering and region-specific access control * style: Format Python code with black - Reformat 14 Python files for consistent code style - Apply PEP 8 formatting standards - Improve code readability and maintainability * docs: Update SRE agent prerequisites and setup documentation - Convert prerequisites section to markdown table format - Add SSL certificate provider examples (no-ip.com, letsencrypt.org) - Add Identity Provider (IDP) requirement with setup_cognito.sh reference - Clarify that all prerequisites must be completed before setup - Add reference to domain name and cert paths needed for BACKEND_DOMAIN - Remove Managing OpenAPI Specifications section (covered in use-case setup) - Add Deployment Guide link to Development to Production section Addresses issues #171 and #174 * fix: Replace 'AWS Bedrock' with 'Amazon Bedrock' in SRE agent files - Updated error messages in llm_utils.py - Updated comments in both .env.example files - Ensures consistent naming convention across SRE agent codebase --------- Co-authored-by: dheerajoruganty <dheo@amazon.com> Co-authored-by: Amit Arora <aroraai@amazon.com>
115 lines
3.9 KiB
Python
Executable File
115 lines
3.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
import boto3
|
|
import json
|
|
import logging
|
|
import time
|
|
from pathlib import Path
|
|
|
|
# Configure logging with basicConfig
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
# Define log message format
|
|
format="%(asctime)s,p%(process)s,{%(filename)s:%(lineno)d},%(levelname)s,%(message)s",
|
|
)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Invoke SRE Agent Runtime via AgentCore"
|
|
)
|
|
parser.add_argument("--prompt", required=True, help="Prompt to send to the agent")
|
|
parser.add_argument(
|
|
"--runtime-arn",
|
|
help="Agent Runtime ARN (reads from .sre_agent_uri if not provided)",
|
|
)
|
|
parser.add_argument(
|
|
"--region", default="us-east-1", help="AWS region (default: us-east-1)"
|
|
)
|
|
parser.add_argument(
|
|
"--session-id", help="Runtime session ID (generates one if not provided)"
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
# Get runtime ARN from file if not provided
|
|
runtime_arn = args.runtime_arn
|
|
if not runtime_arn:
|
|
script_dir = Path(__file__).parent
|
|
|
|
# First try to read from .agent_arn file (preferred)
|
|
arn_file = script_dir / ".agent_arn"
|
|
if arn_file.exists():
|
|
runtime_arn = arn_file.read_text().strip()
|
|
logging.info(f"Using runtime ARN from .agent_arn: {runtime_arn}")
|
|
else:
|
|
# Fallback to deriving from container URI
|
|
uri_file = script_dir / ".sre_agent_uri"
|
|
if uri_file.exists():
|
|
container_uri = uri_file.read_text().strip()
|
|
# Extract account ID and construct runtime ARN
|
|
# Container URI format: account-id.dkr.ecr.region.amazonaws.com/repo:tag
|
|
account_id = container_uri.split(".")[0]
|
|
runtime_arn = f"arn:aws:bedrock-agentcore:{args.region}:{account_id}:runtime/sre-agent"
|
|
logging.info(
|
|
f"Using runtime ARN derived from container URI: {runtime_arn}"
|
|
)
|
|
else:
|
|
logging.error(
|
|
f"No runtime ARN provided and neither .agent_arn nor .sre_agent_uri file found"
|
|
)
|
|
logging.error(
|
|
"Please provide --runtime-arn or ensure the agent is deployed"
|
|
)
|
|
return
|
|
|
|
# Generate session ID if not provided
|
|
session_id = args.session_id
|
|
if not session_id:
|
|
timestamp = str(int(time.time()))
|
|
session_id = f"sre-agent-session-{timestamp}-invoke"
|
|
logging.info(f"Generated session ID: {session_id}")
|
|
|
|
# Validate session ID length (must be 33+ characters)
|
|
if len(session_id) < 33:
|
|
session_id = session_id + "-" + "x" * (33 - len(session_id))
|
|
logging.info(f"Padded session ID to meet minimum length: {session_id}")
|
|
|
|
# Create AgentCore client
|
|
agent_core_client = boto3.client("bedrock-agentcore", region_name=args.region)
|
|
|
|
# Prepare payload
|
|
payload = json.dumps({"input": {"prompt": args.prompt}})
|
|
|
|
logging.info(f"Invoking agent runtime: {runtime_arn}")
|
|
logging.info(f"Session ID: {session_id}")
|
|
logging.info(f"Prompt: {args.prompt}")
|
|
|
|
try:
|
|
response = agent_core_client.invoke_agent_runtime(
|
|
agentRuntimeArn=runtime_arn,
|
|
runtimeSessionId=session_id,
|
|
payload=payload,
|
|
qualifier="DEFAULT",
|
|
)
|
|
|
|
response_body = response["response"].read()
|
|
response_data = json.loads(response_body)
|
|
|
|
logging.info("Agent Response:")
|
|
print(json.dumps(response_data, indent=2))
|
|
|
|
# Extract and print the message separately
|
|
if "output" in response_data and "message" in response_data["output"]:
|
|
print("\nMessage:")
|
|
print(response_data["output"]["message"])
|
|
|
|
except Exception as e:
|
|
logging.error(f"Failed to invoke agent runtime: {e}")
|
|
raise
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|