

# Tutorial: Building a simple Amazon Bedrock agent
<a name="agent-tutorial"></a>

This tutorial guides you through creating and configuring a simple Amazon Bedrock agent using the AWS Management Console. You'll learn how to create an agent that can respond to user queries about the current date and time by invoking a Lambda function.

In this tutorial, you will:

1. Create a Lambda function — Build a Python function that returns the current date and time when invoked by your agent.

1. Create an Amazon Bedrock agent — Set up an agent in the Amazon Bedrock console and configure it with instructions to handle date and time queries.

1. Test the agent — Use the built-in testing interface to verify your agent can correctly respond to date and time requests.

1. Deploy the agent with an alias — Create a version of your agent and deploy it with an alias to make it available for use.

1. Call the agent from Python code — Learn how to programmatically interact with your agent using the AWS SDK for Python (Boto). 

1. Clean up resources — Remove the AWS resources created during this tutorial to avoid incurring unnecessary charges.

By the end of this tutorial, you'll have a working Amazon Bedrock agent that can understand natural language requests for date and time information and respond with accurate data from your Lambda function.

This tutorial is based on the agent code example in the AWS documentation [GitHub repository](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/python/example_code/bedrock-agent/scenario_get_started_with_agents.py). 

**Topics**
+ [Prerequisites](agent-tutorial-prereq.md)
+ [Step 1: Create a Lambda function](agent-tutorial-step1.md)
+ [Step 2: Create an Amazon Bedrock agent](agent-tutorial-step2.md)
+ [Step 3: Test the agent](agent-tutorial-step3.md)
+ [Step 4: Deploy the agent with an alias](agent-tutorial-step4.md)
+ [Step 5: Call the agent from Python code](agent-tutorial-step5.md)
+ [Step 6: Clean up resources](agent-tutorial-step6.md)
+ [Additional resources](agent-tutorial-resources.md)

# Prerequisites
<a name="agent-tutorial-prereq"></a>

