// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Extensions.AI; using Microsoft.Testing.Platform.AI.Resources; using Microsoft.Testing.Platform.Builder; namespace Microsoft.Testing.Platform.AI; /// /// Extension methods for chat client provider. /// /// /// This API is experimental. It may change, break, or be removed at any time without notice. /// [Experimental("TPEXP", UrlFormat = "https://aka.ms/testingplatform/diagnostics#{0}")] public static class ChatClientProviderExtensions { /// /// Adds a chat client provider to the test application builder. /// /// /// Only one chat client provider can be registered per test application. /// /// The test application builder. /// The factory function to create chat client providers. /// Thrown when or is . /// Thrown when the builder does not support AI extensions or a chat client provider has already been registered. public static void AddChatClientProvider(this ITestApplicationBuilder testApplicationBuilder, Func chatClientProvider) { _ = testApplicationBuilder ?? throw new ArgumentNullException(nameof(testApplicationBuilder)); _ = chatClientProvider ?? throw new ArgumentNullException(nameof(chatClientProvider)); if (testApplicationBuilder is not TestApplicationBuilder builder) { throw new InvalidOperationException(AIExtensionResources.InvalidTestApplicationBuilderTypeForAI); } builder.ChatClientManager.AddChatClientProvider(chatClientProvider); } /// /// Gets a chat client from the service provider. /// /// The service provider. /// The cancellation token. /// A task representing the asynchronous operation that returns an instance of , or when no available provider is registered. /// Thrown when is . public static async Task GetChatClientAsync(this IServiceProvider serviceProvider, CancellationToken cancellationToken) { _ = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); var provider = (IChatClientProvider?)serviceProvider.GetService(typeof(IChatClientProvider)); return provider is null || !provider.IsAvailable ? null : await provider.CreateChatClientAsync(cancellationToken).ConfigureAwait(false); } }