chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:21:23 +08:00
commit b957a53def
5423 changed files with 863745 additions and 0 deletions
@@ -0,0 +1,63 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
namespace DependencyInjection;
// These examples show how to use HttpClient and HttpClientFactory within SK SDK.
public class HttpClient_Registration(ITestOutputHelper output) : BaseTest(output)
{
/// <summary>
/// Demonstrates the "basic usage" approach for HttpClientFactory.
/// </summary>
[Fact]
public void UseBasicRegistrationWithHttpClientFactory()
{
//More details - https://learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#basic-usage
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient();
var kernel = serviceCollection.AddTransient<Kernel>((sp) =>
{
var factory = sp.GetRequiredService<IHttpClientFactory>();
return Kernel.CreateBuilder()
.AddOpenAIChatCompletion(
modelId: TestConfiguration.OpenAI.ChatModelId,
apiKey: TestConfiguration.OpenAI.ApiKey,
httpClient: factory.CreateClient())
.Build();
});
}
/// <summary>
/// Demonstrates the "named clients" approach for HttpClientFactory.
/// </summary>
[Fact]
public void UseNamedRegistrationWitHttpClientFactory()
{
// More details https://learn.microsoft.com/en-us/dotnet/core/extensions/httpclient-factory#named-clients
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient();
//Registration of a named HttpClient.
serviceCollection.AddHttpClient("test-client", (client) =>
{
client.BaseAddress = new Uri("https://api.openai.com/v1/", UriKind.Absolute);
});
var kernel = serviceCollection.AddTransient<Kernel>((sp) =>
{
var factory = sp.GetRequiredService<IHttpClientFactory>();
return Kernel.CreateBuilder()
.AddOpenAIChatCompletion(
modelId: TestConfiguration.OpenAI.ChatModelId,
apiKey: TestConfiguration.OpenAI.ApiKey,
httpClient: factory.CreateClient("test-client"))
.Build();
});
}
}
@@ -0,0 +1,56 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http.Resilience;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
namespace DependencyInjection;
// These examples show how to use HttpClient and HttpClientFactory within SK SDK.
public class HttpClient_Resiliency(ITestOutputHelper output) : BaseTest(output)
{
/// <summary>
/// Demonstrates the usage of the HttpClientFactory with a custom resilience policy.
/// </summary>
[Fact]
public async Task RunAsync()
{
// Create a Kernel with the HttpClient
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information));
builder.Services.ConfigureHttpClientDefaults(c =>
{
// Use a standard resiliency policy, augmented to retry on 401 Unauthorized for this example
c.AddStandardResilienceHandler().Configure(o =>
{
o.Retry.ShouldHandle = args => ValueTask.FromResult(args.Outcome.Result?.StatusCode is HttpStatusCode.Unauthorized);
});
});
builder.Services.AddOpenAIChatCompletion("gpt-4", "BAD_KEY"); // OpenAI settings - you can set the OpenAI.ApiKey to an invalid value to see the retry policy in play
Kernel kernel = builder.Build();
var logger = kernel.LoggerFactory.CreateLogger(typeof(HttpClient_Resiliency));
const string Question = "How do I add a standard resilience handler in IHttpClientBuilder??";
logger.LogInformation("Question: {Question}", Question);
// The call to OpenAI will fail and be retried a few times before eventually failing.
// Retrying can overcome transient problems and thus improves resiliency.
try
{
// The InvokePromptAsync call will issue a request to OpenAI with an invalid API key.
// That will cause the request to fail with an HTTP status code 401. As the resilience
// handler is configured to retry on 401s, it'll reissue the request, and will do so
// multiple times until it hits the default retry limit, at which point this operation
// will throw an exception in response to the failure. All of the retries will be visible
// in the logging out to the console.
logger.LogInformation("Answer: {Result}", await kernel.InvokePromptAsync(Question));
}
catch (Exception ex)
{
logger.LogInformation("Error: {Message}", ex.Message);
}
}
}
@@ -0,0 +1,78 @@
// Copyright (c) Microsoft. All rights reserved.
// ==========================================================================================================
// The easier way to instantiate the Semantic Kernel is to use KernelBuilder.
// You can access the builder using Kernel.CreateBuilder().
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Plugins.Core;
namespace DependencyInjection;
public class Kernel_Building(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public void BuildKernelUsingServiceCollection()
{
// For greater flexibility and to incorporate arbitrary services, KernelBuilder.Services
// provides direct access to an underlying IServiceCollection.
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information))
.AddHttpClient()
.AddAzureOpenAIChatCompletion(
deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName,
endpoint: TestConfiguration.AzureOpenAI.Endpoint,
apiKey: TestConfiguration.AzureOpenAI.ApiKey,
modelId: TestConfiguration.AzureOpenAI.ChatModelId);
Kernel kernel2 = builder.Build();
}
[Fact]
public void BuildKernelUsingServiceProvider()
{
// Every call to KernelBuilder.Build creates a new Kernel instance, with a new service provider
// and a new plugin collection.
var builder = Kernel.CreateBuilder();
Debug.Assert(!ReferenceEquals(builder.Build(), builder.Build()));
// KernelBuilder provides a convenient API for creating Kernel instances. However, it is just a
// wrapper around a service collection, ultimately constructing a Kernel
// using the public constructor that's available for anyone to use directly if desired.
var services = new ServiceCollection();
services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information));
services.AddHttpClient();
services.AddAzureOpenAIChatCompletion(
deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName,
endpoint: TestConfiguration.AzureOpenAI.Endpoint,
apiKey: TestConfiguration.AzureOpenAI.ApiKey,
modelId: TestConfiguration.AzureOpenAI.ChatModelId);
Kernel kernel4 = new(services.BuildServiceProvider());
// Kernels can also be constructed and resolved via such a dependency injection container.
services.AddTransient<Kernel>();
Kernel kernel5 = services.BuildServiceProvider().GetRequiredService<Kernel>();
}
[Fact]
public void BuildKernelUsingServiceCollectionExtension()
{
// In fact, the AddKernel method exists to simplify this, registering a singleton KernelPluginCollection
// that can be populated automatically with all IKernelPlugins registered in the collection, and a
// transient Kernel that can then automatically be constructed from the service provider and resulting
// plugins collection.
var services = new ServiceCollection();
services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information));
services.AddHttpClient();
services.AddKernel().AddAzureOpenAIChatCompletion(
deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName,
endpoint: TestConfiguration.AzureOpenAI.Endpoint,
apiKey: TestConfiguration.AzureOpenAI.ApiKey,
modelId: TestConfiguration.AzureOpenAI.ChatModelId);
services.AddSingleton<KernelPlugin>(sp => KernelPluginFactory.CreateFromType<TimePlugin>(serviceProvider: sp));
services.AddSingleton<KernelPlugin>(sp => KernelPluginFactory.CreateFromType<HttpPlugin>(serviceProvider: sp));
Kernel kernel6 = services.BuildServiceProvider().GetRequiredService<Kernel>();
}
}
@@ -0,0 +1,53 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
namespace DependencyInjection;
// The following examples show how to use SK SDK in applications using DI/IoC containers.
public class Kernel_Injecting(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task RunAsync()
{
ServiceCollection collection = new();
collection.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information));
collection.AddOpenAIChatCompletion(TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey);
collection.AddSingleton<Kernel>();
// Registering class that uses Kernel to execute a plugin
collection.AddTransient<KernelClient>();
// Create a service provider for resolving registered services
await using ServiceProvider serviceProvider = collection.BuildServiceProvider();
//If an application follows DI guidelines, the following line is unnecessary because DI will inject an instance of the KernelClient class to a class that references it.
//DI container guidelines - https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#recommendations
KernelClient kernelClient = serviceProvider.GetRequiredService<KernelClient>();
//Execute the function
await kernelClient.SummarizeAsync("What's the tallest building in South America?");
}
/// <summary>
/// Class that uses/references Kernel.
/// </summary>
private sealed class KernelClient(Kernel kernel, ILoggerFactory loggerFactory)
{
private readonly Kernel _kernel = kernel;
private readonly ILogger _logger = loggerFactory.CreateLogger(nameof(KernelClient));
public async Task SummarizeAsync(string ask)
{
string folder = RepoFiles.SamplePluginsPath();
var summarizePlugin = this._kernel.ImportPluginFromPromptDirectory(Path.Combine(folder, "SummarizePlugin"));
var result = await this._kernel.InvokeAsync(summarizePlugin["Summarize"], new() { ["input"] = ask });
this._logger.LogWarning("Result - {0}", result.GetValue<string>());
}
}
}