|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using Microsoft.Extensions.DependencyInjection; |
| 4 | +using Microsoft.SemanticKernel; |
| 5 | +using Microsoft.SemanticKernel.Connectors.OpenAI; |
| 6 | + |
| 7 | +namespace Filtering; |
| 8 | + |
| 9 | +public class ChatClient_AutoFunctionInvocationFiltering(ITestOutputHelper output) : BaseTest(output) |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Shows how to use <see cref="IAutoFunctionInvocationFilter"/>. |
| 13 | + /// </summary> |
| 14 | + [Fact] |
| 15 | + public async Task UsingAutoFunctionInvocationFilter() |
| 16 | + { |
| 17 | + var builder = Kernel.CreateBuilder(); |
| 18 | + |
| 19 | + builder.AddOpenAIChatClient("gpt-4", TestConfiguration.OpenAI.ApiKey); |
| 20 | + |
| 21 | + // This filter outputs information about auto function invocation and returns overridden result. |
| 22 | + builder.Services.AddSingleton<IAutoFunctionInvocationFilter>(new AutoFunctionInvocationFilter(this.Output)); |
| 23 | + |
| 24 | + var kernel = builder.Build(); |
| 25 | + |
| 26 | + var function = KernelFunctionFactory.CreateFromMethod(() => "Result from function", "MyFunction"); |
| 27 | + |
| 28 | + kernel.ImportPluginFromFunctions("MyPlugin", [function]); |
| 29 | + |
| 30 | + var executionSettings = new OpenAIPromptExecutionSettings |
| 31 | + { |
| 32 | + FunctionChoiceBehavior = FunctionChoiceBehavior.Required([function], autoInvoke: true) |
| 33 | + }; |
| 34 | + |
| 35 | + var result = await kernel.InvokePromptAsync("Invoke provided function and return result", new(executionSettings)); |
| 36 | + |
| 37 | + Console.WriteLine(result); |
| 38 | + |
| 39 | + // Output: |
| 40 | + // Request sequence number: 0 |
| 41 | + // Function sequence number: 0 |
| 42 | + // Total number of functions: 1 |
| 43 | + // Result from auto function invocation filter. |
| 44 | + } |
| 45 | + |
| 46 | + /// <summary> |
| 47 | + /// Shows how to get list of function calls by using <see cref="IAutoFunctionInvocationFilter"/>. |
| 48 | + /// </summary> |
| 49 | + [Fact] |
| 50 | + public async Task GetFunctionCallsWithFilterAsync() |
| 51 | + { |
| 52 | + var builder = Kernel.CreateBuilder(); |
| 53 | + |
| 54 | + builder.AddOpenAIChatCompletion("gpt-3.5-turbo-1106", TestConfiguration.OpenAI.ApiKey); |
| 55 | + |
| 56 | + builder.Services.AddSingleton<IAutoFunctionInvocationFilter>(new FunctionCallsFilter(this.Output)); |
| 57 | + |
| 58 | + var kernel = builder.Build(); |
| 59 | + |
| 60 | + kernel.ImportPluginFromFunctions("HelperFunctions", |
| 61 | + [ |
| 62 | + kernel.CreateFunctionFromMethod(() => DateTime.UtcNow.ToString("R"), "GetCurrentUtcTime", "Retrieves the current time in UTC."), |
| 63 | + kernel.CreateFunctionFromMethod((string cityName) => |
| 64 | + cityName switch |
| 65 | + { |
| 66 | + "Boston" => "61 and rainy", |
| 67 | + "London" => "55 and cloudy", |
| 68 | + "Miami" => "80 and sunny", |
| 69 | + "Paris" => "60 and rainy", |
| 70 | + "Tokyo" => "50 and sunny", |
| 71 | + "Sydney" => "75 and sunny", |
| 72 | + "Tel Aviv" => "80 and sunny", |
| 73 | + _ => "31 and snowing", |
| 74 | + }, "GetWeatherForCity", "Gets the current weather for the specified city"), |
| 75 | + ]); |
| 76 | + |
| 77 | + var executionSettings = new OpenAIPromptExecutionSettings |
| 78 | + { |
| 79 | + FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() |
| 80 | + }; |
| 81 | + |
| 82 | + await foreach (var chunk in kernel.InvokePromptStreamingAsync("Check current UTC time and return current weather in Boston city.", new(executionSettings))) |
| 83 | + { |
| 84 | + Console.WriteLine(chunk.ToString()); |
| 85 | + } |
| 86 | + |
| 87 | + // Output: |
| 88 | + // Request #0. Function call: HelperFunctions.GetCurrentUtcTime. |
| 89 | + // Request #0. Function call: HelperFunctions.GetWeatherForCity. |
| 90 | + // The current UTC time is {time of execution}, and the current weather in Boston is 61°F and rainy. |
| 91 | + } |
| 92 | + |
| 93 | + /// <summary>Shows available syntax for auto function invocation filter.</summary> |
| 94 | + private sealed class AutoFunctionInvocationFilter(ITestOutputHelper output) : IAutoFunctionInvocationFilter |
| 95 | + { |
| 96 | + public async Task OnAutoFunctionInvocationAsync(AutoFunctionInvocationContext context, Func<AutoFunctionInvocationContext, Task> next) |
| 97 | + { |
| 98 | + // Example: get function information |
| 99 | + var functionName = context.Function.Name; |
| 100 | + |
| 101 | + // Example: get chat history |
| 102 | + var chatHistory = context.ChatHistory; |
| 103 | + |
| 104 | + // Example: get information about all functions which will be invoked |
| 105 | + var functionCalls = FunctionCallContent.GetFunctionCalls(context.ChatHistory.Last()); |
| 106 | + |
| 107 | + // In function calling functionality there are two loops. |
| 108 | + // Outer loop is "request" loop - it performs multiple requests to LLM until user ask will be satisfied. |
| 109 | + // Inner loop is "function" loop - it handles LLM response with multiple function calls. |
| 110 | + |
| 111 | + // Workflow example: |
| 112 | + // 1. Request to LLM #1 -> Response with 3 functions to call. |
| 113 | + // 1.1. Function #1 called. |
| 114 | + // 1.2. Function #2 called. |
| 115 | + // 1.3. Function #3 called. |
| 116 | + // 2. Request to LLM #2 -> Response with 2 functions to call. |
| 117 | + // 2.1. Function #1 called. |
| 118 | + // 2.2. Function #2 called. |
| 119 | + |
| 120 | + // context.RequestSequenceIndex - it's a sequence number of outer/request loop operation. |
| 121 | + // context.FunctionSequenceIndex - it's a sequence number of inner/function loop operation. |
| 122 | + // context.FunctionCount - number of functions which will be called per request (based on example above: 3 for first request, 2 for second request). |
| 123 | + |
| 124 | + // Example: get request sequence index |
| 125 | + output.WriteLine($"Request sequence index: {context.RequestSequenceIndex}"); |
| 126 | + |
| 127 | + // Example: get function sequence index |
| 128 | + output.WriteLine($"Function sequence index: {context.FunctionSequenceIndex}"); |
| 129 | + |
| 130 | + // Example: get total number of functions which will be called |
| 131 | + output.WriteLine($"Total number of functions: {context.FunctionCount}"); |
| 132 | + |
| 133 | + // Calling next filter in pipeline or function itself. |
| 134 | + // By skipping this call, next filters and function won't be invoked, and function call loop will proceed to the next function. |
| 135 | + await next(context); |
| 136 | + |
| 137 | + // Example: get function result |
| 138 | + var result = context.Result; |
| 139 | + |
| 140 | + // Example: override function result value |
| 141 | + context.Result = new FunctionResult(context.Result, "Result from auto function invocation filter"); |
| 142 | + |
| 143 | + // Example: Terminate function invocation |
| 144 | + context.Terminate = true; |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + /// <summary>Shows how to get list of all function calls per request.</summary> |
| 149 | + private sealed class FunctionCallsFilter(ITestOutputHelper output) : IAutoFunctionInvocationFilter |
| 150 | + { |
| 151 | + public async Task OnAutoFunctionInvocationAsync(AutoFunctionInvocationContext context, Func<AutoFunctionInvocationContext, Task> next) |
| 152 | + { |
| 153 | + var chatHistory = context.ChatHistory; |
| 154 | + var functionCalls = FunctionCallContent.GetFunctionCalls(chatHistory.Last()).ToArray(); |
| 155 | + |
| 156 | + if (functionCalls is { Length: > 0 }) |
| 157 | + { |
| 158 | + foreach (var functionCall in functionCalls) |
| 159 | + { |
| 160 | + output.WriteLine($"Request #{context.RequestSequenceIndex}. Function call: {functionCall.PluginName}.{functionCall.FunctionName}."); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + await next(context); |
| 165 | + } |
| 166 | + } |
| 167 | +} |
0 commit comments