| | | 1 | | using Microsoft.Agents.AI; |
| | | 2 | | using Microsoft.Extensions.AI; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Reflection; |
| | | 7 | | |
| | | 8 | | namespace NexusLabs.Needlr.AgentFramework; |
| | | 9 | | |
| | | 10 | | internal sealed class AgentFactory : IAgentFactory |
| | | 11 | | { |
| | | 12 | | private readonly IServiceProvider _serviceProvider; |
| | | 13 | | private readonly List<Action<AgentFrameworkConfigureOptions>> _configureCallbacks; |
| | | 14 | | private readonly IReadOnlyList<Type> _functionTypes; |
| | | 15 | | private readonly IReadOnlyDictionary<string, IReadOnlyList<Type>> _functionGroupMap; |
| | | 16 | | private readonly Lazy<AgentFrameworkConfigureOptions> _lazyConfiguredOptions; |
| | | 17 | | private readonly Lazy<IReadOnlyDictionary<Type, IReadOnlyList<AIFunction>>> _lazyFunctionsCache; |
| | | 18 | | private readonly IAIFunctionProvider? _generatedProvider; |
| | | 19 | | private readonly IReadOnlyList<IAIAgentBuilderPlugin> _plugins; |
| | | 20 | | private readonly Func<AgentResilienceAttribute, IAIAgentBuilderPlugin>? _perAgentResilienceFactory; |
| | | 21 | | |
| | | 22 | | private readonly IReadOnlyDictionary<string, Type> _agentTypeMap; |
| | | 23 | | |
| | 188 | 24 | | public AgentFactory( |
| | 188 | 25 | | IServiceProvider serviceProvider, |
| | 188 | 26 | | List<Action<AgentFrameworkConfigureOptions>> configureCallbacks, |
| | 188 | 27 | | IReadOnlyList<Type> functionTypes, |
| | 188 | 28 | | IReadOnlyDictionary<string, IReadOnlyList<Type>>? functionGroupMap = null, |
| | 188 | 29 | | IReadOnlyDictionary<string, Type>? agentTypeMap = null, |
| | 188 | 30 | | IAIFunctionProvider? generatedProvider = null, |
| | 188 | 31 | | IReadOnlyList<IAIAgentBuilderPlugin>? plugins = null, |
| | 188 | 32 | | Func<AgentResilienceAttribute, IAIAgentBuilderPlugin>? perAgentResilienceFactory = null) |
| | | 33 | | { |
| | 188 | 34 | | _serviceProvider = serviceProvider; |
| | 188 | 35 | | _configureCallbacks = configureCallbacks; |
| | 188 | 36 | | _functionTypes = functionTypes; |
| | 188 | 37 | | _functionGroupMap = functionGroupMap ?? new Dictionary<string, IReadOnlyList<Type>>(); |
| | 188 | 38 | | _agentTypeMap = agentTypeMap ?? new Dictionary<string, Type>(); |
| | 188 | 39 | | _generatedProvider = generatedProvider; |
| | 188 | 40 | | _plugins = plugins ?? []; |
| | 188 | 41 | | _perAgentResilienceFactory = perAgentResilienceFactory; |
| | | 42 | | |
| | 340 | 43 | | _lazyConfiguredOptions = new(() => BuildConfiguredOptions()); |
| | 345 | 44 | | _lazyFunctionsCache = new(() => BuildFunctionsCache()); |
| | 188 | 45 | | } |
| | | 46 | | |
| | | 47 | | public AIAgent CreateAgent<TAgent>() where TAgent : class |
| | 27 | 48 | | => CreateAgentFromType(typeof(TAgent)); |
| | | 49 | | |
| | | 50 | | public AIAgent CreateAgent<TAgent>(Action<AgentFactoryOptions> configure) where TAgent : class |
| | | 51 | | { |
| | 3 | 52 | | ArgumentNullException.ThrowIfNull(configure); |
| | 2 | 53 | | return CreateAgentFromType(typeof(TAgent), configure); |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | public AIAgent CreateAgent(string agentClassName) |
| | | 57 | | { |
| | 226 | 58 | | ArgumentNullException.ThrowIfNull(agentClassName); |
| | | 59 | | |
| | 226 | 60 | | if (!_agentTypeMap.TryGetValue(agentClassName, out var type)) |
| | 2 | 61 | | throw new InvalidOperationException( |
| | 2 | 62 | | $"No agent named '{agentClassName}' is registered. " + |
| | 2 | 63 | | $"Ensure the class is decorated with [NeedlrAiAgent] and registered via " + |
| | 2 | 64 | | $"AddAgent<T>(), AddAgentsFromGenerated(), or the source generator [ModuleInitializer]."); |
| | | 65 | | |
| | 224 | 66 | | return CreateAgentFromType(type); |
| | | 67 | | } |
| | | 68 | | |
| | | 69 | | public AIAgent CreateAgent(string agentClassName, Action<AgentFactoryOptions> configure) |
| | | 70 | | { |
| | 15 | 71 | | ArgumentNullException.ThrowIfNull(agentClassName); |
| | 15 | 72 | | ArgumentNullException.ThrowIfNull(configure); |
| | | 73 | | |
| | 14 | 74 | | if (!_agentTypeMap.TryGetValue(agentClassName, out var type)) |
| | 1 | 75 | | throw new InvalidOperationException( |
| | 1 | 76 | | $"No agent named '{agentClassName}' is registered. " + |
| | 1 | 77 | | $"Ensure the class is decorated with [NeedlrAiAgent] and registered via " + |
| | 1 | 78 | | $"AddAgent<T>(), AddAgentsFromGenerated(), or the source generator [ModuleInitializer]."); |
| | | 79 | | |
| | 13 | 80 | | return CreateAgentFromType(type, configure); |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | public IReadOnlyList<AITool> ResolveTools(Action<AgentFactoryOptions>? configure = null) |
| | | 84 | | { |
| | 4 | 85 | | var agentOptions = new AgentFactoryOptions(); |
| | 4 | 86 | | configure?.Invoke(agentOptions); |
| | 4 | 87 | | return ResolveToolsCore(agentOptions); |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | public IReadOnlyList<AITool> ResolveTools<TAgent>() where TAgent : class |
| | 1 | 91 | | => ResolveToolsFromType(typeof(TAgent)); |
| | | 92 | | |
| | | 93 | | public IReadOnlyList<AITool> ResolveTools<TAgent>(Action<AgentFactoryOptions> configure) where TAgent : class |
| | | 94 | | { |
| | 0 | 95 | | ArgumentNullException.ThrowIfNull(configure); |
| | 0 | 96 | | return ResolveToolsFromType(typeof(TAgent), configure); |
| | | 97 | | } |
| | | 98 | | |
| | | 99 | | private IReadOnlyList<AITool> ResolveToolsFromType( |
| | | 100 | | Type agentType, |
| | | 101 | | Action<AgentFactoryOptions>? additionalConfigure = null) |
| | | 102 | | { |
| | 1 | 103 | | var attr = agentType.GetCustomAttribute<NeedlrAiAgentAttribute>() |
| | 1 | 104 | | ?? throw new InvalidOperationException( |
| | 1 | 105 | | $"'{agentType.Name}' is not decorated with [NeedlrAiAgent]. " + |
| | 1 | 106 | | $"Apply [NeedlrAiAgent] to the class or use ResolveTools(configure) to set options manually."); |
| | | 107 | | |
| | 1 | 108 | | var agentOptions = new AgentFactoryOptions |
| | 1 | 109 | | { |
| | 1 | 110 | | FunctionTypes = attr.FunctionTypes, |
| | 1 | 111 | | FunctionGroups = attr.FunctionGroups, |
| | 1 | 112 | | }; |
| | 1 | 113 | | additionalConfigure?.Invoke(agentOptions); |
| | | 114 | | |
| | 1 | 115 | | return ResolveToolsCore(agentOptions); |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | private IReadOnlyList<AITool> ResolveToolsCore(AgentFactoryOptions agentOptions) |
| | | 119 | | { |
| | 341 | 120 | | var allFunctions = _lazyFunctionsCache.Value; |
| | 341 | 121 | | var applicableTypes = GetApplicableTypes(agentOptions); |
| | 341 | 122 | | var tools = new List<AITool>(); |
| | | 123 | | |
| | 1072 | 124 | | foreach (var type in applicableTypes) |
| | | 125 | | { |
| | 195 | 126 | | if (allFunctions.TryGetValue(type, out var fns)) |
| | | 127 | | { |
| | 191 | 128 | | tools.AddRange(fns); |
| | | 129 | | } |
| | | 130 | | } |
| | | 131 | | |
| | 341 | 132 | | return tools; |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | private AIAgent CreateAgentFromType(Type agentType, Action<AgentFactoryOptions>? additionalConfigure = null) |
| | | 136 | | { |
| | 266 | 137 | | var attr = agentType.GetCustomAttribute<NeedlrAiAgentAttribute>() |
| | 266 | 138 | | ?? throw new InvalidOperationException( |
| | 266 | 139 | | $"'{agentType.Name}' is not decorated with [NeedlrAiAgent]. " + |
| | 266 | 140 | | $"Apply [NeedlrAiAgent] to the class or use CreateAgent(configure) to set options manually."); |
| | | 141 | | |
| | | 142 | | // Build a per-agent resilience plugin if [AgentResilience] is present on this type. |
| | 264 | 143 | | var resAttr = agentType.GetCustomAttribute<AgentResilienceAttribute>(); |
| | 264 | 144 | | IAIAgentBuilderPlugin? perAgentPlugin = resAttr != null && _perAgentResilienceFactory != null |
| | 264 | 145 | | ? _perAgentResilienceFactory(resAttr) |
| | 264 | 146 | | : null; |
| | | 147 | | |
| | 264 | 148 | | return CreateAgentCore( |
| | 264 | 149 | | additionalPlugins: perAgentPlugin != null ? [perAgentPlugin] : null, |
| | 264 | 150 | | configure: opts => |
| | 264 | 151 | | { |
| | 264 | 152 | | // Populate from [NeedlrAiAgent] attribute as defaults |
| | 264 | 153 | | opts.Name = agentType.Name; |
| | 264 | 154 | | opts.Description = attr.Description; |
| | 264 | 155 | | opts.Instructions = attr.Instructions; |
| | 264 | 156 | | opts.FunctionTypes = attr.FunctionTypes; |
| | 264 | 157 | | opts.FunctionGroups = attr.FunctionGroups; |
| | 264 | 158 | | |
| | 264 | 159 | | // Let the caller override any of the above |
| | 264 | 160 | | additionalConfigure?.Invoke(opts); |
| | 279 | 161 | | }); |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | public AIAgent CreateAgent(Action<AgentFactoryOptions>? configure = null) |
| | 72 | 165 | | => CreateAgentCore(additionalPlugins: null, configure: configure); |
| | | 166 | | |
| | | 167 | | private AIAgent CreateAgentCore( |
| | | 168 | | IReadOnlyList<IAIAgentBuilderPlugin>? additionalPlugins, |
| | | 169 | | Action<AgentFactoryOptions>? configure) |
| | | 170 | | { |
| | 336 | 171 | | var agentOptions = new AgentFactoryOptions(); |
| | 336 | 172 | | configure?.Invoke(agentOptions); |
| | | 173 | | |
| | 336 | 174 | | var configuredOpts = _lazyConfiguredOptions.Value; |
| | 336 | 175 | | var tools = (IList<AITool>)ResolveToolsCore(agentOptions); |
| | | 176 | | |
| | 336 | 177 | | var chatClient = configuredOpts.ChatClientFactory?.Invoke(_serviceProvider) |
| | 336 | 178 | | ?? _serviceProvider.GetRequiredService<IChatClient>(); |
| | | 179 | | |
| | | 180 | | // Apply per-agent middleware if configured |
| | 336 | 181 | | if (agentOptions.ChatClientFactory is { } perAgentFactory) |
| | | 182 | | { |
| | 1 | 183 | | chatClient = perAgentFactory(chatClient); |
| | | 184 | | } |
| | | 185 | | |
| | 336 | 186 | | var instructions = agentOptions.Instructions ?? configuredOpts.DefaultInstructions; |
| | | 187 | | |
| | 336 | 188 | | var rawAgent = chatClient.AsAIAgent( |
| | 336 | 189 | | name: agentOptions.Name, |
| | 336 | 190 | | description: agentOptions.Description, |
| | 336 | 191 | | instructions: instructions, |
| | 336 | 192 | | tools: tools, |
| | 336 | 193 | | services: _serviceProvider); |
| | | 194 | | |
| | 336 | 195 | | return ApplyPlugins(rawAgent, additionalPlugins); |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | private AIAgent ApplyPlugins(AIAgent rawAgent, IReadOnlyList<IAIAgentBuilderPlugin>? additionalPlugins) |
| | | 199 | | { |
| | | 200 | | // Merge global plugins with any per-agent additional plugins. |
| | | 201 | | // Per-agent plugins (e.g., [AgentResilience] overrides) are applied after global ones |
| | | 202 | | // so they take the outermost position in the middleware stack. |
| | 336 | 203 | | var allPlugins = additionalPlugins is { Count: > 0 } |
| | 336 | 204 | | ? [.. _plugins, .. additionalPlugins] |
| | 336 | 205 | | : _plugins; |
| | | 206 | | |
| | 336 | 207 | | if (allPlugins.Count == 0) |
| | 284 | 208 | | return rawAgent; |
| | | 209 | | |
| | 52 | 210 | | var builder = new AIAgentBuilder(rawAgent); |
| | 220 | 211 | | foreach (var plugin in allPlugins) |
| | | 212 | | { |
| | 58 | 213 | | plugin.Configure(new AIAgentBuilderPluginOptions { AgentBuilder = builder }); |
| | | 214 | | } |
| | | 215 | | |
| | 52 | 216 | | return builder.Build(_serviceProvider); |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | private IEnumerable<Type> GetApplicableTypes(AgentFactoryOptions agentOptions) |
| | | 220 | | { |
| | 341 | 221 | | bool hasExplicitScope = agentOptions.FunctionTypes != null || agentOptions.FunctionGroups != null; |
| | | 222 | | |
| | 341 | 223 | | if (!hasExplicitScope) |
| | 297 | 224 | | return _functionTypes; |
| | | 225 | | |
| | 44 | 226 | | var types = new List<Type>(); |
| | | 227 | | |
| | 44 | 228 | | if (agentOptions.FunctionTypes != null) |
| | 28 | 229 | | types.AddRange(agentOptions.FunctionTypes); |
| | | 230 | | |
| | 44 | 231 | | if (agentOptions.FunctionGroups != null) |
| | | 232 | | { |
| | 66 | 233 | | foreach (var group in agentOptions.FunctionGroups) |
| | | 234 | | { |
| | 17 | 235 | | if (_functionGroupMap.TryGetValue(group, out var groupTypes)) |
| | 13 | 236 | | types.AddRange(groupTypes); |
| | | 237 | | } |
| | | 238 | | } |
| | | 239 | | |
| | 44 | 240 | | return types.Distinct(); |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | private AgentFrameworkConfigureOptions BuildConfiguredOptions() |
| | | 244 | | { |
| | 152 | 245 | | var opts = new AgentFrameworkConfigureOptions |
| | 152 | 246 | | { |
| | 152 | 247 | | ServiceProvider = _serviceProvider, |
| | 152 | 248 | | }; |
| | | 249 | | |
| | 730 | 250 | | foreach (var callback in _configureCallbacks) |
| | | 251 | | { |
| | 213 | 252 | | callback(opts); |
| | | 253 | | } |
| | | 254 | | |
| | 152 | 255 | | return opts; |
| | | 256 | | } |
| | | 257 | | |
| | | 258 | | private IReadOnlyDictionary<Type, IReadOnlyList<AIFunction>> BuildFunctionsCache() |
| | | 259 | | { |
| | 157 | 260 | | var dict = new Dictionary<Type, IReadOnlyList<AIFunction>>(); |
| | | 261 | | |
| | 1112 | 262 | | foreach (var type in _functionTypes) |
| | | 263 | | { |
| | 399 | 264 | | var functions = BuildFunctionsForType(type); |
| | 399 | 265 | | if (functions.Count > 0) |
| | | 266 | | { |
| | 385 | 267 | | dict[type] = functions; |
| | | 268 | | } |
| | | 269 | | } |
| | | 270 | | |
| | 157 | 271 | | return dict; |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "Reflection branch is unreachable when GeneratedAIFun |
| | | 275 | | [UnconditionalSuppressMessage("TrimAnalysis", "IL2026", Justification = "Reflection fallback path is unreachable in |
| | | 276 | | [UnconditionalSuppressMessage("TrimAnalysis", "IL2067", Justification = "ActivatorUtilities.CreateInstance is only r |
| | | 277 | | private IReadOnlyList<AIFunction> BuildFunctionsForType(Type type) |
| | | 278 | | { |
| | 399 | 279 | | if (_generatedProvider?.TryGetFunctions(type, _serviceProvider, out var generated) == true) |
| | 1 | 280 | | return generated!; |
| | | 281 | | |
| | 398 | 282 | | var isStatic = type.IsAbstract && type.IsSealed; |
| | 398 | 283 | | object? instance = isStatic |
| | 398 | 284 | | ? null |
| | 398 | 285 | | : ActivatorUtilities.CreateInstance(_serviceProvider, type); |
| | | 286 | | |
| | 398 | 287 | | return BuildFunctionsForTypeViaReflection(type, isStatic, instance); |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | [RequiresDynamicCode("Reflection-based AIFunction building requires dynamic code generation.")] |
| | | 291 | | [RequiresUnreferencedCode("Reflection-based AIFunction building requires unreferenced code access.")] |
| | | 292 | | private static IReadOnlyList<AIFunction> BuildFunctionsForTypeViaReflection(Type type, bool isStatic, object? instan |
| | | 293 | | { |
| | 398 | 294 | | var bindingFlags = isStatic |
| | 398 | 295 | | ? BindingFlags.Public | BindingFlags.Static |
| | 398 | 296 | | : BindingFlags.Public | BindingFlags.Instance; |
| | | 297 | | |
| | 398 | 298 | | var functions = type.GetMethods(bindingFlags) |
| | 1874 | 299 | | .Where(m => m.IsDefined(typeof(AgentFunctionAttribute), inherit: true)) |
| | 418 | 300 | | .Select(m => AIFunctionFactory.Create(m, target: instance)) |
| | 398 | 301 | | .ToList(); |
| | | 302 | | |
| | 398 | 303 | | return functions.AsReadOnly(); |
| | | 304 | | } |
| | | 305 | | } |