Examples

The SDK includes several examples to help you get started. These examples demonstrate different features and use cases for the SDK.

Simple Example

The simple example demonstrates how to create a basic agent with time and math functions.

 1"""
 2Simple example of using the Bedrock Agents SDK.
 3"""
 4from bedrock_agents_sdk import Client, Agent, ActionGroup, Message
 5import datetime
 6
 7# Define a function - this will run locally on your machine
 8def get_time() -> dict:
 9    """Get the current time"""
10    now = datetime.datetime.now()
11    return {"time": now.strftime("%H:%M:%S")}
12
13def get_date() -> dict:
14    """Get the current date"""
15    now = datetime.datetime.now()
16    return {"date": now.strftime("%Y-%m-%d")}
17
18def add_numbers(a: int, b: int) -> dict:
19    """Add two numbers together
20    
21    :param a: The first number
22    :param b: The second number
23    """
24    return {"result": a + b}
25
26def main():
27    # Create action groups
28    time_group = ActionGroup(
29        name="TimeService",
30        description="Provides time-related information",
31        functions=[get_time, get_date]
32    )
33    
34    math_group = ActionGroup(
35        name="MathService",
36        description="Provides mathematical operations",
37        functions=[add_numbers]
38    )
39    
40    # Create the agent with action groups
41    agent = Agent(
42        name="SimpleAgent",
43        model="anthropic.claude-3-sonnet-20240229-v1:0",
44        instructions="You are a helpful assistant that can tell time and do simple math.",
45        action_groups=[time_group, math_group]
46    )
47    
48    # Create the client
49    client = Client(verbosity="verbose")
50    
51    # Start interactive chat session
52    client.chat(agent=agent)
53
54if __name__ == "__main__":
55    main() 

Action Groups Example

The action groups example demonstrates how to use action groups to organize your agent’s functions.

  1"""
  2Example of using action groups with the Bedrock Agents SDK.
  3"""
  4import datetime
  5from typing import List, Dict, Any
  6from bedrock_agents_sdk import Client, Agent, ActionGroup, Message
  7
  8# Define action group functions
  9def get_weather(location: str) -> Dict[str, Any]:
 10    """
 11    Get the current weather for a location.
 12    
 13    Args:
 14        location: The city or location to get weather for
 15        
 16    Returns:
 17        Dictionary with weather information
 18    """
 19    # In a real application, this would call a weather API
 20    # This is a mock implementation for demonstration
 21    weather_data = {
 22        "location": location,
 23        "temperature": 72,
 24        "condition": "Sunny",
 25        "humidity": 45,
 26        "wind_speed": 8
 27    }
 28    return weather_data
 29
 30def get_forecast(location: str, days: int = 3) -> Dict[str, Any]:
 31    """
 32    Get the weather forecast for a location.
 33    
 34    Args:
 35        location: The city or location to get forecast for
 36        days: Number of days for the forecast (default: 3)
 37        
 38    Returns:
 39        Dictionary with forecast information
 40    """
 41    # Mock implementation
 42    forecast = []
 43    for i in range(days):
 44        day = {
 45            "day": (datetime.datetime.now() + datetime.timedelta(days=i)).strftime("%A"),
 46            "temperature": 70 + i * 2,
 47            "condition": "Partly Cloudy" if i % 2 == 0 else "Sunny"
 48        }
 49        forecast.append(day)
 50    
 51    return {
 52        "location": location,
 53        "forecast": forecast
 54    }
 55
 56def main():
 57    # Create the client
 58    client = Client()
 59    
 60    # Create action groups
 61    weather_group = ActionGroup(
 62        name="WeatherService",
 63        description="Provides weather information and forecasts",
 64        functions=[get_weather, get_forecast]
 65    )
 66    
 67    # Create the agent
 68    agent = Agent(
 69        name="WeatherAgent",
 70        model="us.anthropic.claude-3-5-sonnet-20241022-v2:0",
 71        instructions="You are a helpful weather assistant. Use the WeatherService action group to provide weather information when asked.",
 72        action_groups=[weather_group]
 73    )
 74    
 75    # Run the agent with a user query
 76    result = client.run(
 77        agent=agent,
 78        messages=[
 79            {
 80                "role": "user",
 81                "content": "What's the weather like in Seattle? Also, can you give me a 5-day forecast?"
 82            }
 83        ]
 84    )
 85    
 86    print("\nResponse from agent:")
 87    print("-" * 50)
 88    print(result["response"])
 89    print("-" * 50)
 90    
 91    # Interactive chat session
 92    print("\nChat with the Weather Agent (type 'exit' to quit):")
 93    messages = []
 94    
 95    while True:
 96        user_input = input("\nYou: ")
 97        if user_input.lower() == "exit":
 98            break
 99            
100        messages.append({"role": "user", "content": user_input})
101        
102        result = client.run(agent=agent, messages=messages)
103        assistant_message = result["response"]
104        
105        print(f"\nWeather Agent: {assistant_message}")
106        
107        messages.append({"role": "assistant", "content": assistant_message})
108
109if __name__ == "__main__":
110    main() 

Configuration Methods Example

