Skip to content

Commit 7361e11

Browse files
dreamorosisvozzaleandrodamascena
authored
docs(event-handler): add docs page for Bedrock Agent Function (#3991)
Co-authored-by: Stefano Vozza <svozza@amazon.com> Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
1 parent 583e3ae commit 7361e11

File tree

11 files changed

+552
-3
lines changed

11 files changed

+552
-3
lines changed
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
---
2+
title: Bedrock Agents
3+
description: Event Handler for Amazon Bedrock Agents
4+
status: new
5+
---
6+
7+
<!-- markdownlint-disable MD043 -->
8+
9+
Create [Amazon Bedrock Agents](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html#agents-how) and focus on building your agent's logic without worrying about parsing and routing requests.
10+
11+
```mermaid
12+
flowchart LR
13+
Bedrock[LLM] <-- uses --> Agent
14+
You[User input] --> Agent
15+
Agent[Bedrock Agent] <-- tool use --> Lambda
16+
17+
subgraph Agent[Bedrock Agent]
18+
ToolDescriptions[Tool Definitions]
19+
end
20+
21+
subgraph Lambda[Lambda Function]
22+
direction TB
23+
Parsing[Parameter Parsing] --> Routing
24+
Routing --> Code[Your code]
25+
Code --> ResponseBuilding[Response Building]
26+
end
27+
28+
style You stroke:#0F0,stroke-width:2px
29+
```
30+
31+
## Key Features
32+
33+
* Easily expose tools for your Large Language Model (LLM) agents
34+
* Automatic routing based on tool name and function details
35+
* Graceful error handling and response formatting
36+
37+
## Terminology
38+
39+
**Event handler** is a Powertools for AWS feature that processes an event, runs data parsing and validation, routes the request to a specific function, and returns a response to the caller in the proper format.
40+
41+
**Function details** consist of a list of parameters, defined by their name, data type, and whether or not they are required. The agent uses these configurations to determine what information it needs to elicit from the user.
42+
43+
**Action group** is a collection of two resources where you define the actions that the agent should carry out: an OpenAPI schema to define the APIs that the agent can invoke to carry out its tasks, and a Lambda function to execute those actions.
44+
45+
**Large Language Models (LLM)** are very large deep learning models that are pre-trained on vast amounts of data, capable of extracting meanings from a sequence of text and understanding the relationship between words and phrases within that text.
46+
47+
**Amazon Bedrock Agent** is an Amazon Bedrock feature to build and deploy conversational agents that can interact with your customers using Large Language Models (LLM) and AWS Lambda functions.
48+
49+
## Getting Started
50+
51+
```shell
52+
npm i @aws-lambda-powertools/event-handler
53+
```
54+
55+
### Required resources
56+
57+
You must create an Amazon Bedrock Agent with at least one action group. Each action group can contain up to 5 tools, which in turn need to match the ones defined in your Lambda function. Bedrock must have permission to invoke your Lambda function.
58+
59+
??? note "Click to see example IaC templates"
60+
61+
=== "AWS SAM"
62+
63+
```yaml
64+
--8<-- "examples/snippets/event-handler/bedrock-agents/templates/gettingStartedSam.yaml"
65+
```
66+
67+
=== "AWS CDK"
68+
69+
```typescript
70+
--8<-- "examples/snippets/event-handler/bedrock-agents/templates/gettingStartedCdk.ts"
71+
```
72+
73+
### Usage
74+
75+
Use the `BedrockAgentFunctionResolver` to register your tools and handle the requests to your Lambda function. The resolver will automatically parse the request, route it to the appropriate function, and return a well-formed response that includes the tool's output and any existing session attributes.
76+
77+
When passing the tool parameters to your handler, we will automatically cast them to the appropriate type based on the `type` field defined in the action group. This means you can use native JavaScript types like `string`, `number`, `boolean` without worrying about parsing them yourself.
78+
79+
Currently, we don't support parsing `array` types, so you will receive them as strings.
80+
81+
=== "Define a tool"
82+
83+
```typescript hl_lines="4 6 20"
84+
--8<-- "examples/snippets/event-handler/bedrock-agents/gettingStartedFunctionsTool.ts"
85+
```
86+
87+
1. The `description` field is optional, but highly recommended in the action group definition so that the LLM can understand what the tool does and how to use it.
88+
89+
## Advanced
90+
91+
### Handling errors
92+
93+
By default, we will handle errors gracefully and return a well-formed response to the agent so that it can continue the conversation with the user.
94+
95+
When an error occurs, we send back an error message in the response body that includes the error type and message. The agent will then use this information to let the user know that something went wrong.
96+
97+
If you want to handle errors differently, you can return a `BedrockFunctionResponse` with a custom `body` and `responseState` set to `FAILURE`. This is useful when you want to abort the conversation.
98+
99+
!!! tip
100+
You can use the same technique to reprompt the user for missing information or for them to correct their input. Just return a `BedrockFunctionResponse` with a custom message and `responseState` set to `REPROMPT`.
101+
102+
=== "Custom error handling"
103+
104+
```typescript hl_lines="19-25"
105+
--8<-- "examples/snippets/event-handler/bedrock-agents/stopConversation.ts"
106+
```
107+
108+
### Accessing Lambda context and event
109+
110+
You can access to the original Lambda event or context for additional information. These are passed to the handler function as optional arguments.
111+
112+
=== "Access event and context"
113+
114+
```typescript hl_lines="7-9"
115+
--8<-- "examples/snippets/event-handler/bedrock-agents/accessEventAndContext.ts"
116+
```
117+
118+
### Setting session attributes
119+
120+
When Bedrock Agents invoke your Lambda function, it can pass session attributes that you can use to store information across multiple interactions with the user. You can access these attributes in your handler function and modify them as needed.
121+
122+
=== "Working with session attributes"
123+
124+
```typescript hl_lines="24-27"
125+
--8<-- "examples/snippets/event-handler/bedrock-agents/sessionAttributes.ts"
126+
```
127+
128+
### Logging
129+
130+
By default, the `BedrockAgentFunctionResolver` uses the global `console` logger and emits only warnings and errors.
131+
132+
You can change this behavior by passing a custom logger instance to the `BedrockAgentFunctionResolver` constructor and setting its log level. Alternatively, you can also enable [Lambda Advanced Logging Controls](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs-advanced.html) and setting the log level to `DEBUG`.
133+
134+
When debug logging is enabled, the resolver will emit logs that show the underlying handler registration and the routing process. This is useful for understanding how the agent resolves the tools and routes the requests.
135+
136+
For example, when using the [Powertools for AWS Lambda logger](../logger.md), you can set the `LOG_LEVEL` to `DEBUG` in your environment variables or at the logger level and pass the logger instance to the `BedrockAgentFunctionResolver` constructor to enable debug logging.
137+
138+
=== "Debug logging"
139+
140+
```typescript hl_lines="9"
141+
--8<-- "examples/snippets/event-handler/bedrock-agents/debugLogging.ts"
142+
```
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent';
2+
import type { Context } from 'aws-lambda';
3+
4+
const app = new BedrockAgentFunctionResolver();
5+
6+
app.tool<{ city: string }>(
7+
async ({ city }, { event, context }) => {
8+
const { sessionAttributes } = event;
9+
sessionAttributes.requestId = context.awsRequestId;
10+
11+
return {
12+
city,
13+
airportCode: 'XYZ', // Simulated airport code for the city
14+
};
15+
},
16+
{
17+
name: 'getAirportCodeForCity',
18+
description: 'Get the airport code for a given city',
19+
}
20+
);
21+
22+
export const handler = async (event: unknown, context: Context) =>
23+
app.resolve(event, context);
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent';
2+
import { Logger } from '@aws-lambda-powertools/logger';
3+
import type { Context } from 'aws-lambda';
4+
5+
const logger = new Logger({
6+
serviceName: 'serverlessAirline',
7+
logLevel: 'DEBUG',
8+
});
9+
const app = new BedrockAgentFunctionResolver({ logger });
10+
11+
app.tool<{ city: string }>(
12+
async ({ city }) => {
13+
return {
14+
city,
15+
airportCode: 'XYZ', // Simulated airport code for the city
16+
};
17+
},
18+
{
19+
name: 'getAirportCodeForCity',
20+
description: 'Get the airport code for a given city',
21+
}
22+
);
23+
24+
export const handler = async (event: unknown, context: Context) =>
25+
app.resolve(event, context);
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent';
2+
import type { Context } from 'aws-lambda';
3+
4+
const app = new BedrockAgentFunctionResolver();
5+
6+
app.tool<{ city: string }>(
7+
async ({ city }) => {
8+
return {
9+
city,
10+
airportCode: 'XYZ',
11+
};
12+
},
13+
{
14+
name: 'getAirportCodeForCity',
15+
description: 'Get the airport code for a given city', // (1)!
16+
}
17+
);
18+
19+
export const handler = async (event: unknown, context: Context) =>
20+
app.resolve(event, context);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import {
2+
BedrockAgentFunctionResolver,
3+
BedrockFunctionResponse,
4+
} from '@aws-lambda-powertools/event-handler/bedrock-agent';
5+
import type { Context } from 'aws-lambda';
6+
7+
const app = new BedrockAgentFunctionResolver();
8+
9+
app.tool<{ city: string }>(
10+
async ({ city }, { event }) => {
11+
const {
12+
sessionAttributes,
13+
promptSessionAttributes,
14+
knowledgeBasesConfiguration,
15+
} = event;
16+
17+
// your logic to fetch airport code for the city
18+
19+
return new BedrockFunctionResponse({
20+
body: JSON.stringify({
21+
city,
22+
airportCode: 'XYZ',
23+
}),
24+
sessionAttributes: {
25+
...sessionAttributes,
26+
isCommercialAirport: true,
27+
},
28+
promptSessionAttributes,
29+
knowledgeBasesConfiguration,
30+
});
31+
},
32+
{
33+
name: 'getAirportCodeForCity',
34+
description: 'Get the airport code for a given city',
35+
}
36+
);
37+
38+
export const handler = async (event: unknown, context: Context) =>
39+
app.resolve(event, context);
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import {
2+
BedrockAgentFunctionResolver,
3+
BedrockFunctionResponse,
4+
} from '@aws-lambda-powertools/event-handler/bedrock-agent';
5+
import type { Context } from 'aws-lambda';
6+
7+
const app = new BedrockAgentFunctionResolver();
8+
9+
app.tool<{ city: string }>(
10+
async ({ city }, { event }) => {
11+
try {
12+
throw new Error('Simulated error for demonstration purposes');
13+
} catch (error) {
14+
const {
15+
sessionAttributes,
16+
promptSessionAttributes,
17+
knowledgeBasesConfiguration,
18+
} = event;
19+
return new BedrockFunctionResponse({
20+
body: `An error occurred while fetching the airport code for ${city}`,
21+
responseState: 'FAILURE',
22+
sessionAttributes,
23+
promptSessionAttributes,
24+
knowledgeBasesConfiguration,
25+
});
26+
}
27+
},
28+
{
29+
name: 'getAirportCodeForCity',
30+
description: 'Get the airport code for a given city',
31+
}
32+
);
33+
34+
export const handler = async (event: unknown, context: Context) =>
35+
app.resolve(event, context);

0 commit comments

Comments
 (0)