Before you begin this tutorial, make sure you have the following:
+ AWS account with the following managed policies:
  + [AmazonBedrockFullAccess](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonBedrockFullAccess)
  + [AWSLambda\$1FullAccess](https://docs.aws.amazon.com/lambda/latest/dg/security-iam-awsmanpol.html#lambda-security-iam-awsmanpol-AWSLambda_FullAccess)
  + [IAMFullAccess](aws-managed-policy/latest/reference/IAMFullAccess.html)
**Important**  
These permissions allow you to run this tutorial and other, unrelated, tasks. In production environments be sure to assign only those permissions that your users need to run your application.
+ Basic understanding of IAM roles and permissions ([IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html))
+ Familiarity with AWS Lambda functions ([Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html))

# Step 1: Create a Lambda function
<a name="agent-tutorial-step1"></a>

First, create a Lambda function that your agent will invoke to perform actions. In this procedure, you'll create a Python Lambda function that returns the current date and time when invoked. You'll set up the function with basic permissions, add the necessary code to handle requests from your Amazon Bedrock agent, and deploy the function so it's ready to be connected to your agent.

For more information, see [Create your first Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html) in the *AWS Lambda developer guide*.

**Create a Lambda function**

1. Sign in to the AWS Management Console and open the Lambda console at [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/).

1. Choose **Create function**.

1. Select **Author from scratch**.

1. In the **Basic information** section:
   + For **Function name**, enter a function name (for example, `DateTimeFunction`). Note the name of the function, you'll need it in step 15 of [Step 2: Create an Amazon Bedrock agent](agent-tutorial-step2.md).
   + For **Runtime**, select **Python 3.9** (or your preferred version).
   + For **Architecture**, leave unchanged.
   + In **Permissions**, select **Change default execution role** and then select **Create a new role with basic Lambda permissions**.

1. Choose **Create function**.

1. In **Function overview**, under **Function ARN**, note the Amazon Resource Name (ARN) for the function. You need it for step 24 of [Step 2: Create an Amazon Bedrock agent](agent-tutorial-step2.md). 

1. In the **Code** tab, replace the existing code with the following:

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   import datetime
   import json
   
   
   def lambda_handler(event, context):
       now = datetime.datetime.now()
   
       response = {"date": now.strftime("%Y-%m-%d"), "time": now.strftime("%H:%M:%S")}
   
       response_body = {"application/json": {"body": json.dumps(response)}}
   
       action_response = {
           "actionGroup": event["actionGroup"],
           "apiPath": event["apiPath"],
           "httpMethod": event["httpMethod"],
           "httpStatusCode": 200,
           "responseBody": response_body,
       }
   
       session_attributes = event["sessionAttributes"]
       prompt_session_attributes = event["promptSessionAttributes"]
   
       return {
           "messageVersion": "1.0",
           "response": action_response,
           "sessionAttributes": session_attributes,
           "promptSessionAttributes": prompt_session_attributes,
       }
   ```

1. Choose **Deploy** to deploy your function.

1. Choose the **Configuration** tab.

1. Choose **Permissions**.

1. Under **Resource-based policy statements**, choose **Add permissions**.

1. In **Edit policy statement**, do the following:

   1. Choose **AWS service**

   1. In **Service** select **Other**.

   1. For **Statement ID**, enter a unique identifier (for example, `AllowBedrockInvocation`).

   1. For **Principal**, enter `bedrock.amazonaws.com`.

   1. For **Source ARN**, enter `arn:aws:bedrock:region:AWS account ID:agent/*`

      Replace `region` with AWS Region that you are using, such as `us-east-1`. Replace `AWS account ID` your AWS account Id.

   1. For **Action**, select `lambda:InvokeFunction`.

1. Choose **Save**.

# Step 2: Create an Amazon Bedrock agent
<a name="agent-tutorial-step2"></a>

Next, you'll create an Amazon Bedrock agent. In this procedure, you'll set up an agent in the Amazon Bedrock console, configure it with a foundation model, and provide instructions that define its behavior as a friendly chatbot that returns date and time information. You'll also create an action group with an OpenAPI schema that defines the API endpoints your agent can call, specifically the endpoint to get the current date and time. Additionally, you'll add an inline policy to your agent's IAM role to allow it to invoke your Lambda function. The agent will serve as the interface between users and your Lambda function, interpreting natural language requests and converting them into structured function calls to retrieve date and time information.

For more information, see [Create and configure agent manually](agents-create.md).

**Create an Amazon Bedrock agent**

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. Make sure that you are in an AWS [Region](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/select-region.html) that supports Amazon Bedrock [agents](agents-supported.md). 

1. In the navigation pane, under **Builder tools**, choose **Agents**.

1. Choose **Create agent**.

1. For **Name**, enter a name for your agent (for example, `MyBedrockAgent`).

1. (Optional) For **Description**, enter a description.

1. Choose **Create**. The **Agent builder** pane opens.

1. In the **Agent details** section:
   + For **Agent resource role**, select **Create and use a new service role**.
   + For **Select model**, select a model, such as Claude 3 Haiku.
   + In the **Instructions for the Agent** section, enter the folowing instructions.

     ```
     You are a friendly chat bot. You have access to a function called that returns
     information about the current date and time. When responding with date or time,
     please make sure to add the timezone UTC.
     ```

1. Choose **Save**.

1. Choose the **Action groups** tab.

1. In **Action groups**, choose **Add**.

1. For **Enter Action group name**, enter a name for the action group (for example, `TimeActions`).

1. (Optional) For **Description** Enter a description for the action group.

1. In **Action group type**, select **Define with API schemas**.

1. In **Action group invocation**, choose **Select an existing Lambda function**. 

1. In **Select Lambda function**, select the name of the Lambda function that you created in [Step 1: Create a Lambda function](agent-tutorial-step1.md).

1. In **Action group schema**, select **Define via in-line schema editor**.

1. In **In-line OpenAPI schema** text box, replace the existing schema with the following OpenAPI YAML schema:

   ```
   openapi: 3.0.0
   info:
     title: Time API
     version: 1.0.0
     description: API to get the current date and time.
   paths:
     /get-current-date-and-time:
       get:
         summary: Gets the current date and time.
         description: Gets the current date and time.
         operationId: getDateAndTime
         responses:
           '200':
             description: Gets the current date and time.
             content:
               'application/json':
                 schema:
                   type: object
                   properties:
                     date:
                       type: string
                       description: The current date
                     time:
                       type: string
                       description: The current time
   ```

1. Review your action group configuration and choose **Create**.

1. Choose **Save** to save your changes.

1. Choose **Prepare** to prepare the agent.

1. Choose **Save and exit** to save your changes and exit the agent builder.

1. In the **Agent overview** section, under **Permissions**, choose the IAM service role. This opens the role in the IAM console. 

1. In the IAM console, Choose the **Permissions** tab.

1. Choose **Add permissions**, and then select **Create inline policy**.

1. Choose **JSON** and paste the following policy. Make sure `Resource` is the Amazon Resource Name (ARN) for your Lambda function. You noted the ARN in step 6 of [Step 1: Create a Lambda function](agent-tutorial-step1.md). 

1. Choose **Next**.

1. Enter a name for the policy (for example, `BedrockAgentLambdaInvoke`).

1. Choose **Create policy**.

# Step 3: Test the agent
<a name="agent-tutorial-step3"></a>

In this procedure, you'll test the working draft of your agent using the built-in testing interface in the Amazon Bedrock console. You'll send natural language queries asking for the current date and time, and observe how the agent processes these requests, invokes your Lambda function, and returns formatted responses. This testing step allows you to verify that your agent correctly understands user intent, properly calls the Lambda function, and presents the information in a user-friendly way.

For more information, see [Test and troubleshoot agent behavior](agents-test.md).

**To test the agent**

1. In the Amazon Bedrock console, open the agent that you created in [Step 2: Create an Amazon Bedrock agent](agent-tutorial-step2.md)

1. Choose **Test** to open the **Test** panel.

1. In the **Alias** dropdown, select the alias **TestAlias: Working draft**.

1. In the chat interface, enter a prompt that would trigger one of your agent's actions, such as:
   + **What time is it?**
   + **Can you tell me today's date?**

1. The agent will process your prompt, invoke the Lambda function if necessary, and return a response.

1. (Optional) Choose **Show trace** to see the [trace](trace-events.md) steps for the prompt that you sent to the model. In the trace you should see the reasoning that the model uses to determine when to call the Lambda function to get the date and time.

# Step 4: Deploy the agent with an alias
<a name="agent-tutorial-step4"></a>

After configuring your agent, you need to deploy it with an alias to make it available for use. In this procedure, you'll prepare your agent for deployment by creating an alias and version of your agent. The alias points to the version, allowing you to invoke your agent through a stable endpoint while maintaining the ability to update the underlying implementation.

For more information, see [Deploy and use an Amazon Bedrock agent in your application](agents-deploy.md).

**Deploy the agent with an alias**

1. In the Amazon Bedrock console, open the agent that you created in [Step 2: Create an Amazon Bedrock agent](agent-tutorial-step2.md)

1. Choose **Create Alias**.

1. For **Alias name**, enter a name for the alias. For example **DateTimeAliasAgentAlias**.

1. (Optional) For **Description**, enter a description.

1. For **Associate a version**, select **Create a new version and associate it to this alias**.

1. Choose **Create alias**.

1. Test the alias by following the instructions at [Step 3: Test the agent](agent-tutorial-step3.md). For step 6, choose the alias that you just created.

# Step 5: Call the agent from Python code
<a name="agent-tutorial-step5"></a>

In this step, you'll learn how to programmatically interact with your agent using the AWS SDK for Python (Boto). The example code demonstrates how to use the [InvokeAgent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) operation, which requires both the AGENT ID and ALIAS ID as parameters to call your agent. The code shows how to send a prompt to your agent, process the response, and handle both streaming and non-streaming response modes. This allows you to integrate your Bedrock agent into your own Python applications.

For more information, see [Invoke an agent from your application](agents-invoke-agent.md).

**To call the agent from Python code**

1. Get the ID for the agent. For more information, see [View information about an agent](agents-view.md).

1. Get the ID for the agent alias. For more information, see [View information about aliases of agents in Amazon Bedrock](agents-alias-view.md).

1. Run the following code. Update the following:
   + **AGENT\$1ID** – to your agent's ID.
   + **ALIAS\$1ID** – to your agent's Alias ID.
   + **REGION** – to the AWS Region in which you created your agent, such as `us-east-1`. 

   To stream the response from the agent, change the value of `streamFinalResponse` to `True`.

   ```
   import boto3
   import logging
   
   from botocore.exceptions import ClientError
   
   
   logging.basicConfig(level=logging.INFO)
   logger = logging.getLogger(__name__)
   
   def invoke_agent(client, agent_id, alias_id, prompt, session_id):
           response = client.invoke_agent(
               agentId=agent_id,
               agentAliasId=alias_id,
               enableTrace=True,
               sessionId = session_id,
               inputText=prompt,
               streamingConfigurations = { 
       "applyGuardrailInterval" : 20,
         "streamFinalResponse" : False
               }
           )
           completion = ""
           for event in response.get("completion"):
               #Collect agent output.
               if 'chunk' in event:
                   chunk = event["chunk"]
                   completion += chunk["bytes"].decode()
               
               # Log trace output.
               if 'trace' in event:
                   trace_event = event.get("trace")
                   trace = trace_event['trace']
                   for key, value in trace.items():
                       logging.info("%s: %s",key,value)
   
           print(f"Agent response: {completion}")
   
   
   if __name__ == "__main__":
   
       client=boto3.client(
               service_name="bedrock-agent-runtime",
               region_name="REGION") 
       
       agent_id = "AGENT_ID"
       alias_id = "ALIAS_ID"
       session_id = "123456"
       prompt = "What's the current time?"
   
       try:
   
           invoke_agent(client, agent_id, alias_id, prompt, session_id)
   
       except ClientError as e:
           print(f"Client error: {str(e)}")
           logger.error("Client error: %s", {str(e)})
   ```

# Step 6: Clean up resources
<a name="agent-tutorial-step6"></a>

When you're done with your Amazon Bedrock agent, you should clean up the resources to avoid incurring unnecessary charges. In this final procedure, you'll systematically delete all the AWS resources created during this tutorial, including the Bedrock agent, Lambda function, and associated \$1IAM roles. This cleanup process is important for cost management, as it prevents ongoing charges for resources you're no longer using. The procedure is organized into three parts: deleting the agent, removing the Lambda function, and cleaning up the IAM roles that were created to support these services.

**Topics**
+ [Delete the agent](#agent-tutorial-step6-console-agent)
+ [Delete the Lambda function](#agent-tutorial-step6-console-lambda)
+ [Delete the IAM roles](#agent-tutorial-step6-console-iam)

## Delete the agent
<a name="agent-tutorial-step6-console-agent"></a>

**Delete the agent**

1. In the Amazon Bedrock console, open the agent that you created in [Step 2: Create an Amazon Bedrock agent](agent-tutorial-step2.md)

1. Select the agent you created.

1. Choose **Delete**.

1. Confirm the deletion.

## Delete the Lambda function
<a name="agent-tutorial-step6-console-lambda"></a>

**Delete the Lambda function**

1. Open the AWS Lambda console at [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/).

1. Select the Lambda function you created.

1. Choose **Actions**, then **Delete**.

1. Confirm the deletion.

## Delete the IAM roles
<a name="agent-tutorial-step6-console-iam"></a>

**Delete the IAM roles**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Roles**.

1. Select the agent service role that you created.

1. Choose **Delete**.

1. Confirm the deletion.

1. Repeat for the Lambda execution role.

# Additional resources
<a name="agent-tutorial-resources"></a>
+ [Amazon Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
+ [Amazon Bedrock API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html)
+ [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
+ [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)
+ [Amazon Bedrock Agents Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html)
+ [OpenAPI Specification](https://swagger.io/specification/)