

# Use action groups to define actions for your agent to perform
<a name="agents-action-create"></a>

An action group defines actions that the agent can help the user perform. For example, you could define an action group called `BookHotel` that helps users carry out actions that you can define such as:
+ `CreateBooking` – Helps users book a hotel.
+ `GetBooking` – Helps users get information about a hotel they booked.
+ `CancelBooking` – Helps users cancel a booking.

You create an action group by performing the following steps:

1. Define the parameters and information that the agent must elicit from the user for each action in the action group to be carried out.

1. Decide how the agent handles the parameters and information that it receives from the user and where it sends the information it elicits from the user.

To learn more about the components of an action group and how to create the action group after you set it up, select from the following topics:

**Topics**
+ [Define actions in the action group](action-define.md)
+ [Handle fulfillment of the action](action-handle.md)
+ [Add an action group to your agent in Amazon Bedrock](agents-action-add.md)
+ [View information about an action group](agents-action-view.md)
+ [Modify an action group](agents-action-edit.md)
+ [Delete an action group](agents-action-delete.md)

# Define actions in the action group
<a name="action-define"></a>

You can define action groups in one of the following ways (you can use different methods for different action groups):
+ [Set up an OpenAPI schema](agents-api-schema.md) with descriptions, structure, and parameters that define each action in the action group as an API operation. With this option, you can define actions more explicitly and map them to API operations in your system. You add the API schema to the action group in one of the following ways:
  + Upload the schema that you create to an Amazon Simple Storage Service (Amazon S3) bucket.
  + Write the schema in the inline OpenAPI schema editor in the AWS Management Console when you add the action group. This option is only available after the agent that the action group belongs to has already been created.
+ [Set up function details](agents-action-function.md) with the parameters that the agent needs to elicit from the user. With this option, you can simplify the action group creation process and set up the agent to elicit a set of parameters that you define. You can then pass the parameters on to your application and customize how to use them to carry out the action in your own systems.

Continuing the example above, you can define the `CreateBooking` action in one of the following ways:
+ Using an API schema, `CreateBooking` could be an API operation with a request body that includes fields such as `HotelName`, `LengthOfStay`, and `UserEmail` and a response body that returns a `BookingId`.
+ Using function details, `CreateBooking` could be a function defined with parameters such as `HotelName`, `LengthOfStay`, and `UserEmail`. After the values of these parameters are elicited from the user by your agent, you can then pass them to your systems.

When your agent interacts with the user, it will determine which action within an action group it needs to invoke. The agent will then elicit the parameters and other information that is necessary to complete the API request or that are marked as *required* for the function.

Select a topic to learn how to define an action group with different methods.

