| | | 1 | | using Microsoft.Extensions.AI; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | |
| | | 4 | | namespace NexusLabs.Needlr.AgentFramework.Iterative; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Lazily builds and caches the configured <see cref="IChatClient"/> using the same |
| | | 8 | | /// factory chain as <see cref="AgentFactory"/>. This ensures the iterative loop gets |
| | | 9 | | /// the same middleware stack (diagnostics, token budget, etc.) without creating a |
| | | 10 | | /// separate agent. |
| | | 11 | | /// </summary> |
| | | 12 | | [DoNotAutoRegister] |
| | | 13 | | internal sealed class ChatClientAccessor : IChatClientAccessor |
| | | 14 | | { |
| | | 15 | | private readonly IServiceProvider _serviceProvider; |
| | | 16 | | private readonly IReadOnlyList<Action<AgentFrameworkConfigureOptions>> _configureCallbacks; |
| | | 17 | | private readonly Lazy<IChatClient> _lazyChatClient; |
| | | 18 | | |
| | 43 | 19 | | internal ChatClientAccessor( |
| | 43 | 20 | | IServiceProvider serviceProvider, |
| | 43 | 21 | | IReadOnlyList<Action<AgentFrameworkConfigureOptions>> configureCallbacks) |
| | | 22 | | { |
| | 43 | 23 | | _serviceProvider = serviceProvider; |
| | 43 | 24 | | _configureCallbacks = configureCallbacks; |
| | 43 | 25 | | _lazyChatClient = new Lazy<IChatClient>(BuildChatClient); |
| | 43 | 26 | | } |
| | | 27 | | |
| | 37 | 28 | | public IChatClient ChatClient => _lazyChatClient.Value; |
| | | 29 | | |
| | | 30 | | private IChatClient BuildChatClient() |
| | | 31 | | { |
| | 36 | 32 | | var options = new AgentFrameworkConfigureOptions |
| | 36 | 33 | | { |
| | 36 | 34 | | ServiceProvider = _serviceProvider, |
| | 36 | 35 | | }; |
| | | 36 | | |
| | 164 | 37 | | foreach (var configure in _configureCallbacks) |
| | | 38 | | { |
| | 46 | 39 | | configure(options); |
| | | 40 | | } |
| | | 41 | | |
| | 36 | 42 | | return options.ChatClientFactory?.Invoke(_serviceProvider) |
| | 36 | 43 | | ?? _serviceProvider.GetRequiredService<IChatClient>(); |
| | | 44 | | } |
| | | 45 | | } |