|
| 1 | +import { EnvironmentVariablesService } from '@aws-lambda-powertools/commons'; |
| 2 | +import type { Context } from 'aws-lambda'; |
| 3 | +import type { |
| 4 | + BedrockAgentFunctionResponse, |
| 5 | + Configuration, |
| 6 | + ParameterValue, |
| 7 | + ResolverOptions, |
| 8 | + ResponseOptions, |
| 9 | + Tool, |
| 10 | + ToolFunction, |
| 11 | +} from '../types/bedrock-agent.js'; |
| 12 | +import type { GenericLogger } from '../types/common.js'; |
| 13 | +import { assertBedrockAgentFunctionEvent } from './utils.js'; |
| 14 | + |
| 15 | +export class BedrockAgentFunctionResolver { |
| 16 | + readonly #tools: Map<string, Tool> = new Map(); |
| 17 | + readonly #envService: EnvironmentVariablesService; |
| 18 | + readonly #logger: Pick<GenericLogger, 'debug' | 'warn' | 'error'>; |
| 19 | + |
| 20 | + constructor(options?: ResolverOptions) { |
| 21 | + this.#envService = new EnvironmentVariablesService(); |
| 22 | + const alcLogLevel = this.#envService.get('AWS_LAMBDA_LOG_LEVEL'); |
| 23 | + this.#logger = options?.logger ?? { |
| 24 | + debug: alcLogLevel === 'DEBUG' ? console.debug : () => {}, |
| 25 | + error: console.error, |
| 26 | + warn: console.warn, |
| 27 | + }; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Register a tool function for the Bedrock Agent. |
| 32 | + * |
| 33 | + * This method registers a function that can be invoked by a Bedrock Agent. |
| 34 | + * |
| 35 | + * @example |
| 36 | + * ```ts |
| 37 | + * import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent-function'; |
| 38 | + * |
| 39 | + * const app = new BedrockAgentFunctionResolver(); |
| 40 | + * |
| 41 | + * app.tool(async (params) => { |
| 42 | + * const { name } = params; |
| 43 | + * return `Hello, ${name}!`; |
| 44 | + * }, { |
| 45 | + * name: 'greeting', |
| 46 | + * description: 'Greets a person by name', |
| 47 | + * }); |
| 48 | + * |
| 49 | + * export const handler = async (event, context) => |
| 50 | + * app.resolve(event, context); |
| 51 | + * ``` |
| 52 | + * |
| 53 | + * The method also works as a class method decorator: |
| 54 | + * |
| 55 | + * @example |
| 56 | + * ```ts |
| 57 | + * import { BedrockAgentFunctionResolver } from '@aws-lambda-powertools/event-handler/bedrock-agent-function'; |
| 58 | + * |
| 59 | + * const app = new BedrockAgentFunctionResolver(); |
| 60 | + * |
| 61 | + * class Lambda { |
| 62 | + * @app.tool({ name: 'greeting', description: 'Greets a person by name' }) |
| 63 | + * async greeting(params) { |
| 64 | + * const { name } = params; |
| 65 | + * return `Hello, ${name}!`; |
| 66 | + * } |
| 67 | + * |
| 68 | + * async handler(event, context) { |
| 69 | + * return app.resolve(event, context); |
| 70 | + * } |
| 71 | + * } |
| 72 | + * |
| 73 | + * const lambda = new Lambda(); |
| 74 | + * export const handler = lambda.handler.bind(lambda); |
| 75 | + * ``` |
| 76 | + * |
| 77 | + * @param fn - The tool function |
| 78 | + * @param config - The configuration object for the tool |
| 79 | + */ |
| 80 | + public tool<TParams extends Record<string, ParameterValue>>( |
| 81 | + fn: ToolFunction<TParams>, |
| 82 | + config: Configuration |
| 83 | + ): undefined; |
| 84 | + public tool<TParams extends Record<string, ParameterValue>>( |
| 85 | + config: Configuration |
| 86 | + ): MethodDecorator; |
| 87 | + public tool<TParams extends Record<string, ParameterValue>>( |
| 88 | + fnOrConfig: ToolFunction<TParams> | Configuration, |
| 89 | + config?: Configuration |
| 90 | + ): MethodDecorator | undefined { |
| 91 | + // When used as a method (not a decorator) |
| 92 | + if (typeof fnOrConfig === 'function') { |
| 93 | + this.#registerTool(fnOrConfig, config as Configuration); |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + // When used as a decorator |
| 98 | + return (_target, _propertyKey, descriptor: PropertyDescriptor) => { |
| 99 | + const toolFn = descriptor.value as ToolFunction; |
| 100 | + this.#registerTool(toolFn, fnOrConfig); |
| 101 | + return descriptor; |
| 102 | + }; |
| 103 | + } |
| 104 | + |
| 105 | + #registerTool<TParams extends Record<string, ParameterValue>>( |
| 106 | + handler: ToolFunction<TParams>, |
| 107 | + config: Configuration |
| 108 | + ): void { |
| 109 | + const { name } = config; |
| 110 | + |
| 111 | + if (this.#tools.size >= 5) { |
| 112 | + this.#logger.warn( |
| 113 | + `The maximum number of tools that can be registered is 5. Tool ${name} will not be registered.` |
| 114 | + ); |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + if (this.#tools.has(name)) { |
| 119 | + this.#logger.warn( |
| 120 | + `Tool ${name} already registered. Overwriting with new definition.` |
| 121 | + ); |
| 122 | + } |
| 123 | + |
| 124 | + this.#tools.set(name, { |
| 125 | + handler: handler as ToolFunction, |
| 126 | + config, |
| 127 | + }); |
| 128 | + this.#logger.debug(`Tool ${name} has been registered.`); |
| 129 | + } |
| 130 | + |
| 131 | + #buildResponse(options: ResponseOptions): BedrockAgentFunctionResponse { |
| 132 | + const { |
| 133 | + actionGroup, |
| 134 | + function: func, |
| 135 | + body, |
| 136 | + errorType, |
| 137 | + sessionAttributes, |
| 138 | + promptSessionAttributes, |
| 139 | + } = options; |
| 140 | + |
| 141 | + return { |
| 142 | + messageVersion: '1.0', |
| 143 | + response: { |
| 144 | + actionGroup, |
| 145 | + function: func, |
| 146 | + functionResponse: { |
| 147 | + responseState: errorType, |
| 148 | + responseBody: { |
| 149 | + TEXT: { |
| 150 | + body, |
| 151 | + }, |
| 152 | + }, |
| 153 | + }, |
| 154 | + }, |
| 155 | + sessionAttributes, |
| 156 | + promptSessionAttributes, |
| 157 | + }; |
| 158 | + } |
| 159 | + |
| 160 | + async resolve( |
| 161 | + event: unknown, |
| 162 | + context: Context |
| 163 | + ): Promise<BedrockAgentFunctionResponse> { |
| 164 | + assertBedrockAgentFunctionEvent(event); |
| 165 | + |
| 166 | + const { |
| 167 | + function: toolName, |
| 168 | + parameters = [], |
| 169 | + actionGroup, |
| 170 | + sessionAttributes, |
| 171 | + promptSessionAttributes, |
| 172 | + } = event; |
| 173 | + |
| 174 | + const tool = this.#tools.get(toolName); |
| 175 | + |
| 176 | + if (tool == null) { |
| 177 | + this.#logger.error(`Tool ${toolName} has not been registered.`); |
| 178 | + return this.#buildResponse({ |
| 179 | + actionGroup, |
| 180 | + function: toolName, |
| 181 | + body: 'Error: tool has not been registered in handler.', |
| 182 | + }); |
| 183 | + } |
| 184 | + |
| 185 | + const toolParams: Record<string, ParameterValue> = {}; |
| 186 | + for (const param of parameters) { |
| 187 | + switch (param.type) { |
| 188 | + case 'boolean': { |
| 189 | + toolParams[param.name] = param.value === 'true'; |
| 190 | + break; |
| 191 | + } |
| 192 | + case 'number': |
| 193 | + case 'integer': { |
| 194 | + toolParams[param.name] = Number(param.value); |
| 195 | + break; |
| 196 | + } |
| 197 | + // this default will also catch array types but we leave them as strings |
| 198 | + // because we cannot reliably parse them |
| 199 | + default: { |
| 200 | + toolParams[param.name] = param.value; |
| 201 | + break; |
| 202 | + } |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + try { |
| 207 | + const res = await tool.handler(toolParams, { event, context }); |
| 208 | + const body = res == null ? '' : JSON.stringify(res); |
| 209 | + return this.#buildResponse({ |
| 210 | + actionGroup, |
| 211 | + function: toolName, |
| 212 | + body, |
| 213 | + sessionAttributes, |
| 214 | + promptSessionAttributes, |
| 215 | + }); |
| 216 | + } catch (error) { |
| 217 | + this.#logger.error(`An error occurred in tool ${toolName}.`, error); |
| 218 | + return this.#buildResponse({ |
| 219 | + actionGroup, |
| 220 | + function: toolName, |
| 221 | + body: `Error when invoking tool: ${error}`, |
| 222 | + sessionAttributes, |
| 223 | + promptSessionAttributes, |
| 224 | + }); |
| 225 | + } |
| 226 | + } |
| 227 | +} |
0 commit comments