|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System.Collections.Generic; |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.SemanticKernel; |
| 6 | +using Microsoft.SemanticKernel.Services; |
| 7 | +using Xunit; |
| 8 | + |
| 9 | +namespace SemanticKernel.UnitTests.Functions; |
| 10 | + |
| 11 | +public class CustomAIServiceSelectorTests |
| 12 | +{ |
| 13 | + [Fact] |
| 14 | + public void ItGetsAIServiceUsingArbitraryAttributes() |
| 15 | + { |
| 16 | + // Arrange |
| 17 | + IKernelBuilder builder = Kernel.CreateBuilder(); |
| 18 | + builder.Services.AddKeyedSingleton<IAIService>("service1", new AIService()); |
| 19 | + Kernel kernel = builder.Build(); |
| 20 | + |
| 21 | + var function = kernel.CreateFunctionFromPrompt("Hello AI"); |
| 22 | + var serviceSelector = new CustomAIServiceSelector(); |
| 23 | + |
| 24 | + // Act |
| 25 | + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService<IAIService>(kernel, function, new KernelArguments()); |
| 26 | + |
| 27 | + // Assert |
| 28 | + Assert.NotNull(aiService); |
| 29 | + Assert.True(aiService.Attributes?.ContainsKey("Key1")); |
| 30 | + Assert.Null(defaultExecutionSettings); |
| 31 | + } |
| 32 | + |
| 33 | + private sealed class CustomAIServiceSelector : IAIServiceSelector |
| 34 | + { |
| 35 | +#pragma warning disable CS8769 // Nullability of reference types in value doesn't match target type. Cannot use [NotNullWhen] because of access to internals from abstractions. |
| 36 | + bool IAIServiceSelector.TrySelectAIService<T>(Kernel kernel, KernelFunction function, KernelArguments arguments, out T? service, out PromptExecutionSettings? serviceSettings) where T : class |
| 37 | + { |
| 38 | + var keyedService = (kernel.Services as IKeyedServiceProvider)?.GetKeyedService<T>("service1"); |
| 39 | + if (keyedService is null || keyedService.Attributes is null) |
| 40 | + { |
| 41 | + service = null; |
| 42 | + serviceSettings = null; |
| 43 | + return false; |
| 44 | + } |
| 45 | + |
| 46 | + service = keyedService.Attributes.ContainsKey("Key1") ? keyedService as T : null; |
| 47 | + serviceSettings = null; |
| 48 | + return true; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private sealed class AIService : IAIService |
| 53 | + { |
| 54 | + public IReadOnlyDictionary<string, object?> Attributes => this._attributes; |
| 55 | + |
| 56 | + public AIService() |
| 57 | + { |
| 58 | + this._attributes = new Dictionary<string, object?>(); |
| 59 | + this._attributes.Add("Key1", "Value1"); |
| 60 | + } |
| 61 | + |
| 62 | + private readonly Dictionary<string, object?> _attributes; |
| 63 | + } |
| 64 | +} |
0 commit comments