-
Notifications
You must be signed in to change notification settings - Fork 4k
.Net: Example of retry logic using Filters #6152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using System.Net; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.SemanticKernel; | ||
using Microsoft.SemanticKernel.Connectors.OpenAI; | ||
|
||
namespace Filtering; | ||
|
||
/// <summary> | ||
/// This example shows how to perform retry with filter and switch to another model as a fallback. | ||
/// </summary> | ||
public class RetryWithFilters(ITestOutputHelper output) : BaseTest(output) | ||
{ | ||
[Fact] | ||
public async Task ChangeModelAndRetryAsync() | ||
{ | ||
// Default and fallback models for demonstration purposes | ||
const string DefaultModelId = "gpt-4"; | ||
const string FallbackModelId = "gpt-3.5-turbo-1106"; | ||
|
||
var builder = Kernel.CreateBuilder(); | ||
|
||
// Add OpenAI chat completion service with invalid API key to force a 401 Unauthorized response | ||
builder.AddOpenAIChatCompletion(modelId: DefaultModelId, apiKey: "invalid_key"); | ||
|
||
// Add OpenAI chat completion service with valid configuration as a fallback | ||
builder.AddOpenAIChatCompletion(modelId: FallbackModelId, apiKey: TestConfiguration.OpenAI.ApiKey); | ||
|
||
// Add retry filter | ||
builder.Services.AddSingleton<IFunctionInvocationFilter>(new RetryFilter(FallbackModelId)); | ||
|
||
// Build kernel | ||
var kernel = builder.Build(); | ||
|
||
// Initially, use "gpt-4" with invalid API key to simulate exception | ||
var executionSettings = new OpenAIPromptExecutionSettings { ModelId = DefaultModelId, MaxTokens = 20 }; | ||
|
||
var result = await kernel.InvokePromptAsync("Hi, can you help me today?", new(executionSettings)); | ||
|
||
Console.WriteLine(result); | ||
|
||
// Output: Of course! I'll do my best to help you. What do you need assistance with? | ||
} | ||
|
||
/// <summary> | ||
/// Filter to change the model and perform retry in case of exception. | ||
/// </summary> | ||
private sealed class RetryFilter(string fallbackModelId) : IFunctionInvocationFilter | ||
{ | ||
public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next) | ||
{ | ||
try | ||
{ | ||
// Try to invoke function | ||
await next(context); | ||
} | ||
// Catch specific exception | ||
catch (HttpOperationException exception) when (exception.StatusCode == HttpStatusCode.Unauthorized) | ||
{ | ||
// Get current execution settings | ||
PromptExecutionSettings executionSettings = context.Arguments.ExecutionSettings![PromptExecutionSettings.DefaultServiceId]; | ||
|
||
// Override settings with fallback model id | ||
executionSettings.ModelId = fallbackModelId; | ||
|
||
// Try to invoke function again | ||
await next(context); | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.