Skip to content

Commit aa62b14

Browse files
authored
.Net: Function Calling Planner: Catch exceptions and output error messages to chat history (microsoft#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 microsoft#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 😄
1 parent b91529a commit aa62b14

3 files changed

Lines changed: 78 additions & 1 deletion

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
using System;
4+
using System.ComponentModel;
5+
using System.Threading.Tasks;
6+
using Microsoft.Extensions.Logging;
7+
using Microsoft.SemanticKernel;
8+
9+
#pragma warning disable CA1812 // Uninstantiated internal types
10+
11+
namespace SemanticKernel.IntegrationTests.Fakes;
12+
13+
internal sealed class ThrowingEmailPluginFake
14+
{
15+
[KernelFunction, Description("Given an email address and message body, send an email")]
16+
public Task<string> SendEmailAsync(
17+
[Description("The body of the email message to send.")] string input = "",
18+
[Description("The email address to send email to.")] string? email_address = "[email protected]")
19+
{
20+
// Throw a non-critical exception for testing
21+
throw new ArgumentException($"Failed to send email to {email_address}");
22+
}
23+
24+
[KernelFunction, Description("Lookup an email address for a person given a name")]
25+
public Task<string> GetEmailAddressAsync(
26+
ILogger logger,
27+
[Description("The name of the person to email.")] string? input = null)
28+
{
29+
// Throw a critical exception for testing
30+
throw new InvalidProgramException();
31+
}
32+
33+
[KernelFunction, Description("Write a short poem for an e-mail")]
34+
public Task<string> WritePoemAsync(
35+
[Description("The topic of the poem.")] string input)
36+
{
37+
return Task.FromResult($"Roses are red, violets are blue, {input} is hard, so is this test.");
38+
}
39+
}

‎dotnet/src/IntegrationTests/Planners/Stepwise/FunctionCallingStepwisePlannerTests.cs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,42 @@ public async Task CanExecuteStepwisePlanAsync(string prompt, string[] expectedFu
7272
}
7373
}
7474

75+
[Fact]
76+
public async Task DoesNotThrowWhenPluginFunctionThrowsNonCriticalExceptionAsync()
77+
{
78+
Kernel kernel = this.InitializeKernel();
79+
kernel.ImportPluginFromType<ThrowingEmailPluginFake>("Email");
80+
81+
var planner = new FunctionCallingStepwisePlanner(
82+
new FunctionCallingStepwisePlannerConfig() { MaxIterations = 5 });
83+
84+
// Act
85+
var planResult = await planner.ExecuteAsync(kernel, "Email a poem about cats to [email protected]");
86+
87+
// Assert - should contain the expected answer & function calls within the maximum iterations
88+
Assert.NotNull(planResult);
89+
Assert.True(planResult.Iterations > 0);
90+
Assert.True(planResult.Iterations <= 5);
91+
92+
string serializedChatHistory = JsonSerializer.Serialize(planResult.ChatHistory);
93+
Assert.Contains("Email_WritePoem", serializedChatHistory, StringComparison.InvariantCultureIgnoreCase);
94+
Assert.Contains("Email_SendEmail", serializedChatHistory, StringComparison.InvariantCultureIgnoreCase);
95+
}
96+
97+
[Fact]
98+
public async Task ThrowsWhenPluginFunctionThrowsCriticalExceptionAsync()
99+
{
100+
Kernel kernel = this.InitializeKernel();
101+
kernel.ImportPluginFromType<ThrowingEmailPluginFake>("Email");
102+
103+
var planner = new FunctionCallingStepwisePlanner(
104+
new FunctionCallingStepwisePlannerConfig() { MaxIterations = 5 });
105+
106+
// Act & Assert
107+
// Planner should call ThrowingEmailPluginFake.GetEmailAddressAsync, which throws InvalidProgramException
108+
await Assert.ThrowsAsync<InvalidProgramException>(async () => await planner.ExecuteAsync(kernel, "What is Kelly's email address?"));
109+
}
110+
75111
private Kernel InitializeKernel()
76112
{
77113
OpenAIConfiguration? openAIConfiguration = this._configuration.GetSection("Planners:OpenAI").Get<OpenAIConfiguration>();

‎dotnet/src/Planners/Planners.OpenAI/Stepwise/FunctionCallingStepwisePlanner.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Copyright (c) Microsoft. All rights reserved.
22

3+
using System;
34
using System.Collections.Generic;
45
using System.ComponentModel;
56
using System.Diagnostics.CodeAnalysis;
@@ -135,8 +136,9 @@ private async Task<FunctionCallingStepwisePlannerResult> ExecuteCoreAsync(
135136
var result = (await clonedKernel.InvokeAsync(pluginFunction, arguments, cancellationToken).ConfigureAwait(false)).GetValue<object>();
136137
chatHistoryForSteps.AddMessage(AuthorRole.Tool, ParseObjectAsString(result), metadata: new Dictionary<string, object?>(1) { { OpenAIChatMessageContent.ToolIdProperty, functionResponse.Id } });
137138
}
138-
catch (KernelException)
139+
catch (Exception ex) when (!ex.IsCriticalException())
139140
{
141+
chatHistoryForSteps.AddMessage(AuthorRole.Tool, ex.Message, metadata: new Dictionary<string, object?>(1) { { OpenAIChatMessageContent.ToolIdProperty, functionResponse.Id } });
140142
chatHistoryForSteps.AddUserMessage($"Failed to execute function {functionResponse.FullyQualifiedName}. Try something else!");
141143
}
142144
}

0 commit comments

Comments
 (0)