This example demonstrates the four different ways to configure agents with action groups, highlighting the recommended ActionGroup-first approach.

  1"""
  2Example demonstrating the different ways to configure agents with action groups.
  3
  4This example shows all four approaches to configuring agents:
  51. Using ActionGroup objects in the constructor (recommended)
  62. Adding ActionGroup objects after creation
  73. Using a functions dictionary
  84. Using a functions list
  9"""
 10import datetime
 11from typing import Dict, Any
 12from bedrock_agents_sdk import Client, Agent, ActionGroup, Message
 13
 14# Define some example functions
 15def get_weather(location: str) -> Dict[str, Any]:
 16    """Get the current weather for a location"""
 17    # Mock implementation
 18    return {
 19        "location": location,
 20        "temperature": 72,
 21        "condition": "Sunny"
 22    }
 23
 24def get_forecast(location: str, days: int = 3) -> Dict[str, Any]:
 25    """Get the weather forecast for a location"""
 26    # Mock implementation
 27    forecast = []
 28    for i in range(days):
 29        day = {
 30            "day": (datetime.datetime.now() + datetime.timedelta(days=i)).strftime("%A"),
 31            "temperature": 70 + i * 2,
 32            "condition": "Partly Cloudy" if i % 2 == 0 else "Sunny"
 33        }
 34        forecast.append(day)
 35    
 36    return {
 37        "location": location,
 38        "forecast": forecast
 39    }
 40
 41def get_time() -> Dict[str, Any]:
 42    """Get the current time"""
 43    now = datetime.datetime.now()
 44    return {"time": now.strftime("%H:%M:%S")}
 45
 46def get_date() -> Dict[str, Any]:
 47    """Get the current date"""
 48    now = datetime.datetime.now()
 49    return {"date": now.strftime("%Y-%m-%d")}
 50
 51def main():
 52    # Create a client
 53    client = Client(verbosity="verbose")
 54    
 55    # Method 1: Using ActionGroup objects in the constructor (recommended)
 56    print("\n=== Method 1: ActionGroup objects in constructor (recommended) ===")
 57    
 58    # Create action groups
 59    weather_group = ActionGroup(
 60        name="WeatherService",
 61        description="Provides weather information and forecasts",
 62        functions=[get_weather, get_forecast]
 63    )
 64    
 65    time_group = ActionGroup(
 66        name="TimeService",
 67        description="Provides time-related functions",
 68        functions=[get_time, get_date]
 69    )
 70    
 71    # Create the agent with action groups
 72    agent1 = Agent(
 73        name="Method1Agent",
 74        model="anthropic.claude-3-sonnet-20240229-v1:0",
 75        instructions="You are a helpful assistant that can provide weather and time information.",
 76        action_groups=[weather_group, time_group]
 77    )
 78    
 79    # Print information about the agent
 80    print(f"Agent has {len(agent1.action_groups)} action groups:")
 81    for ag in agent1.action_groups:
 82        print(f"  - {ag.name}: {len(ag.functions)} functions")
 83    
 84    # Method 2: Adding ActionGroup objects after creation
 85    print("\n=== Method 2: Adding ActionGroup objects after creation ===")
 86    
 87    # Create the agent
 88    agent2 = Agent(
 89        name="Method2Agent",
 90        model="anthropic.claude-3-sonnet-20240229-v1:0",
 91        instructions="You are a helpful assistant that can provide weather and time information."
 92    )
 93    
 94    # Create and add action groups
 95    weather_group = ActionGroup(
 96        name="WeatherService",
 97        description="Provides weather information and forecasts",
 98        functions=[get_weather, get_forecast]
 99    )
100    
101    agent2.add_action_group(weather_group)
102    
103    time_group = ActionGroup(
104        name="TimeService",
105        description="Provides time-related functions",
106        functions=[get_time, get_date]
107    )
108    
109    agent2.add_action_group(time_group)
110    
111    # Print information about the agent
112    print(f"Agent has {len(agent2.action_groups)} action groups:")
113    for ag in agent2.action_groups:
114        print(f"  - {ag.name}: {len(ag.functions)} functions")
115    
116    # Method 3: Using a functions dictionary
117    print("\n=== Method 3: Using a functions dictionary ===")
118    
119    # Create the agent with a functions dictionary
120    agent3 = Agent(
121        name="Method3Agent",
122        model="anthropic.claude-3-sonnet-20240229-v1:0",
123        instructions="You are a helpful assistant that can provide weather and time information.",
124        functions={
125            "WeatherService": [get_weather, get_forecast],
126            "TimeService": [get_time, get_date]
127        }
128    )
129    
130    # Print information about the agent
131    print(f"Agent has {len(agent3.action_groups)} action groups:")
132    for ag in agent3.action_groups:
133        print(f"  - {ag.name}: {len(ag.functions)} functions")
134    
135    # Method 4: Using a functions list
136    print("\n=== Method 4: Using a functions list ===")
137    
138    # Create the agent with a functions list
139    agent4 = Agent(
140        name="Method4Agent",
141        model="anthropic.claude-3-sonnet-20240229-v1:0",
142        instructions="You are a helpful assistant that can provide weather and time information.",
143        functions=[get_weather, get_forecast, get_time, get_date]
144    )
145    
146    # Print information about the agent
147    print(f"Agent has {len(agent4.action_groups)} action groups:")
148    for ag in agent4.action_groups:
149        print(f"  - {ag.name}: {len(ag.functions)} functions")
150    
151    # Print functions
152    print(f"Agent has {len(agent4.functions)} functions:")
153    for func in agent4.functions:
154        print(f"  - {func.name} (action group: {func.action_group or 'DefaultActions'})")
155    
156    # Run a simple test with the recommended approach (Method 1)
157    print("\n=== Running a test with the recommended approach (Method 1) ===")
158    result = client.run(
159        agent=agent1,
160        messages=[
161            {
162                "role": "user",
163                "content": "What's the weather like in Seattle? Also, what time is it now?"
164            }
165        ]
166    )
167    
168    print("\nResponse from agent:")
169    print("-" * 50)
170    print(result["response"])
171    print("-" * 50)
172
173if __name__ == "__main__":
174    main() 

