Repository navigation
fix(event-handler): make Bedrock Agent Function tool classes and ASP.NET Core work under Native AOT - #1372
Merged
Conversation
…> for Bedrock Agent Functions Add Tool<T1..T8, TResult>(name, description, handler, parameterName1..N) overloads that bind parameters by name without reading the delegate with reflection. RegisterTool<T> now invokes the tool methods kept by [DynamicallyAccessedMembers(PublicMethods)] instead of creating typed delegates, so it no longer needs [RequiresUnreferencedCode] or [RequiresDynamicCode]. The reflection-based JSON fallback for custom types is guarded by JsonSerializer.IsReflectionEnabledByDefault. Refs #1351
…oint work under Native AOT Map the endpoint with a RequestDelegate instead of a Delegate that needs RequestDelegateFactory, and write responses with source-generated serialization. Remove the UnconditionalSuppressMessage attributes that hid both problems. Add the named-parameter MapBedrockFunction overloads and drop [RequiresUnreferencedCode]/[RequiresDynamicCode] from MapBedrockToolType<T>. Refs #1351
…k Agent Functions Refs #1351
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #1372 +/- ##
===========================================
+ Coverage 80.29% 80.43% +0.13%
===========================================
Files 303 305 +2
Lines 12962 13058 +96
Branches 1551 1559 +8
===========================================
+ Hits 10408 10503 +95
- Misses 2098 2102 +4
+ Partials 456 453 -3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
… tool classes under AOT Remove the Tool<T1..T8, TResult> and MapBedrockFunction<T1..T8, TResult> overloads that took parameter names, and their tests. Under Native AOT, tools with parameters are [BedrockFunctionType] classes registered with RegisterTool<T>() or MapBedrockToolType<T>(). Point the Delegate overloads' AOT warning and the docs at tool classes. Refs #1351
…est body Addresses SonarCloud S8949. Refs #1351
|
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.



Issue number: closes #1351
Summary
Changes
#1352 marked the reflection-based Bedrock tool APIs as not AOT compatible. This PR makes
[BedrockFunctionType]tool classes and the ASP.NET Core package work under Native AOT. There are no public API additions.How
RegisterTool<T>works now:Delegatepath. Both paths use the sameParameterMappercode, now driven by(Type, name)pairs instead of aMethodInfo. Names match case-insensitively. The same types convert (string, int, long, double, bool, decimal, enums, arrays). Missing values become defaults.ILambdaContext,BedrockFunctionRequestand DI services bind by type, and custom types deserialize fromInputText. Error messages are the same, andTask<T>results are awaited.JsonSerializer.Deserialize(string, Type, ...)fallback (used when noIJsonTypeInfoResolveris passed) now sits behindJsonSerializer.IsReflectionEnabledByDefault && RuntimeFeatureWrapper.IsDynamicCodeSupported, in a small[ExcludeFromCodeCoverage]helper. Neither analyzer recognizes that guard (net8.0 and net10.0), so the helper has justified[UnconditionalSuppressMessage]attributes, the same approach as fix(tracing): capture async responses under Native AOT and remove Powertools AOT warnings #1353. Under AOT the parameter isnullunless the resolver has aJsonSerializerContext. Before, the same call threw inside acatchand also gavenull.MapPost("/", async (HttpContext) => IResult), which goes throughRequestDelegateFactory, and the response was written with reflection-based JSON. Both fail under AOT, and[UnconditionalSuppressMessage]attributes hid them. The endpoint is now aRequestDelegate, and the response, the 400 body and theProblemDetailsfallback use the package's source-generated context. An app-registeredIProblemDetailsServiceis still used first, asProblemHttpResultdoes.Delegatetools. They can't work under AOT: ILC keeps no metadata for a lambda's method, soDelegate.Methodthrows and the parameter names are gone. They keep[RequiresUnreferencedCode]/[RequiresDynamicCode], and the warning now points to tool classes.User experience
Under Native AOT, tools with parameters are defined as a tool class, and register with no warnings:
Delegatetools still warn at the call site:JIT behavior doesn't change. Docs:
bedrock_agent_function.mdis now a "Native AOT" section that says which APIs to use (tool classes, plus the typedFunc<BedrockFunctionRequest, ...>/Func<string>overloads).docs/snippets/bedrock-agent-function/NativeAot.cs: a tool class, its registration with the Lambda runtime and a source-generated context, and ASP.NET Core.JsonSerializerContext.Evidence
Native AOT runtime (.NET 10,
PublishAot=true, packages packed locally fromdevelopand from this branch, same app run under JIT and as a native binary):Tool(name, Func<BedrockFunctionRequest, BedrockFunctionResponse>),Tool(name, Func<string>)Tool(name, description, (string city, int days) => ...)(Delegate)Cannot retrieve a MethodInfo for this delegate ...(warns)RegisterTool<T>():(string, int),(double, bool),long -> int,(string, enum, int?, bool?), missing params,Task<string>,BedrockFunctionRequestparam, throwing tool, invalid enumFunc<Double, Boolean, String>is missing native code (warns)RegisterTool<T>(), custom type fromInputTextwith aJsonSerializerContextRegisterTool<T>(), custom type without a contextnull(documented)MapBedrockToolType<T>()NotSupportedException: JsonTypeInfo metadata for type Task<IResult>MapBedrockFunction(name, Delegate)MethodInfoerror (warns)The JIT responses of the ASP.NET Core endpoint (200 for a tool, 200 for an unknown tool, 400 for
null) are byte-identical todevelop. The 500ProblemDetailsbody has the same content, but'is now escaped as\u0027, because the source-generated context uses the default encoder rather than ASP.NET Core'sJsonOptions.Native AOT publish warnings (each package with
TrimmerRootAssembly): EventHandler 0, BedrockAgentFunction 0, BedrockAgentFunction.AspNetCore 0, on bothdevelopand this branch. The AspNetCore 0 ondevelopcame from the suppressions, which are now removed.Unit tests (EventHandler.Tests, 189 passed on net8.0 and on net10.0):
The full Release build from
libraries/(dotnet restore && dotnet build -c Release --no-restore) has 0 errors and no new warnings.dotnet build docs/snippetspasses.Merge Danger
Door: two-way
No signatures change. Two methods lose
[RequiresUnreferencedCode]/[RequiresDynamicCode], which could be added back.Blast Radius: narrow
RegisterTool<T>now callsMethodInfo.Invokeinstead ofDynamicInvoke. Arguments are the same, and so is the unwrapping ofTargetInvocationExceptioninto the tool's own error message.RequestDelegateFactory, so route-handler filters and endpoint metadata from the delegate don't apply. The library added none. TheProblemDetailsfallback ignores customizations to the app'sJsonOptions. AnIProblemDetailsServiceis still honored.Follow-ups, not in this PR:
int?,bool?) aren't bound by either path, as before.MapBedrockFunctioncall creates its own resolver, and only the first one gets the endpoint.Checklist
Is this a breaking change?
RFC issue number:
Checklist:
Acknowledgment
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.