### Setup Virtual Environment and Install Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/policy/quickstart.html Set up a Python virtual environment and install necessary libraries for the AgentCore policy quickstart. This includes boto3 for AWS interaction, bedrock-agentcore-starter-toolkit for AgentCore functionalities, and requests for HTTP communication. ```bash mkdir agentcore-policy-quickstart cd agentcore-policy-quickstart python3 -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` ```bash pip install boto3 pip install bedrock-agentcore-starter-toolkit pip install requests ``` -------------------------------- ### Setup Project and Install Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/quickstart.html Create a project directory, set up a virtual environment, and install necessary Python packages. Ensure pip is up-to-date. ```bash mkdir agentcore-runtime-quickstart cd agentcore-runtime-quickstart python3 -m venv .venv source .venv/bin/activate ``` ```bash pip install --upgrade pip ``` ```bash pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkit ``` ```bash agentcore --help ``` -------------------------------- ### Create Virtual Environment and Activate Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/observability/quickstart.html Set up a new folder and initialize a Python virtual environment for the quickstart project. Activate the environment before proceeding with installations. ```bash mkdir agentcore-observability-quickstart cd agentcore-observability-quickstart python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Local Testing Setup Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/import-agent/quickstart.html Commands to navigate to the output directory, install dependencies, and run the imported agent locally. ```bash cd ./output python -m pip install -r requirements.txt python strands_agent.py ``` -------------------------------- ### Setup Project Directory and Virtual Environment Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/gateway/quickstart.html Create a new directory for your project and set up a Python virtual environment. Activate the virtual environment before installing dependencies. ```bash mkdir agentcore-gateway-quickstart cd agentcore-gateway-quickstart python3 -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Install SDK and Dependencies (Python) Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/identity/quickstart.html Installs the necessary Python packages for AgentCore identity quickstart, including bedrock-agentcore, boto3, and pyjwt. Ensure you are in a Python virtual environment. ```bash mkdir agentcore-identity-quickstart cd agentcore-identity-quickstart python3 -m venv .venv source .venv/bin/activate pip install bedrock-agentcore boto3 strands-agents bedrock-agentcore-starter-toolkit pyjwt ``` -------------------------------- ### Install AgentCore Starter Toolkit Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/evaluation/quickstart.html Install the AgentCore starter toolkit using pip. Ensure you have Python 3.10+ installed. ```bash pip install bedrock-agentcore-starter-toolkit ``` -------------------------------- ### Run Gateway Setup Script Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/memory_gateway_agent.html Command to execute the gateway setup script. ```bash python setup_gateway.py ``` -------------------------------- ### Install Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/identity/quickstart-with-cli.html Set up a Python virtual environment and install necessary libraries for AgentCore development. ```bash # Create project directory mkdir agentcore-identity-demo cd agentcore-identity-demo # Create virtual environment python3 -m venv .venv source .venv/bin/activate # Install dependencies pip install bedrock-agentcore bedrock-agentcore-starter-toolkit strands-agents boto3 ``` -------------------------------- ### Install Bedrock AgentCore Starter Toolkit Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/a2a.html Install the Amazon Bedrock AgentCore starter toolkit using pip. This command installs the necessary tools for deploying your A2A server to AWS. ```bash pip install bedrock-agentcore-starter-toolkit ``` -------------------------------- ### List Online Evaluation Configurations Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/evaluation/quickstart.html Lists all available online evaluation configurations. Use this to get an overview of your current evaluation setups. ```bash agentcore eval online list ``` -------------------------------- ### Set Up Python Virtual Environment and Install Packages Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/memory_gateway_agent.html Create and activate a Python virtual environment, then install the necessary packages for Bedrock AgentCore development. ```bash # Create and activate virtual environment python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install required packages pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkit ``` -------------------------------- ### Initialize Gateway Setup Function Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/gateway/quickstart.html Defines the main setup function, sets the AWS region, and initializes the Gateway client with logging enabled. ```python def setup_gateway(): # Configuration region = "us-east-1" # Change to your preferred region print("šŸš€ Setting up AgentCore Gateway...") print(f"Region: {region}\n") # Initialize client client = GatewayClient(region_name=region) client.logger.setLevel(logging.INFO) ``` -------------------------------- ### Basic Agent Import Example Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/import-agent/configuration.html Example of a basic agent import using required parameters for the 'strands' platform. ```bash agentcore import-agent \ --agent-id ABCD1234 \ --agent-alias-id TSTALIASID \ --target-platform strands ``` -------------------------------- ### Set up Python Virtual Environment and Install Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-browser.html Create a project directory, set up a Python virtual environment, and install the necessary packages including bedrock-agentcore, strands-agents, and playwright. ```bash mkdir agentcore-browser-quickstart cd agentcore-browser-quickstart python3 -m venv .venv source .venv/bin/activate pip install bedrock-agentcore strands-agents strands-agents-tools playwright nest-asyncio ``` -------------------------------- ### Install AgentCore Starter Toolkit Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/agentcore-quickstart-example.html Installs the necessary Python packages for the AgentCore starter toolkit, including bedrock-agentcore, strands-agents, and strands-agents-tools. Ensure you are in a virtual environment. ```bash # Create virtual environment python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install required packages (version 0.1.21 or later) pip install "bedrock-agentcore-starter-toolkit>=0.1.21" strands-agents strands-agents-tools boto3 ``` -------------------------------- ### start Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Starts a code interpreter sandbox session. You can use the default system interpreter or specify a custom one. Sessions can also be configured with a timeout. ```APIDOC ## start ### Description Start a code interpreter sandbox session. ### Method `start(identifier=DEFAULT_IDENTIFIER, name=None, session_timeout_seconds=DEFAULT_TIMEOUT)` ### Parameters #### Path Parameters - **identifier** (Optional[str]) - Optional - The interpreter identifier to use. Can be DEFAULT_IDENTIFIER or a custom interpreter ID from create_code_interpreter. - **name** (Optional[str]) - Optional - A name for this session. - **session_timeout_seconds** (Optional[int]) - Optional - The timeout in seconds. Default: 900 (15 minutes). ### Returns #### Success Response (200) - **str** (str) - The session ID of the newly created session. ### Request Example ```python # Use system interpreter session_id = client.start() # Use custom interpreter with VPC session_id = client.start( identifier="my-interpreter-abc123", session_timeout_seconds=1800 # 30 minutes ) ``` ``` -------------------------------- ### Start Bedrock AgentCore Server Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/runtime.html Starts the Bedrock AgentCore server, allowing configuration of the port and host. This is the main entry point for running the server. ```python def run(self, port: int = 8080, host: Optional[str] = None, **kwargs): """Start the Bedrock AgentCore server. Args: ``` -------------------------------- ### Install AgentCore CLI Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/create/quickstart.html Install the AgentCore CLI globally to use its commands for project creation and management. ```bash npm install -g @aws/agentcore ``` -------------------------------- ### Verify AgentCore Evaluation Toolkit Installation Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/evaluation/quickstart.html Verify the installation of the AgentCore evaluation toolkit by running the help command. This confirms the toolkit is accessible and lists available evaluation command options. ```bash agentcore eval --help ``` -------------------------------- ### Complete Weather Agent Example Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/gateway-integration.html A complete example demonstrating a weather agent that integrates with Gateway. This snippet shows the necessary imports for a full implementation. ```python from bedrock_agentcore.gateway import GatewayClient import json import asyncio import httpx ``` -------------------------------- ### Local Testing with curl: Start Agent Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/async.html Starts the agent locally. This is the first step before testing endpoints. ```bash # Start your agent python my_async_agent.py ``` -------------------------------- ### Start Uvicorn Server Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/runtime.html Starts the Uvicorn server with configurable host and port. Detects Docker environment for host binding. Allows overriding uvicorn parameters via kwargs. ```python import os import uvicorn if host is None: if os.path.exists("/.dockerenv") or os.environ.get("DOCKER_CONTAINER"): host = "0.0.0.0" # nosec B104 - Docker needs this to expose the port else: host = "127.0.0.1" # Set default uvicorn parameters, allow kwargs to override uvicorn_params = { "host": host, "port": port, "access_log": self.debug, "log_level": "info" if self.debug else "warning", } uvicorn_params.update(kwargs) uvicorn.run(self, **uvicorn_params) ``` -------------------------------- ### Execute Setup Script Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/policy/quickstart.html Runs the Python setup script to configure the AWS Bedrock Agent Core environment, including gateway, policy engine, and associated resources. The script typically takes a few minutes to complete. ```bash python setup_policy.py ``` -------------------------------- ### Install AgentCore Browser Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-browser.html Commands to set up a Python virtual environment and install necessary packages for using the AgentCore Browser SDK with Playwright. ```bash mkdir agentcore-browser-quickstart cd agentcore-browser-quickstart python3 -m venv .venv source .venv/bin/activate ``` ```bash pip install bedrock-agentcore playwright boto3 nest-asyncio ``` -------------------------------- ### Start Local Development Server Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/create/quickstart.html Run the `agentcore dev` command to start the local development server. Hot reload is enabled by default, allowing for quick iteration. ```bash agentcore dev ``` -------------------------------- ### Start AgentCore Development Server Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/dev/quickstart.html Run the `agentcore dev` command from your project directory to start the local development server with hot reloading. The server will watch for file changes and automatically restart. ```bash agentcore dev ``` -------------------------------- ### Get Policy Engine Details Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/cli.html Retrieves details for a specific policy engine using its ID. The region can also be specified. The example shows how to get details for a policy engine with ID 'testPolicyEngine-abc123'. ```bash agentcore policy get-policy-engine [OPTIONS] ``` ```bash agentcore policy get-policy-engine --policy-engine-id "testPolicyEngine-abc123" ``` -------------------------------- ### Set up Local Development Environment Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/create/quickstart.html Navigate to the `src` directory, create a virtual environment, and activate it to prepare for local development. This ensures dependencies are isolated. ```bash cd src python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate cd .. ``` -------------------------------- ### Basic Code Interpreter Usage Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Demonstrates the basic usage of the Code Interpreter client, including starting and stopping the interpreter, executing code, installing packages, and uploading files. Ensure the client is started before executing code and stopped when finished. ```python from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter client = CodeInterpreter('us-west-2') client.start() # Execute code result = client.execute_code("print('Hello, World!')") # Install packages client.install_packages(['pandas', 'matplotlib']) # Upload and process data client.upload_file('data.csv', csv_content, description='Sales data') client.stop() ``` -------------------------------- ### Deployment Options (Step 7) Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/import-agent/quickstart.html Configure deployment options, including whether to deploy to AgentCore Runtime and how you want to run the agent. ```bash ? Deploy to AgentCore Runtime? [y/N]: Y ? How would you like to run the agent? > Run on AgentCore Runtime Install dependencies and run locally Don't run now ``` -------------------------------- ### Execute Shell Command to Check Python Version Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Use this to execute shell commands within the interpreter environment. This example checks the installed Python version. ```shell python --version ``` -------------------------------- ### Correct Generation Name Example (āœ… Correct) Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/policy-integration.html Shows the correct way to name a policy for generation, using only letters, numbers, and underscores, starting with a letter. ```python # āœ… Correct: Uses underscores policy_client.generate_policy( name='refund_policy_v1', ... ) ``` -------------------------------- ### CodeInterpreter Basic Usage Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Demonstrates the basic usage of the CodeInterpreter client, including starting the client, executing code, installing packages, uploading files, and stopping the client. ```APIDOC ## CodeInterpreter Basic Usage ### Description Provides a step-by-step guide on how to use the `CodeInterpreter` client for common tasks such as starting and stopping the interpreter, executing code, installing packages, and uploading files. ### Usage ```python from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter client = CodeInterpreter('us-west-2') client.start() # Execute code result = client.execute_code("print('Hello, World!')") # Install packages client.install_packages(['pandas', 'matplotlib']) # Upload and process data client.upload_file('data.csv', csv_content, description='Sales data') client.stop() ``` ``` -------------------------------- ### Python Agent Script for Gateway Testing Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/gateway/quickstart.html This script configures and runs an agent that connects to the AgentCore Gateway. It requires a `gateway_config.json` file for setup. Ensure you have the necessary libraries installed. ```python """ Agent script to test the Gateway Run this after setup: python run_agent.py """ from strands import Agent from strands.models import BedrockModel from strands.tools.mcp.mcp_client import MCPClient from mcp.client.streamable_http import streamablehttp_client from bedrock_agentcore_starter_toolkit.operations.gateway.client import GatewayClient import json import sys def create_streamable_http_transport(mcp_url: str, access_token: str): return streamablehttp_client(mcp_url, headers={"Authorization": f"Bearer {access_token}"}) def get_full_tools_list(client): """Get all tools with pagination support""" more_tools = True tools = [] pagination_token = None while more_tools: tmp_tools = client.list_tools_sync(pagination_token=pagination_token) tools.extend(tmp_tools) if tmp_tools.pagination_token is None: more_tools = False else: more_tools = True pagination_token = tmp_tools.pagination_token return tools def run_agent(): # Load configuration try: with open("gateway_config.json", "r") as f: config = json.load(f) except FileNotFoundError: print("āŒ Error: gateway_config.json not found!") print("Please run 'python setup_gateway.py' first to create the Gateway.") sys.exit(1) gateway_url = config["gateway_url"] client_info = config["client_info"] # Get access token for the agent print("Getting access token...") client = GatewayClient(region_name=config["region"]) access_token = client.get_access_token_for_cognito(client_info) print("āœ“ Access token obtained\n") # Model configuration - change if needed model_id = "anthropic.claude-3-7-sonnet-20250219-v1:0" print("šŸ¤– Starting AgentCore Gateway Test Agent") print(f"Gateway URL: {gateway_url}") print(f"Model: {model_id}") print("-" * 60) # Setup Bedrock model bedrockmodel = BedrockModel( inference_profile_id=model_id, streaming=True, ) # Setup MCP client mcp_client = MCPClient(lambda: create_streamable_http_transport(gateway_url, access_token)) with mcp_client: # List available tools tools = get_full_tools_list(mcp_client) print(f"\nšŸ“‹ Available tools: {[tool.tool_name for tool in tools]}") print("-" * 60) # Create agent agent = Agent(model=bedrockmodel, tools=tools) # Interactive loop print("\nšŸ’¬ Interactive Agent Ready!") print("Try asking: 'What's the weather in Seattle?'") print("Type 'exit', 'quit', or 'bye' to end.\n") while True: user_input = input("You: ") if user_input.lower() in ["exit", "quit", "bye"]: print("šŸ‘‹ Goodbye!") break print("\nšŸ¤” Thinking...\n") response = agent(user_input) print(f"\nAgent: {response.message.get('content', response)}\n") if __name__ == "__main__": run_agent() ``` -------------------------------- ### CodeInterpreter Client Usage Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Demonstrates basic and context manager usage of the CodeInterpreter client for starting sessions, executing code, installing packages, uploading files, and stopping sessions. ```APIDOC ## CodeInterpreter Client Client for interacting with the AWS Code Interpreter sandbox service. This client handles the session lifecycle and method invocation for Code Interpreter sandboxes, providing an interface to execute code in a secure, managed environment. ### Attributes: - `region` (str): The AWS region being used. - `control_plane_client`: The boto3 client for control plane operations. - `data_plane_service_name` (str): AWS service name for the data plane. - `client` (str): The boto3 client for interacting with the service. - `identifier` (str): The code interpreter identifier. - `session_id` (str): The active session ID. ### Basic Usage ```python from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter client = CodeInterpreter('us-west-2') client.start() # Execute code result = client.execute_code("print('Hello, World!')") # Install packages client.install_packages(['pandas', 'matplotlib']) # Upload and process data client.upload_file('data.csv', csv_content, description='Sales data') client.stop() ``` ### Context Manager Usage ```python from bedrock_agentcore.tools.code_interpreter_client import code_session with code_session('us-west-2') as client: client.install_packages(['numpy']) result = client.execute_code('import numpy as np; print(np.pi)') ``` ``` -------------------------------- ### Create Project Directory and Virtual Environment Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-browser.html Set up a new project folder and activate a Python virtual environment for managing dependencies. ```bash mkdir agentcore-browser-quickstart cd agentcore-browser-quickstart python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Get Online Evaluation Configuration Details Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/evaluation/quickstart.html Retrieves detailed information about a specific online evaluation configuration using its ID. Replace the example ID with your actual configuration ID. ```bash agentcore eval online get --config-id production_eval_config-2HeyEjChSQ ``` -------------------------------- ### Simple Agent Example with Threading Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/async-processing.html This Python agent uses threading to demonstrate manual task management. It registers tasks with `add_async_task`, starts them in background threads, and marks them complete with `complete_async_task`, allowing AgentCore to manage the system's health status. ```python #!/usr/bin/env python3 """ Simple agent demonstrating manual task management with threading. """ import time import threading from datetime import datetime from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() def process_data(data_id: str, task_id: int): """Process data synchronously in background thread.""" print(f"[{datetime.now()}] Processing data: {data_id}") # Simulate processing work time.sleep(30) # Long-running task print(f"[{datetime.now()}] Completed processing: {data_id}") # Mark task as complete app.complete_async_task(task_id) return f"Processed {data_id}" def cleanup_task(task_id: int): """Cleanup task running in background thread.""" print(f"[{datetime.now()}] Starting cleanup...") time.sleep(10) print(f"[{datetime.now()}] Cleanup completed") # Mark task as complete app.complete_async_task(task_id) return "Cleanup done" @app.entrypoint def handler(event): """Main handler - starts background tasks with manual tracking.""" action = event.get("action", "info") if action == "process": data_id = event.get("data_id", "default_data") # Start tracking the task (status becomes HealthyBusy) task_id = app.add_async_task("data_processing", {"data_id": data_id}) # Start the task in background thread threading.Thread( target=process_data, args=(data_id, task_id), daemon=True ).start() return { "message": f"Started processing {data_id}", "task_id": task_id, "status": "processing" } elif action == "cleanup": # Start tracking cleanup task task_id = app.add_async_task("cleanup", {}) # Start cleanup in background thread threading.Thread( target=cleanup_task, args=(task_id,), daemon=True ).start() return { "message": "Started cleanup", "task_id": task_id } elif action == "status": # Get current status task_info = app.get_async_task_info() current_status = app.get_current_ping_status() return { "ping_status": current_status.value, "active_tasks": task_info["active_count"], "running_jobs": task_info["running_jobs"] } else: return { "message": "Simple BedrockAgentCore Agent", "available_actions": ["process", "cleanup", "status"], "usage": "Send {'action': 'process', 'data_id': 'my_data'}" } if __name__ == "__main__": print("Starting simple BedrockAgentCore agent...") print("The agent will automatically report 'HealthyBusy' when processing tasks") app.run() ``` -------------------------------- ### Run Agent with Code Interpreter Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-code-interpreter.html This example initializes the Code Interpreter tool, creates an agent configured for code execution, sends a prompt to calculate Fibonacci numbers, and prints the agent's response. ```python prompt = "Calculate the first 10 Fibonacci numbers." print(f"\nPrompt: {prompt}\n") response = agent(prompt) print(response.message["content"][0]["text"]) ``` -------------------------------- ### Use Recording-Enabled Browser for Agent Interaction Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-browser.html Starts a browser session using the previously created recording-enabled browser. Performs a series of navigation and interaction tasks, with all actions automatically recorded and stored in S3 upon session completion. This example uses AWS Strands but can be adapted for Playwright or other libraries. ```python import time from strands import Agent from strands_tools.browser import AgentCoreBrowser # Reuse the existing browser created with recording; ensure identifier is used browser_identifier = "your-browser-identifier" region = "us-west-2" browser_tool = AgentCoreBrowser(region=region, identifier=browser_identifier) try: browser_tool.identifier = browser_identifier except Exception: pass agent = Agent(tools=[browser_tool.browser]) prompt = ( "1) Open https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html; " "in the left navigation open 'Use Amazon Bedrock AgentCore built-in tools to interact with your applications', then 'AgentCore Browser: interact with web applications'; scroll down and up briefly. " "2) Go to https://pypi.org, search 'bedrock-agentcore', open the project page, then click 'Release history'. " "3) Go to https://github.com/awslabs/amazon-bedrock-agentcore-samples/tree/main, open 01-tutorials -> 05-AgentCore-tools -> 02-Agent-Core-browser-tool -> 01-browser-with-NovaAct, " "then open 'live_view_with_nova_act.py' (or 'basic_browser_with_nova_act.py') and scroll. Keep all actions in the active tab; be resilient to layout changes. Summarize visited pages." ) print(f"\nPrompt: {prompt}\n") response = agent(prompt) print("\nAgent Response:") print(response.message["content"][0]["text"]) ``` -------------------------------- ### Full Agent Import with Deployment Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/import-agent/configuration.html Example demonstrating a full agent import configuration, including AWS region, target platform, output directory, deployment, and verbose logging for the 'langchain' platform. ```bash agentcore import-agent \ --region us-west-2 \ --agent-id ABCD1234 \ --agent-alias-id PRODALIASID \ --target-platform langchain \ --output-dir ./production-agent \ --deploy-runtime \ --run-option runtime \ --verbose ``` -------------------------------- ### Install Packages with CodeInterpreter Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Install Python packages into the Code Interpreter sandbox environment. Provide a list of package names to install. ```python client.install_packages(['pandas', 'matplotlib']) ``` -------------------------------- ### Get Policy Generation Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/cli.html Get the status and details of a specific policy generation. ```APIDOC ## Get Policy Generation ### Description Get the status and details of a policy generation. ### Usage ``` agentcore policy get-policy-generation [OPTIONS] ``` ### Options * `--policy-engine-id, -e TEXT`: Policy engine ID (required). * `--generation-id, -g TEXT`: Generation ID (required). * `--region, -r TEXT`: AWS region (defaults to us-east-1). ### Example ```bash agentcore policy get-policy-generation \ --policy-engine-id "testPolicyEngine-abc123" \ --generation-id "gen-abc123" ``` ``` -------------------------------- ### Create a New AgentCore Project (Interactive) Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/create/quickstart.html Run the `agentcore create` command in interactive mode to scaffold a new AgentCore project. You will be prompted for project details such as name, SDK, template, IaC provider, model provider, and optional integrations. ```bash agentcore create ``` -------------------------------- ### Execute Gateway Setup Script Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/gateway/quickstart.html Command to run the Python script that sets up the Gateway and Lambda target. The process typically takes a few minutes and provides progress updates. ```bash python setup_gateway.py ``` -------------------------------- ### Install CrewAI and CrewAI-Tools Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/runtime-framework-agents.html Install the necessary libraries for using CrewAI with Bedrock AgentCore. ```bash pip install crewai crewai-tools ``` -------------------------------- ### Initialize and Test AgentCore Runtime in Notebook Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/notebook.html Import the Runtime class, initialize it, configure your agent's entrypoint and execution role, and then test it locally by launching a container and invoking it with a prompt. ```python # Import the notebook Runtime class from bedrock_agentcore_starter_toolkit.notebook import Runtime # Initialize runtime = Runtime() # Configure your agent config = runtime.configure( entrypoint="my_agent.py", execution_role="arn:aws:iam::123456789012:role/MyExecutionRole" ) # Test locally local_result = runtime.launch(local=True) print(f"Local container: {local_result.tag}") # Test your agent response = runtime.invoke({"prompt": "Hello from notebook!"}) print(response) ``` -------------------------------- ### Install LangGraph and Langchain-AWS Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/examples/runtime-framework-agents.html Install the necessary libraries for using LangGraph with Bedrock AgentCore. ```bash pip install langchain-aws langgraph ``` -------------------------------- ### Policy Setup Script Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/policy/quickstart.html This script configures and saves the policy engine setup. It requires the gateway, policy engine, policy details, region, client info, and refund limit to be defined. The configuration is saved to 'config.json'. ```python print("āœ“ Policy Engine attached to Gateway\n") # Step 8: Save configuration config = { "gateway_url": gateway["gatewayUrl"], "gateway_id": gateway["gatewayId"], "gateway_arn": gateway["gatewayArn"], "policy_engine_id": engine["policyEngineId"], "policy_engine_arn": engine["policyEngineArn"], "policy_id": policy["policyId"], "region": region, "client_info": cognito_response["client_info"], "refund_limit": refund_limit } with open("config.json", "w") as f: json.dump(config, f, indent=2) print("=" * 60) print("āœ… Setup complete!") print(f"Gateway URL: {gateway['gatewayUrl']}") print(f"Policy Engine ID: {engine['policyEngineId']}") print(f"Refund limit: ${refund_limit}") print("\nConfiguration saved to: config.json") print("\nNext step: Run 'python test_policy.py' to test your Policy") print("=" * 60) return config if __name__ == "__main__": setup_policy() ``` -------------------------------- ### Install Packages Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Installs Python packages in the code interpreter environment. Supports version specifiers and upgrades. ```APIDOC ## install_packages ### Description Installs Python packages in the code interpreter environment. Supports version specifiers and upgrades. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **packages** (List[str]) - Required - A list of package names to install. Can include version specifiers (e.g., ['pandas>=2.0', 'numpy', 'scikit-learn==1.3.0']). - **upgrade** (bool) - Optional - If True, adds the --upgrade flag to update existing packages. Defaults to False. ### Request Example ```python # Install multiple packages client.install_packages(['pandas', 'matplotlib', 'scikit-learn']) # Install with version constraints client.install_packages(['pandas>=2.0', 'numpy<2.0']) # Upgrade existing packages client.install_packages(['pandas'], upgrade=True) ``` ### Response #### Success Response (200) Dict containing the command execution result with stdout/stderr. #### Response Example ```json { "stdout": "Successfully installed ...", "stderr": "" } ``` ``` -------------------------------- ### Select Target Platform (Step 5) Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/import-agent/quickstart.html Choose the target platform for your imported agent, such as Strands or LangChain/LangGraph. ```bash ? Choose target platform: > strands (1.0.x) langchain (0.3.x) + langgraph (0.5.x) ``` -------------------------------- ### Install A2A packages with pip Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/a2a.html Install the necessary Python packages for A2A development and Bedrock AgentCore integration. ```bash pip install strands-agents[a2a] pip install bedrock-agentcore pip install strands-agents-tools ``` -------------------------------- ### Run the script Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-browser.html Execute the Python script to start the browser session and navigate to the specified URL. ```bash python direct_browser_playwright.py ``` -------------------------------- ### Install Python Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/gateway/quickstart.html Install the necessary Python libraries for working with Bedrock AgentCore, Boto3, and Strands Agents. ```python pip install boto3 pip install bedrock-agentcore-starter-toolkit pip install strands-agents ``` -------------------------------- ### Start A2A Server Locally Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/a2a.html Run your A2A server locally. Ensure the server starts on port 9000. ```bash python my_a2a_server.py ``` -------------------------------- ### Start Browser Session Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Initializes a new browser sandbox session with various configuration options. ```APIDOC ## start ### Description Start a browser sandbox session. This method initializes a new browser session with the provided parameters. ### Method `start` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **identifier** (`Optional[str]`) - Optional - The browser sandbox identifier to use. Can be DEFAULT_IDENTIFIER or a custom browser ID from create_browser. - **name** (`Optional[str]`) - Optional - A name for this session. - **session_timeout_seconds** (`Optional[int]`) - Optional - The timeout for the session in seconds. Range: 1-28800 (8 hours). Default: 3600 (1 hour). - **viewport** (`Optional[Union[ViewportConfiguration, Dict[str, int]]]`) - Optional - The viewport dimensions. Can be a ViewportConfiguration dataclass or a plain dict. - **proxy_configuration** (`Optional[Union[ProxyConfiguration, Dict[str, Any]]]`) - Optional - Proxy configuration for routing browser traffic through external proxy servers. Can be a ProxyConfiguration dataclass or a plain dict matching the API shape. - **extensions** (`Optional[List[Union[BrowserExtension, Dict[str, Any]]]]`) - Optional - List of browser extensions to load into the session. Each element can be a BrowserExtension dataclass or a plain dict: [{"location": {"s3": {"bucket": "...", "prefix": "..."}}}] - **profile_configuration** (`Optional[Union[ProfileConfiguration, Dict[str, Any]]]`) - Optional - Profile configuration for persisting browser state across sessions. Can be a ProfileConfiguration dataclass or a plain dict. - **enterprise_policies** (`Optional[List[Union[EnterprisePolicy, Dict[str, Any]]]]`) - Optional - Chromium enterprise policies at recommended enforcement level. Up to 10 policy files, each .json and max 5MB, from a same-region S3 bucket. - **certificates** (`Optional[List[Union[Certificate, Dict[str, Any]]]]`) - Optional - Root CA certificates from Secrets Manager for the browser session to trust. ### Returns - **str** - The session ID of the newly created session. ### Request Example ```python # Use system browser session_id = client.start() # Use custom browser with Web Bot Auth session_id = client.start( identifier="my-browser-abc123", viewport={'width': 1920, 'height': 1080}, session_timeout_seconds=7200 # 2 hours ) # Use proxy configuration session_id = client.start( proxy_configuration={ "proxies": [ { "externalProxy": { "server": "proxy.example.com", "port": 8080, "domainPatterns": [".example.com"], } } ], "bypass": {"domainPatterns": [".amazonaws.com"]} } ) ``` ``` -------------------------------- ### Install AgentCore Dependencies Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/memory/quickstart.html Install the necessary AgentCore libraries for Python. Ensure you have Python 3.10+ and AWS credentials configured. ```bash mkdir agentcore-memory-quickstart cd agentcore-memory-quickstart python -m venv .venv source .venv/bin/activate pip install bedrock-agentcore pip install bedrock-agentcore-starter-toolkit ``` -------------------------------- ### GET /ping Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/runtime.html Handles GET requests to the /ping endpoint, typically used for health checks to determine if the service is running. ```APIDOC ## GET /ping ### Description Responds to health check requests. ### Method GET ### Endpoint /ping ### Response (Details not provided in source, but typically returns a status indicating the service is operational) ``` -------------------------------- ### BrowserClient.start Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/tools.html Starts a new browser session with optional configurations for viewport, session timeout, proxy, extensions, profile, enterprise policies, and certificates. ```APIDOC ## start ### Description Starts a new browser session. You can optionally provide configurations for the browser environment. ### Method `start` ### Parameters - **identifier** (Optional[str]): The identifier for the browser to use. Defaults to `DEFAULT_IDENTIFIER` or a custom ID from `create_browser`. - **name** (Optional[str]): A name for this session. Defaults to a generated name. - **session_timeout_seconds** (Optional[int]): The timeout for the session in seconds. Range: 1-28800 (8 hours). Default: 3600 (1 hour). - **viewport** (Optional[Union[ViewportConfiguration, Dict[str, int]]]): The viewport dimensions. Can be a `ViewportConfiguration` dataclass or a plain dict: `{'width': 1920, 'height': 1080}`. - **proxy_configuration** (Optional[Union[ProxyConfiguration, Dict[str, Any]]]): Proxy configuration for routing browser traffic. Can be a `ProxyConfiguration` dataclass or a plain dict matching the API shape. - **extensions** (Optional[List[Union[BrowserExtension, Dict[str, Any]]]]): List of browser extensions to load. Each element can be a `BrowserExtension` dataclass or a plain dict: `[{"location": {"s3": {"bucket": "...", "prefix": "..."}}}]`. - **profile_configuration** (Optional[Union[ProfileConfiguration, Dict[str, Any]]]): Profile configuration for persisting browser state. Can be a `ProfileConfiguration` dataclass or a plain dict: `{"profileIdentifier": "my-profile-id"}`. - **enterprise_policies** (Optional[List[Union[EnterprisePolicy, Dict]]]): Chromium enterprise policies at recommended enforcement level. Up to 10 policy files, each .json and max 5MB, from a same-region S3 bucket. - **certificates** (Optional[List[Union[Certificate, Dict]]]): Root CA certificates from Secrets Manager for the browser session to trust. ### Returns - **str**: The session ID of the newly created session. ### Example ```python # Use system browser session_id = client.start() # Use custom browser with Web Bot Auth session_id = client.start( identifier="my-browser-abc123", viewport={'width': 1920, 'height': 1080}, session_timeout_seconds=7200 # 2 hours ) # Use proxy configuration session_id = client.start( proxy_configuration={ "proxies": [{ "externalProxy": { "server": "proxy.example.com", "port": 8080, "domainPatterns": [".example.com"], } }], "bypass": {"domainPatterns": [".amazonaws.com"]} } ) ``` ``` -------------------------------- ### Initialize Boto3 Client for Code Execution Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/builtin-tools/quickstart-code-interpreter.html Sets up the AWS SDK (Boto3) client for the `bedrock-agentcore` service in the `us-west-2` region to prepare for direct code execution. ```python import boto3 import json # Code to execute code_to_execute = """ print("Hello World!!!") """ # Initialize the bedrock-agentcore client client = boto3.client( "bedrock-agentcore", region_name="us-west-2" ) ``` -------------------------------- ### Start WebSocket Agent Locally Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/overview.html Command to start a local WebSocket agent. Ensure the agent script is named 'websocket_echo_agent.py'. ```bash # Terminal 1: Start your agent python websocket_echo_agent.py ``` -------------------------------- ### Get Verbose Status Output Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/api-reference/cli.html Use the --verbose flag to get detailed JSON output for the agentcore status command. ```bash agentcore status --verbose ``` -------------------------------- ### Configure, Launch, and Invoke Agent from Notebook Source: https://aws.github.io/bedrock-agentcore-starter-toolkit/user-guide/runtime/notebook.html This snippet shows how to use the Runtime class in a notebook to configure an agent defined in 'my_agent.py', launch it locally, and then test its functionality by invoking it with a specific prompt. ```python from bedrock_agentcore_starter_toolkit.notebook import Runtime runtime = Runtime() # Configure runtime.configure( entrypoint="my_agent.py", execution_role="arn:aws:iam::123456789012:role/MyRole" ) # Launch locally for testing runtime.launch(local=True) # Test the agent response = runtime.invoke({"prompt": "Test from notebook"}) print(response) # {"result": "You said: Test from notebook"} ```