Skip to content

feat(event-handler): add Amazon Bedrock Agents Functions Resolver #3957

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
May 26, 2025
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/event-handler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@
"default": "./lib/esm/appsync-events/index.js"
}
},
"./bedrock-agent-function": {
"require": {
"types": "./lib/cjs/bedrock-agent/index.d.ts",
"default": "./lib/cjs/bedrock-agent/index.js"
},
"import": {
"types": "./lib/esm/bedrock-agent/index.d.ts",
"default": "./lib/esm/bedrock-agent/index.js"
}
},
"./types": {
"require": {
"types": "./lib/cjs/types/index.d.ts",
Expand All @@ -56,6 +66,10 @@
"./lib/cjs/appsync-events/index.d.ts",
"./lib/esm/appsync-events/index.d.ts"
],
"bedrock-agent": [
"./lib/cjs/bedrock-agent/index.d.ts",
"./lib/esm/bedrock-agent/index.d.ts"
],
"types": [
"./lib/cjs/types/index.d.ts",
"./lib/esm/types/index.d.ts"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import { EnvironmentVariablesService } from '@aws-lambda-powertools/commons';
import type { Context } from 'aws-lambda';
import type {
BedrockAgentFunctionResponse,
Configuration,
ParameterValue,
ResolverOptions,
ResponseOptions,
Tool,
ToolFunction,
} from '../types/bedrock-agent.js';
import type { GenericLogger } from '../types/common.js';
import { assertBedrockAgentFunctionEvent } from './utils.js';

export class BedrockAgentFunctionResolver {
readonly #tools: Map<string, Tool> = new Map();
readonly #envService: EnvironmentVariablesService;
readonly #logger: Pick<GenericLogger, 'debug' | 'warn' | 'error'>;

constructor(options?: ResolverOptions) {
this.#envService = new EnvironmentVariablesService();
const alcLogLevel = this.#envService.get('AWS_LAMBDA_LOG_LEVEL');
this.#logger = options?.logger ?? {
debug: alcLogLevel === 'DEBUG' ? console.debug : () => {},
error: console.error,
warn: console.warn,
};
}

/**
* Register a tool function for the Bedrock Agent.
*
* This method registers a function that can be invoked by a Bedrock Agent.
*
* @example
* ```ts
* import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent-function';
*
* const app = new BedrockAgentFunctionResolver();
*
* app.tool(async (params) => {
* const { name } = params;
* return `Hello, ${name}!`;
* }, {
* name: 'greeting',
* description: 'Greets a person by name',
* });
*
* export const handler = async (event, context) =>
* app.resolve(event, context);
* ```
*
* The method also works as a class method decorator:
*
* @example
* ```ts
* import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent-function';
*
* const app = new BedrockAgentFunctionResolver();
*
* class Lambda {
* @app.tool({ name: 'greeting', description: 'Greets a person by name' })
* async greeting(params) {
* const { name } = params;
* return `Hello, ${name}!`;
* }
*
* async handler(event, context) {
* return app.resolve(event, context);
* }
* }
*
* const lambda = new Lambda();
* export const handler = lambda.handler.bind(lambda);
* ```
*
* @param fn - The tool function
* @param config - The configuration object for the tool
*/
public tool<TParams extends Record<string, ParameterValue>>(
fn: ToolFunction<TParams>,
config: Configuration
): undefined;
public tool<TParams extends Record<string, ParameterValue>>(
config: Configuration
): MethodDecorator;
public tool<TParams extends Record<string, ParameterValue>>(
fnOrConfig: ToolFunction<TParams> | Configuration,
config?: Configuration
): MethodDecorator | undefined {
// When used as a method (not a decorator)
if (typeof fnOrConfig === 'function') {
this.#registerTool(fnOrConfig, config as Configuration);
return;
}

// When used as a decorator
return (_target, _propertyKey, descriptor: PropertyDescriptor) => {
const toolFn = descriptor.value as ToolFunction;
this.#registerTool(toolFn, fnOrConfig);
return descriptor;
};
}

#registerTool<TParams extends Record<string, ParameterValue>>(
handler: ToolFunction<TParams>,
config: Configuration
): void {
const { name } = config;

if (this.#tools.size >= 5) {
this.#logger.warn(
`The maximum number of tools that can be registered is 5. Tool ${name} will not be registered.`
);
return;
}

if (this.#tools.has(name)) {
this.#logger.warn(
`Tool ${name} already registered. Overwriting with new definition.`
);
}

this.#tools.set(name, {
handler: handler as ToolFunction,
config,
});
this.#logger.debug(`Tool ${name} has been registered.`);
}

