-
Notifications
You must be signed in to change notification settings - Fork 156
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
dreamorosi
merged 17 commits into
aws-powertools:main
from
svozza:bedrock-agent-resolver
May 26, 2025
Merged
Changes from 16 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8eee45d
wip(event-handler): add Amazon Bedrock Agents Functions Resolver
svozza ac2289d
use it.each for testing fucntion return type tests
svozza cb56656
create separate folders for agent/appsync resolver tests
svozza d604188
fix param name from definition to description
svozza 4054abd
make tool method generic for type Record<string, ParameterValue>>
svozza bf915d3
set type of event given to resolve as unknown and use type assertion …
svozza 30dd319
fix custom logger test to trigger all levels of log messages
svozza 4d8f48c
only use json.stringify
svozza fbca0ab
don't allow too function to be void
svozza 2bcb1bc
remove apply call in resolver
svozza 1fee557
rename folder to bedrock-agent
svozza ec0975d
remove object checkin type assertion
svozza 3b560ed
update paths in package.json to new bedrock-agent path
svozza 9807c2c
fix createEvent function to not add parameters key and set to undefined
svozza 610e72a
remove unused ParameterValue type import
svozza c916396
put event and context parameters into an options object
svozza c7332ed
fix missed reference to old bedrock-agent-function name
svozza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
227 changes: 227 additions & 0 deletions
227
packages/event-handler/src/bedrock-agent/BedrockAgentFunctionResolver.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { BedrockAgentFunctionResolver } from './BedrockAgentFunctionResolver.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.