mirror of
https://github.com/microsoft/semantic-kernel.git
synced 2026-10-12 11:19:56 +00:00
.Net: Function Calling Planner: Catch exceptions and output error messages to chat history (#4455)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> Resolves #3224. Exceptions thrown by invoked functions are currently not being caught by the planner. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> This change catches any non-critical exceptions from function invocation, adds the error message into chat history, and lets the planner retry. ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [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 - [x] I didn't break anyone 😄
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.SemanticKernel;
|
||||
|
||||
#pragma warning disable CA1812 // Uninstantiated internal types
|
||||
|
||||
namespace SemanticKernel.IntegrationTests.Fakes;
|
||||
|
||||
internal sealed class ThrowingEmailPluginFake
|
||||
{
|
||||
[KernelFunction, Description("Given an email address and message body, send an email")]
|
||||
public Task<string> SendEmailAsync(
|
||||
[Description("The body of the email message to send.")] string input = "",
|
||||
[Description("The email address to send email to.")] string? email_address = "[email protected]")
|
||||
{
|
||||
// Throw a non-critical exception for testing
|
||||
throw new ArgumentException($"Failed to send email to {email_address}");
|
||||
}
|
||||
|
||||
[KernelFunction, Description("Lookup an email address for a person given a name")]
|
||||
public Task<string> GetEmailAddressAsync(
|
||||
ILogger logger,
|
||||
[Description("The name of the person to email.")] string? input = null)
|
||||
{
|
||||
// Throw a critical exception for testing
|
||||
throw new InvalidProgramException();
|
||||
}
|
||||
|
||||
[KernelFunction, Description("Write a short poem for an e-mail")]
|
||||
public Task<string> WritePoemAsync(
|
||||
[Description("The topic of the poem.")] string input)
|
||||
{
|
||||
return Task.FromResult($"Roses are red, violets are blue, {input} is hard, so is this test.");
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,42 @@ public sealed class FunctionCallingStepwisePlannerTests : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DoesNotThrowWhenPluginFunctionThrowsNonCriticalExceptionAsync()
|
||||
{
|
||||
Kernel kernel = this.InitializeKernel();
|
||||
kernel.ImportPluginFromType<ThrowingEmailPluginFake>("Email");
|
||||
|
||||
var planner = new FunctionCallingStepwisePlanner(
|
||||
new FunctionCallingStepwisePlannerConfig() { MaxIterations = 5 });
|
||||
|
||||
// Act
|
||||
var planResult = await planner.ExecuteAsync(kernel, "Email a poem about cats to [email protected]");
|
||||
|
||||
// Assert - should contain the expected answer & function calls within the maximum iterations
|
||||
Assert.NotNull(planResult);
|
||||
Assert.True(planResult.Iterations > 0);
|
||||
Assert.True(planResult.Iterations <= 5);
|
||||
|
||||
string serializedChatHistory = JsonSerializer.Serialize(planResult.ChatHistory);
|
||||
Assert.Contains("Email_WritePoem", serializedChatHistory, StringComparison.InvariantCultureIgnoreCase);
|
||||
Assert.Contains("Email_SendEmail", serializedChatHistory, StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThrowsWhenPluginFunctionThrowsCriticalExceptionAsync()
|
||||
{
|
||||
Kernel kernel = this.InitializeKernel();
|
||||
kernel.ImportPluginFromType<ThrowingEmailPluginFake>("Email");
|
||||
|
||||
var planner = new FunctionCallingStepwisePlanner(
|
||||
new FunctionCallingStepwisePlannerConfig() { MaxIterations = 5 });
|
||||
|
||||
// Act & Assert
|
||||
// Planner should call ThrowingEmailPluginFake.GetEmailAddressAsync, which throws InvalidProgramException
|
||||
await Assert.ThrowsAsync<InvalidProgramException>(async () => await planner.ExecuteAsync(kernel, "What is Kelly's email address?"));
|
||||
}
|
||||
|
||||
private Kernel InitializeKernel()
|
||||
{
|
||||
OpenAIConfiguration? openAIConfiguration = this._configuration.GetSection("Planners:OpenAI").Get<OpenAIConfiguration>();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -135,8 +136,9 @@ public sealed class FunctionCallingStepwisePlanner
|
||||
var result = (await clonedKernel.InvokeAsync(pluginFunction, arguments, cancellationToken).ConfigureAwait(false)).GetValue<object>();
|
||||
chatHistoryForSteps.AddMessage(AuthorRole.Tool, ParseObjectAsString(result), metadata: new Dictionary<string, object?>(1) { { OpenAIChatMessageContent.ToolIdProperty, functionResponse.Id } });
|
||||
}
|
||||
catch (KernelException)
|
||||
catch (Exception ex) when (!ex.IsCriticalException())
|
||||
{
|
||||
chatHistoryForSteps.AddMessage(AuthorRole.Tool, ex.Message, metadata: new Dictionary<string, object?>(1) { { OpenAIChatMessageContent.ToolIdProperty, functionResponse.Id } });
|
||||
chatHistoryForSteps.AddUserMessage($"Failed to execute function {functionResponse.FullyQualifiedName}. Try something else!");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user