Files
semantic-kernel/dotnet/samples/KernelSyntaxExamples/Example22_OpenApiSkill_AzureKeyVault.cs
T
Roger Barreto 5de1dbac66 .Net: Extract Retry Implementation (#2656)
### Motivation and Context

Reduce the responsibility surface of Semantic Kernel regarding
Resiliency implementations, keeping only the abstractions that can be
delegated and handling by well know resiliency libraries and custom
implementations.

Extract existing logic from Kernel Core to an extension project that can
handle retry logic similar to the prior using Polly Policies.

Resolves #2271
Closes #2271 

⚠️ Small breaking changes.

### Description

This change removes and deprecates the usage of Retry implementations in
our Resiliency namespace with `NullHttpHandlerFactory` implementations.

### Contribution Checklist

- [x] The code builds clean without any errors or warnings
- [x] The PR follows the [SK Contribution
Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [x] All unit tests pass, and I have added new tests where possible
- [ ] I didn't break anyone 😄
2023-09-04 16:51:06 +00:00

94 lines
3.9 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Orchestration;
using Microsoft.SemanticKernel.Skills.OpenAPI.Authentication;
using Microsoft.SemanticKernel.Skills.OpenAPI.Extensions;
using Microsoft.SemanticKernel.Skills.OpenAPI.Skills;
using RepoUtils;
#pragma warning disable CA1861 // Avoid constant arrays as arguments
// ReSharper disable once InconsistentNaming
public static class Example22_OpenApiSkill_AzureKeyVault
{
public static async Task RunAsync()
{
// To run this example, you must register a client application with the Microsoft identity platform.
// Instructions here: https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
var authenticationProvider = new InteractiveMsalAuthenticationProvider(
TestConfiguration.KeyVault.ClientId,
TestConfiguration.KeyVault.TenantId,
new[] { "https://vault.azure.net/.default" },
new Uri("http://localhost"));
await GetSecretFromAzureKeyVaultWithRetryAsync(authenticationProvider);
await AddSecretToAzureKeyVaultAsync(authenticationProvider);
}
public static async Task GetSecretFromAzureKeyVaultWithRetryAsync(InteractiveMsalAuthenticationProvider authenticationProvider)
{
var kernel = new KernelBuilder()
.WithLoggerFactory(ConsoleLogger.LoggerFactory)
.WithRetryBasic(new()
{
MaxRetryCount = 3,
UseExponentialBackoff = true
})
.Build();
var type = typeof(SkillResourceNames);
var resourceName = $"{SkillResourceNames.AzureKeyVault}.openapi.json";
var stream = type.Assembly.GetManifestResourceStream(type, resourceName);
// Import AI Plugin
var skill = await kernel.ImportAIPluginAsync(
SkillResourceNames.AzureKeyVault,
stream!,
new OpenApiSkillExecutionParameters { AuthCallback = authenticationProvider.AuthenticateRequestAsync });
// Add arguments for required parameters, arguments for optional ones can be skipped.
var contextVariables = new ContextVariables();
contextVariables.Set("server-url", TestConfiguration.KeyVault.Endpoint);
contextVariables.Set("secret-name", "<secret-name>");
contextVariables.Set("api-version", "7.0");
// Run
var result = await kernel.RunAsync(contextVariables, skill["GetSecret"]);
Console.WriteLine("GetSecret skill response: {0}", result);
}
public static async Task AddSecretToAzureKeyVaultAsync(InteractiveMsalAuthenticationProvider authenticationProvider)
{
var kernel = new KernelBuilder().WithLoggerFactory(ConsoleLogger.LoggerFactory).Build();
var type = typeof(SkillResourceNames);
var resourceName = $"{SkillResourceNames.AzureKeyVault}.openapi.json";
var stream = type.Assembly.GetManifestResourceStream(type, resourceName);
// Import AI Plugin
var skill = await kernel.ImportAIPluginAsync(
SkillResourceNames.AzureKeyVault,
stream!,
new OpenApiSkillExecutionParameters { AuthCallback = authenticationProvider.AuthenticateRequestAsync });
// Add arguments for required parameters, arguments for optional ones can be skipped.
var contextVariables = new ContextVariables();
contextVariables.Set("server-url", TestConfiguration.KeyVault.Endpoint);
contextVariables.Set("secret-name", "<secret-name>");
contextVariables.Set("api-version", "7.0");
contextVariables.Set("payload", JsonSerializer.Serialize(new { value = "<secret>", attributes = new { enabled = true } }));
// Run
var result = await kernel.RunAsync(contextVariables, skill["SetSecret"]);
Console.WriteLine("SetSecret skill response: {0}", result);
}
}