|
| 1 | +using System.Text.Json; |
| 2 | +using Microsoft.Agents.AI; |
| 3 | +using Microsoft.Extensions.AI; |
| 4 | +using Microsoft.Extensions.Configuration; |
| 5 | +using Microsoft.Extensions.DependencyInjection; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | + |
| 8 | +namespace Devlooped.Agents.AI; |
| 9 | + |
| 10 | +public sealed partial class ConfigurableAIAgent : AIAgent, IDisposable |
| 11 | +{ |
| 12 | + readonly IServiceProvider services; |
| 13 | + readonly IConfiguration configuration; |
| 14 | + readonly string section; |
| 15 | + readonly string name; |
| 16 | + readonly ILogger logger; |
| 17 | + readonly Action<string, ChatClientAgentOptions>? configure; |
| 18 | + IDisposable reloadToken; |
| 19 | + ChatClientAgent agent; |
| 20 | + IChatClient chat; |
| 21 | + ChatClientAgentOptions options; |
| 22 | + |
| 23 | + public ConfigurableAIAgent(IServiceProvider services, string section, string name, Action<string, ChatClientAgentOptions>? configure) |
| 24 | + { |
| 25 | + if (section.Contains('.')) |
| 26 | + throw new ArgumentException("Section separator must be ':', not '.'"); |
| 27 | + |
| 28 | + this.services = Throw.IfNull(services); |
| 29 | + this.configuration = services.GetRequiredService<IConfiguration>(); |
| 30 | + this.logger = services.GetRequiredService<ILogger<ConfigurableAIAgent>>(); |
| 31 | + this.section = Throw.IfNullOrEmpty(section); |
| 32 | + this.name = Throw.IfNullOrEmpty(name); |
| 33 | + this.configure = configure; |
| 34 | + |
| 35 | + (agent, options, chat) = Configure(configuration.GetRequiredSection(section)); |
| 36 | + reloadToken = configuration.GetReloadToken().RegisterChangeCallback(OnReload, state: null); |
| 37 | + } |
| 38 | + |
| 39 | + public void Dispose() => reloadToken?.Dispose(); |
| 40 | + |
| 41 | + public override object? GetService(Type serviceType, object? serviceKey = null) => serviceType switch |
| 42 | + { |
| 43 | + Type t when t == typeof(ChatClientAgentOptions) => options, |
| 44 | + Type t when t == typeof(IChatClient) => chat, |
| 45 | + _ => agent.GetService(serviceType, serviceKey) |
| 46 | + }; |
| 47 | + |
| 48 | + public override string Id => agent.Id; |
| 49 | + public override string? Description => agent.Description; |
| 50 | + public override string DisplayName => agent.DisplayName; |
| 51 | + public override string? Name => agent.Name; |
| 52 | + public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) |
| 53 | + => agent.DeserializeThread(serializedThread, jsonSerializerOptions); |
| 54 | + public override AgentThread GetNewThread() => agent.GetNewThread(); |
| 55 | + public override Task<AgentRunResponse> RunAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) |
| 56 | + => agent.RunAsync(messages, thread, options, cancellationToken); |
| 57 | + public override IAsyncEnumerable<AgentRunResponseUpdate> RunStreamingAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default) |
| 58 | + => agent.RunStreamingAsync(messages, thread, options, cancellationToken); |
| 59 | + |
| 60 | + (ChatClientAgent, ChatClientAgentOptions, IChatClient) Configure(IConfigurationSection configSection) |
| 61 | + { |
| 62 | + var options = configSection.Get<AgentClientOptions>(); |
| 63 | + options?.Name ??= name; |
| 64 | + |
| 65 | + // If there was a custom id, we must validate it didn't change since that's not supported. |
| 66 | + if (configuration[$"{section}:name"] is { } newname && newname != name) |
| 67 | + throw new InvalidOperationException($"The name of a configured agent cannot be changed at runtime. Expected '{name}' but was '{newname}'."); |
| 68 | + |
| 69 | + var client = services.GetRequiredKeyedService<IChatClient>(options?.Client |
| 70 | + ?? throw new InvalidOperationException($"A client must be specified for agent '{name}' in configuration section '{section}'.")); |
| 71 | + |
| 72 | + var chat = configSection.GetSection("options").Get<ChatOptions>(); |
| 73 | + if (chat is not null) |
| 74 | + options.ChatOptions = chat; |
| 75 | + |
| 76 | + configure?.Invoke(name, options); |
| 77 | + |
| 78 | + LogConfigured(name); |
| 79 | + |
| 80 | + return (new ChatClientAgent(client, options, services.GetRequiredService<ILoggerFactory>(), services), options, client); |
| 81 | + } |
| 82 | + |
| 83 | + void OnReload(object? state) |
| 84 | + { |
| 85 | + var configSection = configuration.GetRequiredSection(section); |
| 86 | + reloadToken?.Dispose(); |
| 87 | + chat?.Dispose(); |
| 88 | + (agent, options, chat) = Configure(configSection); |
| 89 | + reloadToken = configuration.GetReloadToken().RegisterChangeCallback(OnReload, state: null); |
| 90 | + } |
| 91 | + |
| 92 | + [LoggerMessage(LogLevel.Information, "AIAgent '{Id}' configured.")] |
| 93 | + private partial void LogConfigured(string id); |
| 94 | + |
| 95 | + class AgentClientOptions : ChatClientAgentOptions |
| 96 | + { |
| 97 | + public required string Client { get; set; } |
| 98 | + } |
| 99 | +} |
0 commit comments