#buildResponse(options: ResponseOptions): BedrockAgentFunctionResponse {
const {
actionGroup,
function: func,
body,
errorType,
sessionAttributes,
promptSessionAttributes,
} = options;

return {
messageVersion: '1.0',
response: {
actionGroup,
function: func,
functionResponse: {
responseState: errorType,
responseBody: {
TEXT: {
body,
},
},
},
},
sessionAttributes,
promptSessionAttributes,
};
}

async resolve(
event: unknown,
context: Context
): Promise<BedrockAgentFunctionResponse> {
assertBedrockAgentFunctionEvent(event);

const {
function: toolName,
parameters = [],
actionGroup,
sessionAttributes,
promptSessionAttributes,
} = event;

const tool = this.#tools.get(toolName);

if (tool == null) {
this.#logger.error(`Tool ${toolName} has not been registered.`);
return this.#buildResponse({
actionGroup,
function: toolName,
body: 'Error: tool has not been registered in handler.',
});
}

const toolParams: Record<string, ParameterValue> = {};
for (const param of parameters) {
switch (param.type) {
case 'boolean': {
toolParams[param.name] = param.value === 'true';
break;
}
case 'number':
case 'integer': {
toolParams[param.name] = Number(param.value);
break;
}
// this default will also catch array types but we leave them as strings
// because we cannot reliably parse them
default: {
toolParams[param.name] = param.value;
break;
}
}
}

try {
const res = await tool.handler(toolParams, { event, context });
const body = res == null ? '' : JSON.stringify(res);
return this.#buildResponse({
actionGroup,
function: toolName,
body,
sessionAttributes,
promptSessionAttributes,
});
} catch (error) {
this.#logger.error(`An error occurred in tool ${toolName}.`, error);
return this.#buildResponse({
actionGroup,
function: toolName,
body: `Error when invoking tool: ${error}`,
sessionAttributes,
promptSessionAttributes,
});
}
}
}
1 change: 1 addition & 0 deletions packages/event-handler/src/bedrock-agent/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { BedrockAgentFunctionResolver } from './BedrockAgentFunctionResolver.js';
55 changes: 55 additions & 0 deletions packages/event-handler/src/bedrock-agent/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { isRecord, isString } from '@aws-lambda-powertools/commons/typeutils';
import type { BedrockAgentFunctionEvent } from '../types/bedrock-agent.js';

/**
* Asserts that the provided event is a BedrockAgentFunctionEvent.
*
* @param event - The incoming event to check
* @throws Error if the event is not a valid BedrockAgentFunctionEvent
*/
export function assertBedrockAgentFunctionEvent(
event: unknown
): asserts event is BedrockAgentFunctionEvent {
const isValid =
isRecord(event) &&
'actionGroup' in event &&
isString(event.actionGroup) &&
'function' in event &&
isString(event.function) &&
(!('parameters' in event) ||
(Array.isArray(event.parameters) &&
event.parameters.every(
(param) =>
isRecord(param) &&
'name' in param &&
isString(param.name) &&
'type' in param &&
isString(param.type) &&
'value' in param &&
isString(param.value)
))) &&
'messageVersion' in event &&
isString(event.messageVersion) &&
'agent' in event &&
isRecord(event.agent) &&
'name' in event.agent &&
isString(event.agent.name) &&
'id' in event.agent &&
isString(event.agent.id) &&
'alias' in event.agent &&
isString(event.agent.alias) &&
'version' in event.agent &&
isString(event.agent.version) &&
'inputText' in event &&
isString(event.inputText) &&
'sessionId' in event &&
isString(event.sessionId) &&
'sessionAttributes' in event &&
isRecord(event.sessionAttributes) &&
'promptSessionAttributes' in event &&
isRecord(event.promptSessionAttributes);

if (!isValid) {
throw new Error('Event is not a valid BedrockAgentFunctionEvent');
}
}
17 changes: 1 addition & 16 deletions packages/event-handler/src/types/appsync-events.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,7 @@
import type { Context } from 'aws-lambda';
import type { RouteHandlerRegistry } from '../appsync-events/RouteHandlerRegistry.js';
import type { Router } from '../appsync-events/Router.js';

// #region Shared

// biome-ignore lint/suspicious/noExplicitAny: We intentionally use `any` here to represent any type of data and keep the logger is as flexible as possible.
type Anything = any;

/**
* Interface for a generic logger object.
*/
type GenericLogger = {
trace?: (...content: Anything[]) => void;
debug: (...content: Anything[]) => void;
info?: (...content: Anything[]) => void;
warn: (...content: Anything[]) => void;
error: (...content: Anything[]) => void;
};
import type { Anything, GenericLogger } from './common.js';

// #region OnPublish fn

Expand Down
Loading