**Topics**
+ [Define function details for your agent's action groups in Amazon Bedrock](agents-action-function.md)
+ [Define OpenAPI schemas for your agent's action groups in Amazon Bedrock](agents-api-schema.md)

# Define function details for your agent's action groups in Amazon Bedrock
<a name="agents-action-function"></a>

When you create an action group in Amazon Bedrock, you can define function details to specify the parameters that the agent needs to invoke from the user. Function details consist of a list of parameters, defined by their name, data type (for a list of supported data types, see [ParameterDetail](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ParameterDetail.html)), and whether they are required. The agent uses these configurations to determine what information it needs to elicit from the user.

For example, you might define a function called **BookHotel** that contains parameters that the agent needs to invoke from the user in order to book a hotel for the user. You might define the following parameters for the function:


****  

| Parameter | Description | Type | Required | 
| --- | --- | --- | --- | 
| HotelName | The name of the hotel | string | Yes | 
| CheckinDate | The date to check in | string | Yes | 
| NumberOfNights | The number of nights to stay | integer | No | 
| Email | An email address to contact the user | string | Yes | 
| AllowMarketingEmails | Whether to allow promotional emails to be sent to the user | boolean | Yes | 

Defining this set of parameters would help the agent determine that it must minimally elicit the name of the hotel that the user wants to book, the check-in date, the user's email address, and whether they want to allow promotional emails to be sent to their email.

If the user says **"I want to book Hotel X for tomorrow"**, the agent would determine the parameters `HotelName` and `CheckinDate`. It would then follow up with the user on the remaining parameters with questions such as:
+ "What is your email address?"
+ "Do you want to allow the hotel to send you promotional emails?"

Once the agent determines all the required parameters, it then sends them to a Lambda function that you define to carry out the action or returns them in the response of the agent invocation.

To learn how to define a function while creating the action group, see [Add an action group to your agent in Amazon Bedrock](agents-action-add.md).

# Define OpenAPI schemas for your agent's action groups in Amazon Bedrock
<a name="agents-api-schema"></a>

When you create an action group in Amazon Bedrock, you must define the parameters that the agent needs to invoke from the user. You can also define API operations that the agent can invoke using these parameters. To define the API operations, create an OpenAPI schema in JSON or YAML format. You can create OpenAPI schema files and upload them to Amazon Simple Storage Service (Amazon S3). Alternatively, you can use the OpenAPI text editor in the console, which will validate your schema. After you create an agent, you can use the text editor when you add an action group to the agent or edit an existing action group. For more information, see [Modify an agent](agents-edit.md).

The agent uses the schema to determine the API operation that it needs to invoke and the parameters that are required to make the API request. These details are then sent through a Lambda function that you define to carry out the action or returned in the response of the agent invocation.

For more information about API schemas, see the following resources:
+ For more details about OpenAPI schemas, see [OpenAPI specification](https://swagger.io/specification/) on the Swagger website.
+ For best practices in writing API schemas, see [Best practices in API design](https://swagger.io/resources/articles/best-practices-in-api-design/) on the Swagger website.

The following is the general format of an OpenAPI schema for an action group.

```
{
    "openapi": "3.0.0",
    "paths": {
        "/path": {
            "method": {
                "description": "string",
                "operationId": "string",
                "parameters": [ ... ],
                "requestBody": { ... },
                "responses": { ... },
                "x-requireConfirmation": ENABLED | DISABLED
           }
       }
    }
}
```

The following list describes fields in the OpenAPI schema
+ `openapi` – (Required) The version of OpenAPI that's being used. This value must be `"3.0.0"` for the action group to work.
+ `paths` – (Required) Contains relative paths to individual endpoints. Each path must begin with a forward slash (`/`).
+ `method` – (Required) Defines the method to use.
+ `x-requireConfirmation` – (Optional) Specifies if the user confirmation is required before invoking the action. Enable this field to request confirmation from the user before the action is invoked. Requesting user confirmation before invoking the action may safeguard your application from taking actions due to malicious prompt injections. By default, user confirmation is `DISABLED` if this field is not specified.

Minimally, each method requires the following fields:
+ `description` – A description of the API operation. Use this field to inform the agent when to call this API operation and what the operation does.
+ `operationId` – A unique string that identifies an operation in an API, like a function name. This is a required field for all new toolUse enabled models such as Anthropic Claude 3.5 Sonnet, Meta Llama, etc. Ensure that the identifier (Id) you provide is unique across all operations and follows simple alphanumeric pattern with only hyphens or underscores as separators.
+ `responses` – Contains properties that the agent returns in the API response. The agent uses the response properties to construct prompts, accurately process the results of an API call, and determine a correct set of steps for performing a task. The agent can use response values from one operation as inputs for subsequent steps in the orchestration.

The fields within the following two objects provide more information for your agent to effectively take advantage of your action group. For each field, set the value of the `required` field to `true` if required and to `false` if optional.
+ `parameters` – Contains information about parameters that can be included in the request.
+ `requestBody` – Contains the fields in the request body for the operation. Don't include this field for `GET` and `DELETE` methods.

To learn more about a structure, select from the following tabs.

------
#### [ responses ]

```
"responses": {
    "200": {
        "content": {
            "<media type>": {
                "schema": {
                    "properties": {
                        "<property>": {
                            "type": "string",
                            "description": "string"
                        },
                        ...
                    }
                }
            }
        },
    },
    ...
}
```

Each key in the `responses` object is a response code, which describes the status of the response. The response code maps to an object that contains the following information for the response:
+ `content` – (Required for each response) The content of the response.
+ *<media type>* – The format of the response body. For more information, see [Media types](https://swagger.io/docs/specification/media-types/) on the Swagger website.
+ `schema` – (Required for each media type) Defines the data type of the response body and its fields.
+ `properties` – (Required if there are `items` in the schema) Your agent uses properties that you define in the schema to determine the information it needs to return to the end user in order to fulfill a task. Each property contains the following fields:
  + `type` – (Required for each property) The data type of the response field.
  + `description` – (Optional) Describes the property. The agent can use this information to determine the information that it needs to return to the end user.

------
#### [ parameters ]

```
"parameters": [
    {
        "name": "string",
        "description": "string",
        "required": boolean,
        "schema": {
            ...
        }
    },
    ...
]
```

Your agent uses the following fields to determine the information it must get from the end user to perform the action group's requirements.
+ `name` – (Required) The name of the parameter.
+ `description` – (Required) A description of the parameter. Use this field to help the agent understand how to elicit this parameter from the agent user or determine that it already has that parameter value from prior actions or from the user’s request to the agent.
+ `required` – (Optional) Whether the parameter is required for the API request. Use this field to indicate to the agent whether this parameter is needed for every invocation or if it's optional.
+ `schema` – (Optional) The definition of input and output data types. For more information, see [Data Models (Schemas)](https://swagger.io/docs/specification/data-models/) on the Swagger website.

------
#### [ requestBody ]

Following is the general structure of a `requestBody` field:

```
"requestBody": {
    "required": boolean,
    "content": {
        "<media type>": {
            "schema": {
                "properties": {
                    "<property>": {
                        "type": "string",
                        "description": "string"
                    },
                    ...
                }
            }
        }
    }
}
```

The following list describes each field:
+ `required` – (Optional) Whether the request body is required for the API request.
+ `content` – (Required) The content of the request body.
+ *<media type>* – (Optional) The format of the request body. For more information, see [Media types](https://swagger.io/docs/specification/media-types/) on the Swagger website.
+ `schema` – (Optional) Defines the data type of the request body and its fields.
+ `properties` – (Optional) Your agent uses properties that you define in the schema to determine the information it must get from the end user to make the API request. Each property contains the following fields:
  + `type` – (Optional) The data type of the request field.
  + `description` – (Optional) Describes the property. The agent can use this information to determine the information it needs to return to the end user.

------

To learn how to add the OpenAPI schema you created while creating the action group, see [Add an action group to your agent in Amazon Bedrock](agents-action-add.md).

## Example API schemas
<a name="agents-api-schema-example"></a>

The following example provides a simple OpenAPI schema in YAML format that gets the weather for a given location in Celsius.

```
openapi: 3.0.0
info:
  title: GetWeather API
  version: 1.0.0
  description: gets weather
paths:
  /getWeather/{location}/:
    get:
      summary: gets weather in Celsius
      description: gets weather in Celsius
      operationId: getWeather
      parameters:
        - name: location
          in: path
          description: location name
          required: true
          schema:
            type: string
      responses:
        "200":
          description: weather in Celsius
          content:
            application/json:
              schema:
                type: string
```

The following example API schema defines a group of API operations that help handle insurance claims. Three APIs are defined as follows:
+ `getAllOpenClaims` – Your agent can use the `description` field to determine that it should call this API operation if a list of open claims is needed. The `properties` in the `responses` specify to return the ID and the policy holder and the status of the claim. The agent returns this information to the agent user or uses some or all of the response as input to subsequent API calls.
+ `identifyMissingDocuments` – Your agent can use the `description` field to determine that it should call this API operation if missing documents must be identified for an insurance claim. The `name`, `description`, and `required` fields tell the agent that it must elicit the unique identifier of the open claim from the customer. The `properties` in the `responses` specify to return the IDs of the open insurance claims. The agent returns this information to the end user or uses some or all of the response as input to subsequent API calls.
+ `sendReminders` – Your agent can use the `description` field to determine that it should call this API operation if there is a need to send reminders to the customer. For example, a reminder about pending documents that they have for open claims. The `properties` in the `requestBody` tell the agent that it must find the claim IDs and the pending documents. The `properties` in the `responses` specify to return an ID of the reminder and its status. The agent returns this information to the end user or uses some or all of the response as input to subsequent API calls.

```
{
    "openapi": "3.0.0",
    "info": {
        "title": "Insurance Claims Automation API",
        "version": "1.0.0",
        "description": "APIs for managing insurance claims by pulling a list of open claims, identifying outstanding paperwork for each claim, and sending reminders to policy holders."
    },
    "paths": {
        "/claims": {
            "get": {
                "summary": "Get a list of all open claims",
                "description": "Get the list of all open insurance claims. Return all the open claimIds.",
                "operationId": "getAllOpenClaims",
                "responses": {
                    "200": {
                        "description": "Gets the list of all open insurance claims for policy holders",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "array",
                                    "items": {
                                        "type": "object",
                                        "properties": {
                                            "claimId": {
                                                "type": "string",
                                                "description": "Unique ID of the claim."
                                            },
                                            "policyHolderId": {
                                                "type": "string",
                                                "description": "Unique ID of the policy holder who has filed the claim."
                                            },
                                            "claimStatus": {
                                                "type": "string",
                                                "description": "The status of the claim. Claim can be in Open or Closed state"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        "/claims/{claimId}/identify-missing-documents": {
            "get": {
                "summary": "Identify missing documents for a specific claim",
                "description": "Get the list of pending documents that need to be uploaded by policy holder before the claim can be processed. The API takes in only one claim id and returns the list of documents that are pending to be uploaded by policy holder for that claim. This API should be called for each claim id",
                "operationId": "identifyMissingDocuments",
                "parameters": [{
                    "name": "claimId",
                    "in": "path",
                    "description": "Unique ID of the open insurance claim",
                    "required": true,
                    "schema": {
                        "type": "string"
                    }
                }],
                "responses": {
                    "200": {
                        "description": "List of documents that are pending to be uploaded by policy holder for insurance claim",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "pendingDocuments": {
                                            "type": "string",
                                            "description": "The list of pending documents for the claim."
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
        },
        "/send-reminders": {
            "post": {
                "summary": "API to send reminder to the customer about pending documents for open claim",
                "description": "Send reminder to the customer about pending documents for open claim. The API takes in only one claim id and its pending documents at a time, sends the reminder and returns the tracking details for the reminder. This API should be called for each claim id you want to send reminders for.",
                "operationId": "sendReminders",
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "type": "object",
                                "properties": {
                                    "claimId": {
                                        "type": "string",
                                        "description": "Unique ID of open claims to send reminders for."
                                    },
                                    "pendingDocuments": {
                                        "type": "string",
                                        "description": "The list of pending documents for the claim."
                                    }
                                },
                                "required": [
                                    "claimId",
                                    "pendingDocuments"
                                ]
                            }
                        }
                    }
                },
                "responses": {
                    "200": {
                        "description": "Reminders sent successfully",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "sendReminderTrackingId": {
                                            "type": "string",
                                            "description": "Unique Id to track the status of the send reminder Call"
                                        },
                                        "sendReminderStatus": {
                                            "type": "string",
                                            "description": "Status of send reminder notifications"
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "400": {
                        "description": "Bad request. One or more required fields are missing or invalid."
                    }
                }
            }
        }
    }
}
```

For more examples of OpenAPI schemas, see [Example API Descriptions](https://learn.openapis.org/examples/) on the OpenAPI website.

# Handle fulfillment of the action
<a name="action-handle"></a>

When you configure the action group, you also select one of the following options for the agent to pass the information and parameters that it receives from the user:
+ Add user input to your agent's action group. With user input, agent can [request user for more information](agents-user-input.md) if it doesn't have enough information to complete a task. 
+ Pass to a [Lambda function that you create](agents-lambda.md) to define the business logic for the action group.
+ Skip using a Lambda function and [return control](agents-returncontrol.md) by passing the information and parameters from the user in the `InvokeAgent` response. The information and parameters can be sent to your own systems to yield results and these results can be sent in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_SessionState.html#bedrock-Type-agent-runtime_SessionState) of another [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) request.
+ Enable user confirmation for an action. Enabling user confirmation can safeguard your application from malicious prompt injections by [requesting confirmation from your application users](agents-userconfirmation.md) before invoking the action group function. 

Select a topic to learn how to configure how fulfillment of the action group is handled after the necessary information has been elicited from the user.

**Topics**
+ [Configure Lambda functions to send information that an Amazon Bedrock agent elicits from the user](agents-lambda.md)
+ [Return control to the agent developer by sending elicited information in an InvokeAgent response](agents-returncontrol.md)
+ [Get user confirmation before invoking action group function](agents-userconfirmation.md)

# Configure Lambda functions to send information that an Amazon Bedrock agent elicits from the user
<a name="agents-lambda"></a>

You can define a Lambda function to program the business logic for an action group. After an Amazon Bedrock agent determines the API operation that it needs to invoke in an action group, it sends information from the API schema alongside relevant metadata as an input event to the Lambda function. To write your function, you must understand the following components of the Lambda function:
+ **Input event** – Contains relevant metadata and populated fields from the request body of the API operation or the function parameters for the action that the agent determines must be called.
+ **Response** – Contains relevant metadata and populated fields for the response body returned from the API operation or the function.

You write your Lambda function to define how to handle an action group and to customize how you want the API response to be returned. You use the variables from the input event to define your functions and return a response to the agent.

**Note**  
An action group can contain up to 11 API operations, but you can only write one Lambda function. Because the Lambda function can only receive an input event and return a response for one API operation at a time, you should write the function considering the different API operations that may be invoked.

For your agent to use a Lambda function, you must attach a resource-based policy to the function to provide permissions for the agent. For more information, follow the steps at [Resource-based policy to allow Amazon Bedrock to invoke an action group Lambda function](agents-permissions.md#agents-permissions-lambda). For more information about resource-based policies in Lambda, see [Using resource-based policies for Lambda](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html) in the AWS Lambda Developer Guide.

To learn how to define a function while creating the action group, see [Add an action group to your agent in Amazon Bedrock](agents-action-add.md).

**Topics**
+ [Lambda input event from Amazon Bedrock](#agents-lambda-input)
+ [Lambda response event to Amazon Bedrock](#agents-lambda-response)
+ [Action group Lambda function example](#agents-lambda-example)

## Lambda input event from Amazon Bedrock
<a name="agents-lambda-input"></a>

When an action group using a Lambda function is invoked, Amazon Bedrock sends a Lambda input event of the following general format. You can define your Lambda function to use any of the input event fields to manipulate the business logic within the function to successfully perform the action. For more information about Lambda functions, see [Event-driven invocation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html#event-driven-invocation) in the AWS Lambda Developer Guide.

The input event format depends on whether you defined the action group with an API schema or with function details:
+ If you defined the action group with an API schema, the input event format is as follows:

  ```
  {
      "messageVersion": "1.0",
      "agent": {
          "name": "string",
          "id": "string",
          "alias": "string",
          "version": "string"
      },
      "inputText": "string",
      "sessionId": "string",
      "actionGroup": "string",
      "apiPath": "string",
      "httpMethod": "string",
      "parameters": [
          {
              "name": "string",
              "type": "string",
              "value": "string"
          },
      ...
      ],
      "requestBody": {
          "content": {
              "<content_type>": {
                  "properties": [
                     {
                         "name": "string",
                         "type": "string",
                         "value": "string"
                      },
                              ...
                  ]
              }
          }
      },
      "sessionAttributes": {
          "string": "string",
      },
      "promptSessionAttributes": {
          "string": "string"
      }
  }
  ```
+ If you defined the action group with function details, the input event format is as follows:

  ```
  {
      "messageVersion": "1.0",
      "agent": {
          "name": "string",
          "id": "string",
          "alias": "string",
          "version": "string"
      },
      "inputText": "string",
      "sessionId": "string",
      "actionGroup": "string",
      "function": "string",
      "parameters": [
          {
              "name": "string",
              "type": "string",
              "value": "string"
          },
      ...
      ],
      "sessionAttributes": {
          "string": "string",
      },
      "promptSessionAttributes": {
          "string": "string"
      }
  }
  ```

The following list describes the input event fields;
+ `messageVersion` – The version of the message that identifies the format of the event data going into the Lambda function and the expected format of the response from a Lambda function. Amazon Bedrock only supports version 1.0.
+ `agent` – Contains information about the name, ID, alias, and version of the agent that the action group belongs to.
+ `inputText` – The user input for the conversation turn.
+ `sessionId` – The unique identifier of the agent session.
+ `actionGroup` – The name of the action group.
+ `parameters` – Contains a list of objects. Each object contains the name, type, and value of a parameter in the API operation, as defined in the OpenAPI schema, or in the function.
+ If you defined the action group with an API schema, the input event contains the following fields:
  + `apiPath` – The path to the API operation, as defined in the OpenAPI schema.
  + `httpMethod` – The method of the API operation, as defined in the OpenAPI schema.
  + `requestBody` – Contains the request body and its properties, as defined in the OpenAPI schema for the action group.
+ If you defined the action group with function details, the input event contains the following field:
  + `function` – The name of the function as defined in the function details for the action group.
+ `sessionAttributes` – Contains [session attributes](agents-session-state.md) and their values. These attributes are stored over a [session](advanced-prompts.md#advanced-prompts-terminology) and provide context for the agent.
+ `promptSessionAttributes` – Contains [prompt session attributes](agents-session-state.md) and their values. These attributes are stored over a [turn](advanced-prompts.md#advanced-prompts-terminology) and provide context for the agent.

## Lambda response event to Amazon Bedrock
<a name="agents-lambda-response"></a>

Amazon Bedrock expects a response from your Lambda function that matches the following format. The response consists of parameters returned from the API operation. The agent can use the response from the Lambda function for further orchestration or to help it return a response to the customer.

**Note**  
The maximum payload response size matches the maximum size of a synchronous response from the Lambda function. For more information, see the *invocation payload* resource [quota](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html#function-configuration-deployment-and-execution) in the AWS Lambda Developer Guide.

The input event format depends on whether you defined the action group with an API schema or with function details:
+ If you defined the action group with an API schema, the response format is as follows:

  ```
  {
      "messageVersion": "1.0",
      "response": {
          "actionGroup": "string",
          "apiPath": "string",
          "httpMethod": "string",
          "httpStatusCode": number,
          "responseBody": {
              "<contentType>": {
                  "body": "JSON-formatted string" 
              }
          }
      },
      "sessionAttributes": {
          "string": "string",
          ...
      },
      "promptSessionAttributes": {
          "string": "string",
          ...
      },
      "knowledgeBasesConfiguration": [
          {
              "knowledgeBaseId": "string",
              "retrievalConfiguration": {
                  "vectorSearchConfiguration": {
                      "numberOfResults": int,
                      "overrideSearchType": "HYBRID | SEMANTIC",
                      "filter": [RetrievalFilter](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrievalFilter.html) object
                  }
              }
          },
          ...
      ]
  }
  ```
+ If you defined the action group with function details, the response format is as follows:

  ```
  {
      "messageVersion": "1.0",
      "response": {
          "actionGroup": "string",
          "function": "string",
          "functionResponse": {
              "responseState": "FAILURE | REPROMPT",
              "responseBody": {
                  "<functionContentType>": { 
                      "body": "JSON-formatted string"
                  }
              }
          }
      },
      "sessionAttributes": {
          "string": "string",
      },
      "promptSessionAttributes": {
          "string": "string"
      },
      "knowledgeBasesConfiguration": [
          {
              "knowledgeBaseId": "string",
              "retrievalConfiguration": {
                  "vectorSearchConfiguration": {
                      "numberOfResults": int,
                      "filter": {
                          [RetrievalFilter](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrievalFilter.html) object
                      }
                  }
              }
          },
          ...
      ]
  }
  ```

The following list describes the response fields:
+ `messageVersion` – The version of the message that identifies the format of the event data going into the Lambda function and the expected format of the response from a Lambda function. Amazon Bedrock only supports version 1.0.
+ `response` – Contains the following information about the API response.
  + `actionGroup` – The name of the action group.
  + If you defined the action group with an API schema, the following fields can be in the response:
    + `apiPath` – The path to the API operation, as defined in the OpenAPI schema.
    + `httpMethod` – The method of the API operation, as defined in the OpenAPI schema.
    + `httpStatusCode` – The HTTP status code returned from the API operation.
    + `responseBody` – Contains the response body, as defined in the OpenAPI schema.
  + If you defined the action group with function details, the following fields can be in the response:
    + `responseState` (Optional) – Set to one of the following states to define the agent's behavior after processing the action:
      + FAILURE – The agent throws a `DependencyFailedException` for the current session. Applies when the function execution fails because of a dependency failure.
      + REPROMPT – The agent passes a response string to the model to reprompt it. Applies when the function execution fails because of invalid input.
    + `responseBody` – Contains an object that defines the response from execution of the function. The key is the content type (currently only `TEXT` is supported) and the value is an object containing the `body` of the response.
+ (Optional) `sessionAttributes` – Contains session attributes and their values. For more information, see [Session and prompt session attributes](agents-session-state.md#session-state-attributes).
+ (Optional) `promptSessionAttributes` – Contains prompt attributes and their values. For more information, see [Session and prompt session attributes](agents-session-state.md#session-state-attributes).
+ (Optional) `knowledgeBasesConfiguration` – Contains a list of query configurations for knowledge bases attached to the agent. For more information, see [Knowledge base retrieval configurations](agents-session-state.md#session-state-kb).

## Action group Lambda function example
<a name="agents-lambda-example"></a>

The following is a minimal example of how the Lambda function can be defined in Python. Select the tab corresponding to whether you defined the action group with an OpenAPI schema or with function details:

------
#### [ OpenAPI schema ]

```
def lambda_handler(event, context):

    agent = event['agent']
    actionGroup = event['actionGroup']
    api_path = event['apiPath']
    # get parameters
    get_parameters = event.get('parameters', [])
    # post parameters
    post_parameters = event['requestBody']['content']['application/json']['properties']

    response_body = {
        'application/json': {
            'body': "sample 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']
    
    api_response = {
        'messageVersion': '1.0', 
        'response': action_response,
        'sessionAttributes': session_attributes,
        'promptSessionAttributes': prompt_session_attributes
    }
        
    return api_response
```

------
#### [ Function details ]

```
def lambda_handler(event, context):

    agent = event['agent']
    actionGroup = event['actionGroup']
    function = event['function']
    parameters = event.get('parameters', [])

    response_body = {
        'TEXT': {
            'body': "sample response"
        }
    }
    
    function_response = {
        'actionGroup': event['actionGroup'],
        'function': event['function'],
        'functionResponse': {
            'responseBody': response_body
        }
    }
    
    session_attributes = event['sessionAttributes']
    prompt_session_attributes = event['promptSessionAttributes']
    
    action_response = {
        'messageVersion': '1.0', 
        'response': function_response,
        'sessionAttributes': session_attributes,
        'promptSessionAttributes': prompt_session_attributes
    }
        
    return action_response
```

------

# Return control to the agent developer by sending elicited information in an InvokeAgent response
<a name="agents-returncontrol"></a>

Rather than sending the information that your agent has elicited from the user to a Lambda function for fulfillment, you can instead choose to return control to the agent developer by sending the information in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response. You can configure return of control to the agent developer when creating or updating an action group. Through the API, you specify `RETURN_CONTROL` as the `customControl` value in the `actionGroupExecutor` object in a [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreateAgentActionGroup.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreateAgentActionGroup.html) or [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_UpdateAgentActionGroup.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_UpdateAgentActionGroup.html) request. For more information, see [Add an action group to your agent in Amazon Bedrock](agents-action-add.md).

If you configure return of control for an action group, and if the agent determines that it should call an action in this action group, the API or function details elicited from the user will be returned in the `invocationInputs` field in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response, alongside a unique `invocationId`. You can then do the following:
+ Set up your application to invoke the API or function that you defined, provided the information returned in the `invocationInputs`.
+ Send the results from your application's invocation in another [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) request, in the `sessionState` field, to provide context to the agent. You must use the same `invocationId` and `actionGroup` that were returned in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response. This information can be used as context for further orchestration, sent to post-processing for the agent to format a response, or used directly in the agent's response to the user.
**Note**  
If you include `returnControlInvocationResults` in the `sessionState` field, the `inputText` field will be ignored.

To learn how to configure return of control to the agent developer while creating the action group, see [Add an action group to your agent in Amazon Bedrock](agents-action-add.md).

## Example for returning control to the agent developer
<a name="agents-returncontrol-ex"></a>

For example, you might have the following action groups:
+ A `PlanTrip` action group with a `suggestActivities` action that helps your users find activities to do during a trip. The `description` for this action says `This action suggests activities based on retrieved weather information`.
+ A `WeatherAPIs` action group with a `getWeather` action that helps your user get the weather for a specific location. The action's required parameters are `location` and `date`. The action group is configured to return control to the agent developer.

The following is a hypothetical sequence that might occur:

1. The user prompts your agent with the following query: **What should I do today?** This query is sent in the `inputText` field of an [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) request.

1. Your agent recognizes that the `suggestActivities` action should be invoked, but given the description, predicts that it should first invoke the `getWeather` action as context for helping to fulfill the `suggestActivities` action.

1. The agent knows that the current `date` is `2024-09-15`, but needs the `location` of the user as a required parameter to get the weather. It reprompts the user with the question "Where are you located?"

1. The user responds **Seattle**.

1. The agent returns the parameters for `getWeather` in the following [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response (select a tab to see examples for an action group defined with that method):

------
#### [ Function details ]

   ```
   HTTP/1.1 200
   x-amzn-bedrock-agent-content-type: application/json
   x-amz-bedrock-agent-session-id: session0
   Content-type: application/json
    
   {
       "returnControl": {
           "invocationInputs": [{
               "functionInvocationInput": {
                   "actionGroup": "WeatherAPIs",
                   "function": "getWeather",
                   "parameters": [
                       {
                           "name": "location",
                           "type": "string",
                           "value": "seattle"
                       },
                       {
                           "name": "date",
                           "type": "string",
                           "value": "2024-09-15"
                       }
                   ]
               }
           }],
           "invocationId": "79e0feaa-c6f7-49bf-814d-b7c498505172"
       }
   }
   ```

------
#### [ OpenAPI schema ]

   ```
   HTTP/1.1 200
   x-amzn-bedrock-agent-content-type: application/json
   x-amz-bedrock-agent-session-id: session0
   Content-type: application/json
   
   {
       "invocationInputs": [{
           "apiInvocationInput": {
               "actionGroup": "WeatherAPIs",
               "apiPath": "/get-weather",
               "httpMethod": "get",
               "parameters": [
                   {
                       "name": "location",
                       "type": "string",
                       "value": "seattle"
                   },
                   {
                       "name": "date",
                       "type": "string",
                       "value": "2024-09-15"
                   }
               ]
           }
       }],
       "invocationId": "337cb2f6-ec74-4b49-8141-00b8091498ad"
   }
   ```

------

1. Your application is configured to use these parameters to get the weather for `seattle` for the date `2024-09-15`. The weather is determined to be rainy.

1. You send these results in the `sessionState` field of another [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) request, using the same `invocationId`, `actionGroup`, and `function` as the previous response. Select a tab to see examples for an action group defined with that method:

------
#### [ Function details ]

   ```
   POST https://bedrock-agent-runtime.us-east-1.amazonaws.com/agents/AGENT12345/agentAliases/TSTALIASID/sessions/abb/text
               
   {
       "enableTrace": true,
       "sessionState": {
           "invocationId": "79e0feaa-c6f7-49bf-814d-b7c498505172",
           "returnControlInvocationResults": [{
               "functionResult": {
                   "actionGroup": "WeatherAPIs",
                   "function": "getWeather",
                   "responseBody": {
                       "TEXT": {
                           "body": "It's rainy in Seattle today."
                       }
                   }
               }
           }]
       }
   }
   ```

------
#### [ OpenAPI schema ]

   ```
   POST https: //bedrock-agent-runtime.us-east-1.amazonaws.com/agents/AGENT12345/agentAliases/TSTALIASID/sessions/abb/text
    
   {
       "enableTrace": true,
       "sessionState": {
           "invocationId": "337cb2f6-ec74-4b49-8141-00b8091498ad",
           "returnControlInvocationResults": [{
               "apiResult": {
                   "actionGroup": "WeatherAPIs",
                   "httpMethod": "get",
                   "apiPath": "/get-weather",
                   "responseBody": {
                       "application/json": {
                           "body": "It's rainy in Seattle today."
                       }
                   }
               }
           }]
       }
   }
   ```

------

1. The agent predicts that it should call the `suggestActivities` action. It uses the context that it's rainy that day and suggests indoor, rather than outdoor, activities for the user in the response.

### Example for returning control to the collaborator agent
<a name="collaborator-agent-returncontrol-ex"></a>

If you are using [multi-agent collaboration](agents-multi-agent-collaboration.md) and if an agent collaborator chooses to return control by sending the information in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response, the information is returned in supervisor agent response with additional identifiers `agentId` and `collaboratorName`. Select a tab to see examples for an action group defined with that method: 

------
#### [ Function details ]

```
HTTP/1.1 200
x-amzn-bedrock-agent-content-type: application/json
x-amz-bedrock-agent-session-id: session0
Content-type: application/json
 
{
    "returnControl": {
        "invocationInputs": [{
            "functionInvocationInput": {
                "agentId": "AGENTID",
                "collaboratorName": "WeatherAgent"
                "actionGroup": "WeatherAPIs",
                "function": "getWeather",
                "parameters": [
                    {
                        "name": "location",
                        "type": "string",
                        "value": "seattle"
                    },
                    {
                        "name": "date",
                        "type": "string",
                        "value": "2024-09-15"
                    }
                ]
            }
        }],
        "invocationId": "79e0feaa-c6f7-49bf-814d-b7c498505172"
    }
}
```

------
#### [ OpenAPI Schema ]

```
HTTP/1.1 200
x-amzn-bedrock-agent-content-type: application/json
x-amz-bedrock-agent-session-id: session0
Content-type: application/json

{
    "invocationInputs": [{
        "apiInvocationInput": {
            "actionGroup": "WeatherAPIs",
            "agentId": "AGENTID",
            "collaboratorName": "WeatherAgent"
            "apiPath": "/get-weather",
            "httpMethod": "get",
            "parameters": [
                {
                    "name": "location",
                    "type": "string",
                    "value": "seattle"
                },
                {
                    "name": "date",
                    "type": "string",
                    "value": "2024-09-15"
                }
            ]
        }
    }],
    "invocationId": "337cb2f6-ec74-4b49-8141-00b8091498ad"
}
```

------

Invoker of supervisor agent sends the results in the `sessionState` field back to supervisor agent with the corresponding `agentId` for it to be propagated to the right agent collaborator.

------
#### [ Function details ]

```
POST https://bedrock-agent-runtime.us-east-1.amazonaws.com/agents/AGENT12345/agentAliases/TSTALIASID/sessions/abb/text
            
{
    "enableTrace": true,
    "sessionState": {
        "invocationId": "79e0feaa-c6f7-49bf-814d-b7c498505172",
        "returnControlInvocationResults": [{
            "functionResult": {
                "agentId": "AGENTID",
                "actionGroup": "WeatherAPIs",
                "function": "getWeather",
                "responseBody": {
                    "TEXT": {
                        "body": "It's rainy in Seattle today."
                    }
                }
            }
        }]
    }
}
```

------
#### [ OpenAPI Schema ]

```
POST https: //bedrock-agent-runtime.us-east-1.amazonaws.com/agents/AGENT12345/agentAliases/TSTALIASID/sessions/abb/text
 
{
    "enableTrace": true,
    "sessionState": {
        "invocationId": "337cb2f6-ec74-4b49-8141-00b8091498ad",
        "returnControlInvocationResults": [{
            "apiResult": {
                "agentId": "AGENTID",
                "actionGroup": "WeatherAPIs",
                "httpMethod": "get",
                "apiPath": "/get-weather",
                "responseBody": {
                    "application/json": {
                        "body": "It's rainy in Seattle today."
                    }
                }
            }
        }]
    }
}
```

------

# Get user confirmation before invoking action group function
<a name="agents-userconfirmation"></a>

You can safeguard your application from malicious prompt injections by requesting confirmation from your application users before invoking the action group function. When an end user interacts with your application, Amazon Bedrock Agent figures out the API or knowledge bases to invoke to automate the task for the user. The information from the API or knowledge bases might contain potentially damaging data. Between each iteration if the response contains any instruction, the agent will comply. If the response includes instructions for the model to invoke unintended actions, the agent will go ahead and comply with the instruction. To ensure that certain actions are implemented only after explicit user consent, we recommend that you request confirmation from the end user before invoking the function. 

When you configure your action group, you can choose to enable user confirmation for specific actions. If user confirmation is enabled for an action, agent responds with a confirmation question asking end user to either confirm or deny the action. You can enable user confirmation in the console, using the CLI, or using the SDK. 

To enable user confirmation for an action, see [Add an action group to your agent in Amazon Bedrock](agents-action-add.md).

## How user confirmation works
<a name="user-confirmation-works"></a>

The user confirmation is configured for an action in the action group by the agent developer. If the agent decides that it should call that action, the API or the function details elicited from the user and the user confirmation configured by the agent developer will be returned in the `invocationInputs` field in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response, alongside `invocationType`, and an unique `invocationId`.

The agent invokes the API or the function that was provided in the `invocationInputs`. If the user confirmation is enabled for the function or the API, the user is presented with an option to **CONFIRM** or **DENY** the action mentioned in the response.

The results from the agent’s invocation of the function or API is sent in another [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) request, in the `sessionState` field, to provide context to the agent. The request parameter for `InvokeAgent` uses `returnControlInvocationResults`, which is a list of map to `apiResult` or `functionResult` objects. The `apiResult` and `functionResult` objects have an additional field of `confirmationState`. This field has the user confirmation response. 

If the user response is **CONFIRM**, the function or the API in the response is implemented. 

If the user response is **DENY**, the function or the API in the response is not implemented. 

## Examples of the InvokeAgent response and request
<a name="agents-userconfirmation-ex"></a>

**Response**

```
HTTP/1.1 200
x-amzn-bedrock-agent-content-type: contentType
x-amz-bedrock-agent-session-id: sessionId
Content-type: application/json

{
   "chunk": { 
      ...
   },
   ...
   "returnControl": { 
      "invocationId": "string",
      "invocationInputs": [ 
         { ... }
      ]
   },
   "trace": { 
      "agentAliasId": "string",
      "agentId": "string",
      "agentVersion": "string",
      "sessionId": "string",
      "trace": { ... }
   },
}
```

**Request**

```
POST /agents/agentId/agentAliases/agentAliasId/sessions/sessionId/text HTTP/1.1
Content-type: application/json

{
   "enableTrace": boolean,
   "endSession": boolean,
   "inputText": "string",
   "sessionState": { 
      "invocationId": "string",
      "promptSessionAttributes": { 
         "string" : "string" 
      },
      "returnControlInvocationResults": [ 
         { ... }
      ],
      "sessionAttributes": { 
         "string" : "string" 
      }
   }
}
```

# Add an action group to your agent in Amazon Bedrock
<a name="agents-action-add"></a>

After setting up the OpenAPI schema and Lambda function for your action group, you can create the action group. Choose the tab for your preferred method, and then follow the steps:

**Note**  
If you are using Anthropic Claude 3.5 Sonnet, make sure that your tool name which will be of the form `httpVerb__actionGroupName__apiName` follows the Anthropic tool name format `^[a-zA-Z0-9_-]{1,64}$`. Your actionGroupName and apiName must not contain double underscores `'__'`.

------
#### [ Console ]

When you [create an agent](agents-create.md), you can add action groups to the working draft.

After an agent is created, you can add action groups to it by doing the following steps:

**To add an action group to an 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. Select **Agents** from the left navigation pane. Then, choose an agent in the **Agents** section.

1. Choose **Edit in Agent builder**.

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

1. (Optional) In the **Action group details** section, change the automatically generated **Name** and provide an optional **Description** for your action group.

1. In the **Action group type** section, select one of the following methods for defining the parameters that the agent can elicit from users to help carry out actions:

   1. **Define with function details** – Define parameters for your agent to elicit from the user in order to carry out the actions. For more information on adding functions, see [Define function details for your agent's action groups in Amazon Bedrock](agents-action-function.md).

   1. **Define with API schemas** – Define the API operations that the agent can invoke and the parameters . Use an OpenAPI schema that you created or use the console text editor to create the schema. For more information on setting up an OpenAPI schema, see [Define OpenAPI schemas for your agent's action groups in Amazon Bedrock](agents-api-schema.md)

1. In the **Action group invocation** section, you set up what the agent does after it predicts the API or function that it should invoke and receives the parameters that it needs. Choose one of the following options:
   + **Quick create a new Lambda function – *recommended*** – Let Amazon Bedrock create a basic Lambda function for your agent that you can later modify in AWS Lambda for your use case. The agent will pass the API or function that it predicts and the parameters, based on the session, to the Lambda function.
   + **Select an existing Lambda function** – Choose a [Lambda function that you created previously](agents-lambda.md) in AWS Lambda and the version of the function to use. The agent will pass the API or function that it predicts and the parameters, based on the session, to the Lambda function.
**Note**  
To allow the Amazon Bedrock service principal to access the Lambda function, [attach a resource-based policy to the Lambda function](agents-permissions.md#agents-permissions-lambda) to allow the Amazon Bedrock service principal to access the Lambda function.
   + **Return control** – Rather than passing the parameters for the API or function that it predicts to the Lambda function, the agent returns control to your application by passing the action that it predicts should be invoked, in addition to the parameters and information for the action that it determined from the session, in the [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) response. For more information, see [Return control to the agent developer by sending elicited information in an InvokeAgent response](agents-returncontrol.md).

1. Depending on your choice for the **Action group type**, you'll see one of the following sections:
   + If you selected **Define with function details**, you'll have an **Action group function** section. Do the following to define the function:

     1. Provide a **Name** and optional (but recommended) **Description**.

     1. To request confirmation from the user before the function is invoked, select **Enabled**. Requesting confirmation before invoking the function may safeguard your application from taking actions due to malicious prompt injections.

     1. In the **Parameters** subsection, choose **Add parameter**. Define the following fields:  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-add.html)

     1. To add another parameter, choose **Add parameter**.

     1. To edit a field in a parameter, select the field and edit it as necessary.

     1. To delete a parameter, choose the delete icon (![\[Trapezoid-shaped diagram showing data flow from source to destination through AWS Transfer Family.\]](http://docs.aws.amazon.com/bedrock/latest/userguide/images/icons/trash.png)) in the row containing the parameter.

     If you prefer to define the function by using a JSON object, choose **JSON editor** instead of **Table**. The JSON object format is as follows (each key in the `parameters` object is a parameter name that you provide):

     ```
     {
         "name": "string",
         "description": "string",
         "parameters": [
             {
                 "name": "string",
                 "description": "string",
                 "required": "True" | "False",
                 "type": "string" | "number" | "integer" | "boolean" | "array"
             }
         ]
     }
     ```

     To add another function to your action group by defining another set of parameters, choose **Add action group function**.
   + If you selected **Define with API schemas**, you'll have an **Action group schema** section with the following options:
     + To use an OpenAPI schema that you previously prepared with API descriptions, structures, and parameters for the action group, select **Select API schema** and provide a link to the Amazon S3 URI of the schema.
     + To define the OpenAPI schema with the in-line schema editor, select **Define via in-line schema editor**. A sample schema appears that you can edit.

       1. Select the format for the schema by using the dropdown menu next to **Format**.

       1. To import an existing schema from S3 to edit, select **Import schema**, provide the S3 URI, and select **Import**.

       1. To restore the schema to the original sample schema, select **Reset** and then confirm the message that appears by selecting **Reset** again.

1. When you're done creating the action group, choose **Add**. If you defined an API schema, a green success banner appears if there are no issues. If there are issues validating the schema, a red banner appears. You have the following options:
   + Scroll through the schema to see the lines where an error or warning about formatting exists. An X indicates a formatting error, while an exclamation mark indicates a warning about formatting.
   + Select **View details** in the red banner to see a list of errors about the content of the API schema.

1. Make sure to **Prepare** to apply the changes that you have made to the agent before testing it.

------
#### [ API ]

To create an action group, send a [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreateAgentActionGroup.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreateAgentActionGroup.html) request with an [Agents for Amazon Bedrock build-time endpoint](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt). You must provide either a [ function schema](agents-action-function.md) or an [OpenAPI schema](agents-api-schema.md).

The following list describes the fields in the request:
+ The following fields are required:  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-add.html)
+ To define the parameters for the action group, you must specify one of the following fields (you can't specify both).  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-add.html)

  The following shows the general format of the `functionSchema` and `apiSchema`:
  + Each item in the `functionSchema` array is a [FunctionSchema](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_FunctionSchema.html) object. For each function, specify the following: 
    + Provide a `name` and optional (but recommended) `description`.
    + Optionally, specify `ENABLED` for `requireConfirmation` field to request confirmation from the user before the function is invoked. Requesting confirmation before invoking the function may safeguard your application from taking actions due to malicious prompt injections.
    + In the `parameters` object, each key is a parameter name, mapped to details about it in a [ParameterDetail](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ParameterDetail.html) object.

    The general format of the `functionSchema` is as follows:

    ```
    "functionSchema": [
        {
            "name": "string",
            "description": "string",
            "requireConfirmation": ENABLED | DISABLED,
            "parameters": {
                "<string>": {
                    "type": "string" | number | integer | boolean | array,
                    "description": "string",
                    "required": boolean
                },
                ... // up to 5 parameters
            }
        },
        ... // up to 11 functions
    ]
    ```
  + The [APISchema](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_APISchema.html) can be in one of the following formats:

    1. For the following format, you can directly paste the JSON or YAML-formatted OpenAPI schema as the value.

       ```
       "apiSchema": {
           "payload": "string"
       }
       ```

    1. For the following format, specify the Amazon S3 bucket name and object key where the OpenAPI schema is stored.

       ```
       "apiSchema": {
           "s3": {
               "s3BucketName": "string",
               "s3ObjectKey": "string"
           }
       }
       ```
+ To configure how the action group handles the invocation of the action group after eliciting parameters from the user, you must specify one of the following fields within the `actionGroupExecutor` field.  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-add.html)
+ The following fields are optional:  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-add.html)

  ```
      def create_agent_action_group(
              self, name, description, agent_id, agent_version, function_arn, api_schema
      ):
          """
          Creates an action group for an agent. An action group defines a set of actions that an
          agent should carry out for the customer.
  
          :param name: The name to give the action group.
          :param description: The description of the action group.
          :param agent_id: The unique identifier of the agent for which to create the action group.
          :param agent_version: The version of the agent for which to create the action group.
          :param function_arn: The ARN of the Lambda function containing the business logic that is
                               carried out upon invoking the action.
          :param api_schema: Contains the OpenAPI schema for the action group.
          :return: Details about the action group that was created.
          """
          try:
              response = self.client.create_agent_action_group(
                  actionGroupName=name,
                  description=description,
                  agentId=agent_id,
                  agentVersion=agent_version,
                  actionGroupExecutor={"lambda": function_arn},
                  apiSchema={"payload": api_schema},
              )
              agent_action_group = response["agentActionGroup"]
          except ClientError as e:
              logger.error(f"Error: Couldn't create agent action group. Here's why: {e}")
              raise
          else:
              return agent_action_group
  ```

  For more information, see [Hello Amazon Bedrock Agents](bedrock-agent_example_bedrock-agent_Hello_section.md).

------

# View information about an action group
<a name="agents-action-view"></a>

To learn how to view information about an action group, choose the tab for your preferred method, and then follow the steps:

------
#### [ Console ]

**To view information about an action group**

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. Select **Agents** from the left navigation pane. Then, choose an agent in the **Agents** section.

1. Choose an agent in the **Agents** section.

1. On the agent details page, for the **Working draft** section, choose the working draft.

1. In the **Action groups** section, choose an action group for which to view information.

------
#### [ API ]

To get information about an action group, send a [GetAgentActionGroup](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetAgentActionGroup.html) request with an [Agents for Amazon Bedrock build-time endpoint](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt) and specify the `actionGroupId`, `agentId`, and `agentVersion`.

To list information about an agent's action groups, send a [ListAgentActionGroups](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListAgentActionGroups.html) request with an [Agents for Amazon Bedrock build-time endpoint](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt). Specify the `agentId` and `agentVersion` for which you want to see action groups. You can include the following optional parameters:


****  

| Field | Short description | 
| --- | --- | 
| maxResults | The maximum number of results to return in a response. | 
| nextToken | If there are more results than the number you specified in the maxResults field, the response returns a nextToken value. To see the next batch of results, send the nextToken value in another request. | 

```
    def list_agent_action_groups(self, agent_id, agent_version):
        """
        List the action groups for a version of an Amazon Bedrock Agent.

        :param agent_id: The unique identifier of the agent.
        :param agent_version: The version of the agent.
        :return: The list of action group summaries for the version of the agent.
        """

        try:
            action_groups = []

            paginator = self.client.get_paginator("list_agent_action_groups")
            for page in paginator.paginate(
                    agentId=agent_id,
                    agentVersion=agent_version,
                    PaginationConfig={"PageSize": 10},
            ):
                action_groups.extend(page["actionGroupSummaries"])

        except ClientError as e:
            logger.error(f"Couldn't list action groups. {e}")
            raise
        else:
            return action_groups
```

For more information, see [Hello Amazon Bedrock Agents](bedrock-agent_example_bedrock-agent_Hello_section.md).

------

# Modify an action group
<a name="agents-action-edit"></a>

To learn how to modify an action group, choose the tab for your preferred method, and then follow the steps:

------
#### [ Console ]

**To modify an action group**

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. Select **Agents** from the left navigation pane. Then, choose an agent in the **Agents** section.

1. Choose **Edit in Agent builder**

1. In the **Action groups** section, select an action group to edit. Then choose **Edit**.

1. Edit the existing fields as necessary. For more information, see [Use action groups to define actions for your agent to perform](agents-action-create.md).

1. To define the schema for the action group with the in-line OpenAPI schema editor, for **Select API schema**, choose **Define with in-line OpenAPI schema editor**. A sample schema appears that you can edit. You can configure the following options:
   + To import an existing schema from Amazon S3 to edit, choose **Import schema**, provide the Amazon S3 URI, and select **Import**.
   + To restore the schema to the original sample schema, choose **Reset** and then confirm the message that appears by choosing **Confirm**.
   + To select a different format for the schema, use the dropdown menu labeled **JSON**.
   + To change the visual appearance of the schema, choose the gear icon below the schema.

1. To control whether the agent can use the action group, select **Enable** or **Disable**. Use this function to help troubleshoot your agent's behavior.

1. To remain in the same window so that you can test your change, choose **Save**. To return to the action group details page, choose **Save and exit**.

1. A success banner appears if there are no issues. If there are issues validating the schema, an error banner appears. To see a list of errors, choose **Show details** in the banner.

1. To apply the changes that you made to the agent before testing it, choose **Prepare** in the **Test** window or at the top of the **Working draft** page.

------
#### [ API ]

To modify an action group, send an [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_UpdateAgentActionGroup.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_UpdateAgentActionGroup.html) request with an [Agents for Amazon Bedrock build-time endpoint](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt). Because all fields will be overwritten, include both fields that you want to update as well as fields that you want to keep the same. You must specify the `agentVersion` as `DRAFT`. For more information about required and optional fields, see [Use action groups to define actions for your agent to perform](agents-action-create.md).

To apply the changes to the working draft, send a [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_PrepareAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_PrepareAgent.html) request with an [Agents for Amazon Bedrock build-time endpoint](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt). Include the `agentId` in the request. The changes apply to the `DRAFT` version, which the `TSTALIASID` alias points to.

------

# Delete an action group
<a name="agents-action-delete"></a>

To learn how to delete an action group, choose the tab for your preferred method, and then follow the steps:

------
#### [ Console ]

**To delete an action group**

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. Select **Agents** from the left navigation pane. Then, choose an agent in the **Agents** section.

1. Choose **Edit in Agent builder**

1. In the **Action groups** section, choose the option button that's next to the action group you want to delete.

1. A dialog box appears warning you about the consequences of deletion. To confirm that you want to delete the action group, enter **delete** in the input field and then select **Delete**.

1. When deletion is complete, a success banner appears.

1. To apply the changes that you made to the agent before testing it, choose **Prepare** in the **Test** window or at the top of the **Working draft** page.

------
#### [ API ]

To delete an action group, send a [DeleteAgentActionGroup](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_DeleteAgentActionGroup.html) request. Specify the `actionGroupId` and the `agentId` and `agentVersion` from which to delete it. By default, the `skipResourceInUseCheck` parameter is `false` and deletion is stopped if the resource is in use. If you set `skipResourceInUseCheck` to `true`, the resource will be deleted even if the resource is in use.

To apply the changes to the working draft, send a [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_PrepareAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_PrepareAgent.html) request with an [Agents for Amazon Bedrock build-time endpoint](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt). Include the `agentId` in the request. The changes apply to the `DRAFT` version, which the `TSTALIASID` alias points to.

------