Parameter Handling Example

The parameter handling example demonstrates how to work with function parameters and validation.

  1"""
  2Example of deploying a Bedrock Agent with various parameter types.
  3
  4This example demonstrates how to:
  51. Define functions with different parameter types (string, int, float, bool)
  62. Use type hints to ensure proper parameter conversion in Lambda functions
  73. Provide default values for optional parameters
  84. Deploy an agent that correctly handles parameters in Lambda
  9"""
 10import os
 11from bedrock_agents_sdk import Client, Agent, ActionGroup, Message
 12
 13# Define functions with various parameter types
 14def calculate(operation: str, a: int, b: int) -> dict:
 15    """
 16    Perform a mathematical calculation
 17    
 18    :param operation: The operation to perform (add, subtract, multiply, divide)
 19    :param a: The first number
 20    :param b: The second number
 21    """
 22    if operation == "add":
 23        result = a + b
 24    elif operation == "subtract":
 25        result = a - b
 26    elif operation == "multiply":
 27        result = a * b
 28    elif operation == "divide":
 29        if b == 0:
 30            return {"error": "Cannot divide by zero"}
 31        result = a / b
 32    else:
 33        return {"error": f"Unknown operation: {operation}"}
 34    
 35    return {
 36        "operation": operation,
 37        "a": a,
 38        "b": b,
 39        "result": result
 40    }
 41
 42def format_text(text: str, uppercase: bool = False, max_length: int = 100) -> dict:
 43    """
 44    Format a text string
 45    
 46    :param text: The text to format
 47    :param uppercase: Whether to convert the text to uppercase
 48    :param max_length: Maximum length of the text (will be truncated if longer)
 49    """
 50    # Truncate text if needed
 51    if len(text) > max_length:
 52        text = text[:max_length]
 53    
 54    # Convert to uppercase if requested
 55    if uppercase:
 56        text = text.upper()
 57    
 58    return {
 59        "original_length": len(text),
 60        "formatted_text": text,
 61        "uppercase": uppercase,
 62        "max_length": max_length
 63    }
 64
 65def calculate_statistics(numbers: str, precision: float = 2.0) -> dict:
 66    """
 67    Calculate statistics for a list of numbers
 68    
 69    :param numbers: Comma-separated list of numbers (e.g., "1, 2, 3, 4, 5")
 70    :param precision: Number of decimal places for results (default: 2.0)
 71    """
 72    # Parse the input string into a list of numbers
 73    try:
 74        # Split by comma and convert each item to float
 75        num_list = [float(n.strip()) for n in numbers.split(",")]
 76        
 77        if not num_list:
 78            return {"error": "No numbers provided"}
 79        
 80        # Calculate statistics
 81        count = len(num_list)
 82        total = sum(num_list)
 83        mean = total / count
 84        
 85        # Sort the list for median and min/max
 86        sorted_nums = sorted(num_list)
 87        
 88        # Calculate median
 89        if count % 2 == 0:
 90            # Even number of items
 91            median = (sorted_nums[count//2 - 1] + sorted_nums[count//2]) / 2
 92        else:
 93            # Odd number of items
 94            median = sorted_nums[count//2]
 95        
 96        # Round results to specified precision
 97        precision = int(precision)  # Convert to integer for rounding
 98        
 99        return {
100            "count": count,
101            "min": round(min(num_list), precision),
102            "max": round(max(num_list), precision),
103            "sum": round(total, precision),
104            "mean": round(mean, precision),
105            "median": round(median, precision),
106            "numbers": num_list
107        }
108    except Exception as e:
109        return {"error": f"Error processing numbers: {str(e)}"}
110
111def main():
112    # Create action groups
113    math_group = ActionGroup(
114        name="MathActions",
115        description="Functions for performing mathematical calculations",
116        functions=[calculate]
117    )
118    
119    text_group = ActionGroup(
120        name="TextActions",
121        description="Functions for formatting and manipulating text",
122        functions=[format_text]
123    )
124    
125    stats_group = ActionGroup(
126        name="StatisticsActions",
127        description="Functions for calculating statistics on sets of numbers",
128        functions=[calculate_statistics]
129    )
130    
131    # Create the agent with action groups
132    agent = Agent(
133        name="ParameterDemoAgent",
134        model="anthropic.claude-3-sonnet-20240229-v1:0",
135        instructions="""You are a helpful assistant that demonstrates parameter handling.
136        
137        You can:
138        1. Perform calculations using the calculate function
139        2. Format text using the format_text function
140        3. Calculate statistics for a list of numbers using the calculate_statistics function
141        
142        Please use these functions to help users with their requests.
143        """,
144        action_groups=[math_group, text_group, stats_group]
145    )
146    
147    # Test the agent locally before deploying
148    print("Testing agent locally before deployment...")
149    client = Client(verbosity="normal")
150    
151    # Test with different parameter types
152    test_messages = [
153        "Calculate 25 + 17",
154        "Format this text in uppercase: Hello, world!",
155        "Calculate statistics for these numbers: 10, 15, 7, 22, 18, 5, 12, 30, 25, 20"
156    ]
157    
158    for message in test_messages:
159        print(f"\nTesting: {message}")
160        result = client.run(agent=agent, message=message)
161        print("-" * 50)
162        print(result["response"])
163        print("-" * 50)
164    
165    # Deploy the agent to AWS
166    print("\nDeploying agent to AWS...")
167    
168    # Generate the SAM template and supporting files
169    # The output directory will default to "./parameterdemoagent_deployment"
170    template_path = agent.deploy(
171        description="Parameter handling demonstration agent",
172        # Uncomment the following lines to automatically build and deploy
173        # auto_build=True,
174        # auto_deploy=True
175    )
176    
177    print("\nAfter deployment, you can test your agent in the AWS Console:")
178    print("1. Go to the Amazon Bedrock console")
179    print("2. Navigate to Agents")
180    print("3. Find your agent named 'ParameterDemoAgent'")
181    print("4. Click on the agent and use the 'Test' tab to interact with it")
182    
183    print("\nTry these test messages:")
184    for message in test_messages:
185        print(f"- {message}")
186
187if __name__ == "__main__":
188    main() 

Code Interpreter Example

The code interpreter example demonstrates how to use the Code Interpreter feature to write and execute Python code.

 1"""
 2Code Interpreter Example
 3
 4This example demonstrates how to use the Code Interpreter feature of Amazon Bedrock Agents.
 5The Code Interpreter allows the agent to write and execute Python code to solve problems.
 6"""
 7
 8import os
 9from bedrock_agents_sdk import Client, Agent, Message
10
11def main():
12    """
13    Main function to demonstrate Code Interpreter functionality.
14    """
15    # Create an agent with Code Interpreter enabled
16    agent = Agent(
17        name="CodeInterpreterAgent",
18        model="anthropic.claude-3-5-sonnet-20241022-v2:0",
19        instructions="""
20        You are a helpful data analysis assistant that can write and execute Python code.
21        When asked to analyze data or solve mathematical problems, use Python code to provide solutions.
22        Create visualizations when appropriate to help explain your findings.
23        """,
24        enable_code_interpreter=True  # This enables the Code Interpreter feature
25    )
26
27    # Create a client with raw trace level to see the code being executed
28    client = Client(
29        verbosity="normal",
30        trace_level="raw"  # Use "raw" to see the actual code being executed
31    )
32
33    # Example 1: Simple calculation
34    print("\n=== Example 1: Simple Calculation ===")
35    response = client.run(
36        agent=agent,
37        message="Calculate the first 10 Fibonacci numbers and show them in a table."
38    )
39    print(f"Response: {response['response']}")
40
41    # Example 2: Data analysis with a CSV file
42    print("\n=== Example 2: Data Analysis with CSV ===")
43    
44    # Create a sample CSV file if it doesn't exist
45    csv_path = "sample_data.csv"
46    if not os.path.exists(csv_path):
47        with open(csv_path, "w") as f:
48            f.write("Month,Sales,Expenses\n")
49            f.write("January,10000,8000\n")
50            f.write("February,12000,8500\n")
51            f.write("March,15000,9000\n")
52            f.write("April,9000,7500\n")
53            f.write("May,11000,8200\n")
54            f.write("June,13500,8800\n")
55    
56    # Add the CSV file to the agent
57    agent.add_file_from_path(csv_path)
58    
59    # Run the agent with a data analysis request
60    response = client.run(
61        agent=agent,
62        message="""
63        Please analyze the sales data in the CSV file:
64        1. Calculate the total sales and expenses
65        2. Calculate the profit for each month
66        3. Create a bar chart showing sales and expenses by month
67        4. Which month had the highest profit margin?
68        """
69    )
70    print(f"Response: {response['response']}")
71    
72    # Save any generated files
73    if response.get("files"):
74        print(f"\nThe agent generated {len(response['files'])} file(s)")
75        saved_paths = response["save_all_files"]("output")
76        print(f"Files saved to: {', '.join(saved_paths)}")
77
78    # Example 3: Interactive chat with Code Interpreter
79    print("\n=== Example 3: Interactive Chat with Code Interpreter ===")
80    print("Starting interactive chat. Type 'exit' to quit.")
81    
82    # Start an interactive chat session
83    client.chat(agent=agent)
84
85if __name__ == "__main__":
86    main() 

Plugin Example

The plugin example demonstrates how to use plugins to extend your agent’s capabilities.

  1"""
  2Example of using plugins with the Bedrock Agents SDK.
  3"""
  4import datetime
  5from bedrock_agents_sdk import BedrockAgents, Agent, Message
  6from bedrock_agents_sdk import SecurityPlugin, GuardrailPlugin, KnowledgeBasePlugin
  7from bedrock_agents_sdk.plugins.base import BedrockAgentsPlugin
  8
  9# Define a function
 10def get_time() -> dict:
 11    """Get the current time"""
 12    now = datetime.datetime.now()
 13    return {"time": now.strftime("%H:%M:%S")}
 14
 15# Define a custom plugin
 16class LoggingPlugin(BedrockAgentsPlugin):
 17    """A plugin that logs all API calls"""
 18    
 19    def __init__(self, log_file="api_calls.log"):
 20        self.log_file = log_file
 21    
 22    def pre_invoke(self, params):
 23        """Log the parameters before invocation"""
 24        with open(self.log_file, "a") as f:
 25            f.write(f"API Call Parameters: {params}\n")
 26        return params
 27    
 28    def post_invoke(self, response):
 29        """Log the response after invocation"""
 30        with open(self.log_file, "a") as f:
 31            f.write(f"API Response: {response}\n")
 32        return response
 33    
 34    def pre_deploy(self, template):
 35        """Log the template before deployment"""
 36        with open(self.log_file, "a") as f:
 37            f.write(f"Deployment Template: {template}\n")
 38        return template
 39
 40def main():
 41    # Create the client
 42    client = BedrockAgents(verbosity="verbose")
 43    
 44    # Create plugins
 45    kb_plugin = KnowledgeBasePlugin(
 46        knowledge_base_id="your-kb-id",
 47        description="Knowledge base containing company documentation"
 48    )
 49    
 50    guardrail_plugin = GuardrailPlugin(guardrail_id="your-guardrail-id")
 51    
 52    # Create a custom logging plugin
 53    logging_plugin = LoggingPlugin(log_file="api_calls.log")
 54    
 55    # Create a security plugin (uncomment to use)
 56    # security_plugin = SecurityPlugin(customer_encryption_key_arn="your-kms-key-arn")
 57    
 58    # Create the agent with plugins
 59    agent = Agent(
 60        name="PluginAgent",
 61        model="us.anthropic.claude-3-5-sonnet-20241022-v2:0",
 62        instructions="You are a helpful assistant that can tell the time.",
 63        functions=[get_time],
 64        plugins=[
 65            kb_plugin,
 66            guardrail_plugin,
 67            logging_plugin,
 68            # security_plugin  # Uncomment to use
 69        ]
 70    )
 71    
 72    # Run the agent
 73    result = client.run(
 74        agent=agent,
 75        messages=[
 76            {
 77                "role": "user",
 78                "content": "What time is it now?"
 79            }
 80        ]
 81    )
 82    
 83    print("\nResponse from agent:")
 84    print("-" * 50)
 85    print(result["response"])
 86    print("-" * 50)
 87    
 88    # Deploy the agent to AWS
 89    print("\nDeploying agent to AWS...")
 90    
 91    # All plugins will be applied to the deployment
 92    # template_path = agent.deploy(
 93    #     description="Plugin example agent",
 94    #     # Uncomment the following lines to automatically build and deploy
 95    #     # auto_build=True,
 96    #     # auto_deploy=True
 97    # )
 98
 99if __name__ == "__main__":
100    main() 

Dependency Example

The dependency example demonstrates how to handle dependencies in your agent’s functions.

  1"""
  2Example of deploying a Bedrock Agent with web search capabilities.
  3
  4This example demonstrates how to:
  51. Create functions that search the web and extract content from URLs
  62. Handle different response formats from third-party libraries
  73. Properly specify dependencies for Lambda deployment
  84. Handle Lambda parameter format correctly (list of dictionaries)
  9"""
 10import os
 11from bedrock_agents_sdk import BedrockAgents, Agent, Message
 12
 13# Define functions for web search and content extraction
 14def search_internet(query: str, num_results: int = 5) -> dict:
 15    """
 16    Search the internet using DuckDuckGo
 17    
 18    :param query: The search query
 19    :param num_results: Number of results to return (default: 5)
 20    """
 21    from duckduckgo_search import DDGS
 22    
 23    try:
 24        # Create a DuckDuckGo Search instance
 25        ddg = DDGS()
 26        
 27        # Perform the search
 28        search_results = list(ddg.text(query, max_results=num_results))
 29        
 30        # Format the results - handle different possible return formats
 31        results = []
 32        for result in search_results:
 33            # Check if result is a dictionary (newer versions of the library)
 34            if isinstance(result, dict):
 35                results.append({
 36                    "title": result.get('title', ''),
 37                    "url": result.get('href', ''),
 38                    "snippet": result.get('body', '')
 39                })
 40            # Check if result is a list or tuple (older versions or different format)
 41            elif isinstance(result, (list, tuple)) and len(result) >= 3:
 42                results.append({
 43                    "title": result[0] if len(result) > 0 else '',
 44                    "url": result[1] if len(result) > 1 else '',
 45                    "snippet": result[2] if len(result) > 2 else ''
 46                })
 47            # Fallback for any other format
 48            else:
 49                results.append({
 50                    "title": str(result),
 51                    "url": "",
 52                    "snippet": str(result)
 53                })
 54                
 55        return {
 56            "results": results,
 57            "query": query
 58        }
 59    except Exception as e:
 60        # Return error information if the search fails
 61        return {
 62            "results": [],
 63            "query": query,
 64            "error": str(e)
 65        }
 66
 67def load_text_from_url(url: str) -> dict:
 68    """
 69    Load and extract text content from a specified URL
 70    
 71    :param url: The URL to fetch text content from
 72    """
 73    import requests
 74    from bs4 import BeautifulSoup
 75    
 76    try:
 77        # Add user agent to avoid being blocked
 78        headers = {
 79            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
 80        }
 81        
 82        response = requests.get(url, headers=headers, timeout=10)
 83        response.raise_for_status()  # Raise exception for 4XX/5XX responses
 84        
 85        # Parse the HTML content
 86        soup = BeautifulSoup(response.text, 'html.parser')
 87        
 88        # Remove script and style elements
 89        for script_or_style in soup(["script", "style", "header", "footer", "nav"]):
 90            script_or_style.extract()
 91            
 92        # Get text content
 93        text = soup.get_text()
 94        
 95        # Clean up text: remove extra whitespace and blank lines
 96        lines = (line.strip() for line in text.splitlines())
 97        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
 98        text = '\n'.join(chunk for chunk in chunks if chunk)
 99        
100        # Limit text length to avoid exceeding Lambda response size limits
101        max_length = 100000  # Adjust as needed
102        if len(text) > max_length:
103            text = text[:max_length] + "... [content truncated due to size]"
104        
105        return {
106            "content": text,
107            "url": url,
108            "status_code": response.status_code
109        }
110    except Exception as e:
111        # Handle errors gracefully
112        return {
113            "content": f"Error retrieving content: {str(e)}",
114            "url": url,
115            "status_code": 500
116        }
117
118# Helper function to extract parameters in Lambda
119def extract_parameter_value(parameters, param_name, default=None):
120    """
121    Extract a parameter value from the parameters list
122    
123    Args:
124        parameters: List of parameter dictionaries
125        param_name: Name of the parameter to extract
126        default: Default value if parameter is not found
127        
128    Returns:
129        The parameter value or default if not found
130    """
131    if isinstance(parameters, list):
132        # Parameters is a list of dictionaries
133        for param in parameters:
134            if isinstance(param, dict) and param.get('name') == param_name:
135                return param.get('value', default)
136    elif isinstance(parameters, dict):
137        # Parameters is a dictionary
138        return parameters.get(param_name, default)
139    
140    # If we get here, parameter was not found
141    return default
142
143def main():
144    # Create the agent
145    agent = Agent(
146        name="WebSearchAgent",
147        model="anthropic.claude-3-sonnet-20240229-v1:0",
148        instructions="""You are a helpful web search assistant. 
149        When asked for information, use the search_internet function to find relevant information.
150        If the user wants to read content from a specific URL, use the load_text_from_url function.
151        Always cite your sources by providing the URLs.""",
152        functions={
153            "SearchActions": [search_internet, load_text_from_url]
154        }
155    )
156    
157    # Test the agent locally before deploying
158    print("Testing agent locally before deployment...")
159    client = BedrockAgents(verbosity="normal")
160    result = client.run(
161        agent=agent,
162        message="What is the current weather in Seattle?"
163    )
164    print("\nLocal agent response:")
165    print("-" * 50)
166    print(result["response"])
167    print("-" * 50)
168    
169    # Deploy the agent to AWS
170    print("\nDeploying agent to AWS...")
171    
172    # Add specific version constraints for dependencies
173    agent.add_dependency("requests", ">=2.25.0")
174    agent.add_dependency("beautifulsoup4", ">=4.9.0")
175    agent.add_dependency("duckduckgo-search", ">=3.0.0")
176    
177    # Generate the SAM template and supporting files
178    # The output directory will default to "./websearchagent_deployment"
179    template_path = agent.deploy(
180        description="Web search agent with DuckDuckGo and BeautifulSoup",
181        # Uncomment the following lines to automatically build and deploy
182        # auto_build=True,
183        # auto_deploy=True
184    )
185    
186    print("\nIMPORTANT: After deployment, you need to manually update the Lambda function code")
187    print("to handle parameters correctly. In the Lambda console, add the following function:")
188    print("""
189def extract_parameter_value(parameters, param_name, default=None):
190    \"\"\"
191    Extract a parameter value from the parameters list
192    \"\"\"
193    if isinstance(parameters, list):
194        # Parameters is a list of dictionaries
195        for param in parameters:
196            if isinstance(param, dict) and param.get('name') == param_name:
197                return param.get('value', default)
198    elif isinstance(parameters, dict):
199        # Parameters is a dictionary
200        return parameters.get(param_name, default)
201    
202    # If we get here, parameter was not found
203    return default
204    """)
205    print("\nThen update the lambda_handler function to use this helper function:")
206    print("""
207# Get parameters from the event if available
208parameters = event.get("parameters", [])
209
210# For search_internet function:
211query = extract_parameter_value(parameters, "query", "")
212num_results_str = extract_parameter_value(parameters, "num_results", "5")
213try:
214    num_results = int(num_results_str)
215except (ValueError, TypeError):
216    num_results = 5
217output_from_logic = search_internet(query=query, num_results=num_results)
218
219# For load_text_from_url function:
220url = extract_parameter_value(parameters, "url", "")
221output_from_logic = load_text_from_url(url=url)
222    """)
223
224if __name__ == "__main__":
225    main() 

Deployment Example

The deployment example demonstrates how to deploy your agent to AWS.

 1"""
 2Example of deploying a Bedrock Agent to AWS using the Bedrock Agents SDK.
 3"""
 4import datetime
 5import os
 6from bedrock_agents_sdk import BedrockAgents, Agent, Message
 7
 8# Define functions - these will run in AWS Lambda when deployed
 9def get_time() -> dict:
10    """Get the current time"""
11    now = datetime.datetime.now()
12    return {"time": now.strftime("%H:%M:%S")}
13
14def get_date() -> dict:
15    """Get the current date"""
16    now = datetime.datetime.now()
17    return {"date": now.strftime("%Y-%m-%d")}
18
19def add_numbers(a: int, b: int) -> dict:
20    """Add two numbers together
21    
22    :param a: The first number
23    :param b: The second number
24    """
25    return {"result": a + b}
26
27def main():
28    # Create the agent
29    agent = Agent(
30        name="DeploymentExample",
31        model="anthropic.claude-3-sonnet-20240229-v1:0",
32        instructions="""You are a helpful assistant that can tell the time and date, 
33        and perform simple calculations. When asked about time or date, use the 
34        appropriate function to get accurate information. When asked to add numbers, 
35        use the add_numbers function.""",
36        functions={
37            "TimeActions": [get_time, get_date],
38            "MathActions": [add_numbers]
39        }
40    )
41    
42    # Test the agent locally before deploying
43    print("Testing agent locally before deployment...")
44    client = BedrockAgents(verbosity="normal")
45    result = client.run(
46        agent=agent,
47        message="What time is it now, and can you also add 25 and 17 for me?"
48    )
49    print("\nLocal agent response:")
50    print("-" * 50)
51    print(result["response"])
52    print("-" * 50)
53    
54    # Deploy the agent to AWS
55    print("\nDeploying agent to AWS...")
56    
57    # Generate the SAM template and supporting files
58    # The output directory will default to "./deploymentexample_deployment"
59    template_path = agent.deploy(
60        description="Example agent deployment",
61        # Uncomment the following lines to automatically build and deploy
62        # auto_build=True,
63        # auto_deploy=True
64    )
65    
66    print("\nAfter deployment, you can test your agent in the AWS Console:")
67    print("1. Go to the Amazon Bedrock console")
68    print("2. Navigate to Agents")
69    print("3. Find your agent named 'DeploymentExample'")
70    print("4. Click on the agent and use the 'Test' tab to interact with it")
71
72if __name__ == "__main__":
73    main() 

Knowledge Base Example

The knowledge base example demonstrates how to connect your agent to an Amazon Bedrock Knowledge Base.

 1"""
 2Example of using knowledge bases with the Bedrock Agents SDK.
 3"""
 4import os
 5from bedrock_agents_sdk import BedrockAgents, Agent, Message, KnowledgeBasePlugin
 6
 7def main():
 8    # Create the client
 9    client = BedrockAgents()
10    
11    # Create a knowledge base plugin
12    kb_plugin = KnowledgeBasePlugin(
13        knowledge_base_id="your-knowledge-base-id",  # Replace with your actual KB ID
14        description="Knowledge base containing company documentation and FAQs"
15    )
16    
17    # Create the agent with the knowledge base plugin
18    agent = Agent(
19        name="SupportAgent",
20        model="us.anthropic.claude-3-5-sonnet-20241022-v2:0",
21        instructions="""
22        You are a helpful support assistant for our company.
23        Use the knowledge base to answer questions about our products and services.
24        If you don't know the answer, say so and don't make up information.
25        """,
26        plugins=[kb_plugin]  # Add the plugin directly to the agent
27    )
28    
29    # Run the agent with a user query
30    result = client.run(
31        agent=agent,
32        messages=[
33            {
34                "role": "user",
35                "content": "What are your refund policies?"
36            }
37        ]
38    )
39    
40    print("\nResponse from agent:")
41    print("-" * 50)
42    print(result["response"])
43    print("-" * 50)
44    
45    # Example of uploading a document to a knowledge base
46    def upload_document_example():
47        # This is a demonstration of how you might upload a document
48        # In a real application, you would use the AWS SDK or console
49        print("\nUploading document to knowledge base (example code):")
50        print("client.upload_document(")
51        print("    knowledge_base_id='your-knowledge-base-id',")
52        print("    document_path='path/to/document.pdf',")
53        print("    metadata={'category': 'policies', 'department': 'legal'}")
54        print(")")
55    
56    upload_document_example()
57    
58    # Interactive chat session
59    print("\nChat with the Support Agent (type 'exit' to quit):")
60    messages = []
61    
62    while True:
63        user_input = input("\nYou: ")
64        if user_input.lower() == "exit":
65            break
66            
67        messages.append({"role": "user", "content": user_input})
68        
69        result = client.run(agent=agent, messages=messages)
70        assistant_message = result["response"]
71        
72        print(f"\nSupport Agent: {assistant_message}")
73        
74        messages.append({"role": "assistant", "content": assistant_message})
75
76if __name__ == "__main__":
77    main() 

Simple Weather Agent

import requests
from bedrock_agents_sdk import Client, Agent

def get_weather(location: str) -> dict:
    """Get the current weather for a location

    Args:
        location: The city and state, e.g. 'Seattle, WA'

    Returns:
        dict: Weather information including temperature and conditions
    """
    # This is a mock implementation - in a real application, you would call a weather API
    return {
        "location": location,
        "temperature": 72,
        "conditions": "sunny",
        "humidity": 45,
        "wind_speed": 5
    }

agent = Agent(
    name="WeatherAgent",
    description="An agent that can tell you the weather",
    foundation_model="anthropic.claude-3-sonnet-20240229-v1:0",
    instructions="You are a helpful weather assistant. You can tell users the current weather for a location."
)

agent.add_function(get_weather)

client = Client()
client.add_agent(agent)
client.run()

File Processing Agent

import os
import json
from bedrock_agents_sdk import Client, Agent, InputFile, OutputFile

def read_file(file_path: InputFile) -> dict:
    """Read the contents of a file

    Args:
        file_path: The path to the file to read

    Returns:
        dict: The contents of the file
    """
    with open(file_path.local_path, "r") as f:
        content = f.read()

    return {"content": content}

def write_file(content: str, file_name: str) -> OutputFile:
    """Write content to a file

    Args:
        content: The content to write to the file
        file_name: The name of the file to write

    Returns:
        OutputFile: The file that was written
    """
    file_path = f"/tmp/{file_name}"
    with open(file_path, "w") as f:
        f.write(content)

    return OutputFile(local_path=file_path, file_name=file_name)

agent = Agent(
    name="FileAgent",
    description="An agent that can read and write files",
    foundation_model="anthropic.claude-3-sonnet-20240229-v1:0",
    instructions="You are a helpful assistant that can read and write files."
)

agent.add_function(read_file)
agent.add_function(write_file)

client = Client()
client.add_agent(agent)
client.run()

Multi-Agent System

from bedrock_agents_sdk import Client, Agent, ActionGroup

# Weather functions
def get_weather(location: str) -> dict:
    """Get the current weather for a location"""
    return {"temperature": 72, "conditions": "sunny"}

def get_forecast(location: str, days: int) -> dict:
    """Get the weather forecast for a location"""
    return {"forecast": [{"day": i, "temperature": 70 + i, "conditions": "sunny"} for i in range(days)]}

# Time functions
def get_time() -> dict:
    """Get the current time"""
    import datetime
    now = datetime.datetime.now()
    return {"time": now.strftime("%H:%M:%S")}

def get_date() -> dict:
    """Get the current date"""
    import datetime
    now = datetime.datetime.now()
    return {"date": now.strftime("%Y-%m-%d")}

# Create agents
weather_agent = Agent(
    name="WeatherAgent",
    description="An agent that can tell you the weather",
    foundation_model="anthropic.claude-3-sonnet-20240229-v1:0",
    instructions="You are a helpful weather assistant."
)

time_agent = Agent(
    name="TimeAgent",
    description="An agent that can tell you the time and date",
    foundation_model="anthropic.claude-3-sonnet-20240229-v1:0",
    instructions="You are a helpful time assistant."
)

# Create action groups
weather_group = ActionGroup(
    name="weather",
    description="Functions for getting weather information"
)
weather_group.add_function(get_weather)
weather_group.add_function(get_forecast)

time_group = ActionGroup(
    name="time",
    description="Functions for getting time information"
)
time_group.add_function(get_time)
time_group.add_function(get_date)

# Add action groups to agents
weather_agent.add_action_group(weather_group)
time_agent.add_action_group(time_group)

# Create client and add agents
client = Client()
client.add_agent(weather_agent)
client.add_agent(time_agent)

# Set the active agent
client.set_active_agent("WeatherAgent")

# Run the client
client.run()

Agent with Knowledge Base

from bedrock_agents_sdk import Client, Agent, KnowledgeBasePlugin

agent = Agent(
    name="DocsAgent",
    description="An agent that can answer questions about documentation",
    foundation_model="anthropic.claude-3-sonnet-20240229-v1:0",
    instructions="You are a helpful assistant that can answer questions about documentation."
)

kb_plugin = KnowledgeBasePlugin(
    knowledge_base_id="my-docs-kb",
    retrieval_config={
        "vector_search_configuration": {
            "number_of_results": 5
        }
    }
)

agent.add_plugin(kb_plugin)

client = Client()
client.add_agent(agent)
client.run()